/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.platform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.Area;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.R;
import com.yami.shop.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * 地区信息管理实现
 *
 * @author lgh
 * @version 1.0.0
 * @since 2018-10-26
 */
@RestController
@RequestMapping("/admin/area")
public class AreaController {

    @Autowired
    private AreaService areaService;

    /**
     * 分页获取
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('admin:area:page')")
    public R<IPage<Area>> page(Area area, PageParam<Area> page) {
        IPage<Area> sysUserPage = areaService.page(page, new LambdaQueryWrapper<Area>());
        return R.SUCCESS(sysUserPage);
    }

    /**
     * 获取省市
     */
    @GetMapping("/list")
    @PreAuthorize("@pms.hasPermission('admin:area:list')")
    public R<List<Area>> list(Area area) {
        List<Area> areas = areaService.list(new LambdaQueryWrapper<Area>()
                .like(area.getAreaName() != null, Area::getAreaName, area.getAreaName())
                .eq(Objects.nonNull(area.getParentId()), Area::getParentId, area.getAreaId())
                .lt(!Objects.isNull(area.getMaxGrade()),Area::getLevel,area.getMaxGrade())
        );
        return R.SUCCESS(areas);
    }

    /**
     * 通过父级id获取区域列表
     */
    @GetMapping("/listByPid")
    public R<List<Area>> listByPid(Long pid) {
        List<Area> list = areaService.listByPid(pid);
        return R.SUCCESS(list);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("@pms.hasPermission('admin:area:info')")
    public R<Area> info(@PathVariable("id") Long id) {
        Area area = areaService.getById(id);
        return R.SUCCESS(area);
    }

    /**
     * 保存
     */
    @PostMapping
    @PreAuthorize("@pms.hasPermission('admin:area:save')")
    public R<Void> save(@Valid @RequestBody Area area) {
        if(area.getCode() == null){
            Random random = new Random();
            int randomNumber = 10000 + random.nextInt(90000);
            area.setCode((long) randomNumber);
        }
        if (area.getParentId() != null && !Objects.equals(area.getParentId(), 0L)) {
            Area parentArea = areaService.getById(area.getParentId());
            area.setLevel(parentArea.getLevel() + 1);
            area.setParentId(parentArea.getCode());
            areaService.removeAreaCacheByParentId(area.getParentId());
        }
        areaService.removeAreaListCache();
        areaService.save(area);
        return R.SUCCESS();
    }

    /**
     * 修改
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('admin:area:update')")
    public R<Void> update(@Valid @RequestBody Area area) {
        areaService.updateById(area);
        areaService.removeAreaCacheByParentId(area.getParentId());
        areaService.removeAreaListCache();
        return R.SUCCESS();
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('admin:area:delete')")
    public R<Void> delete(@PathVariable Long id) {
        if (areaService.count(new LambdaQueryWrapper<Area>().eq(Area::getParentId,id)) > 0) {
            throw new GlobalException("请先删除子地区");
        }

        Area area = areaService.getById(id);
        areaService.removeById(id);
        areaService.removeAreaCacheByParentId(area.getParentId());
        areaService.removeAreaListCache();
        return R.SUCCESS();
    }

}
