package com.ghy.web.controller.system;

import com.ghy.common.annotation.Log;
import com.ghy.common.constant.UserConstants;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.enums.BusinessType;
import com.ghy.common.json.JSONObject;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.system.domain.SysArea;
import com.ghy.system.service.ISysAreaService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 区域信息
 *
 * @author clunt
 */
@Controller
@RequestMapping("/system/area")
public class SysAreaController extends BaseController {

    private String prefix = "system/area";

    @Resource
    private ISysAreaService sysAreaService;

//    @RequiresPermissions("system:area:list")
    @PostMapping("/list")
    @ResponseBody
    public AjaxResult list(SysArea sysArea)
    {
        try {
            return AjaxResult.success(sysAreaService.selectSysAreaList(sysArea));
        }catch (Exception e){
            logger.error(ExceptionUtil.getExceptionMessage(e));
            return AjaxResult.error(e.getMessage());
        }

    }

    @PostMapping("/app/all")
    @ResponseBody
    public Object appAll(@RequestBody SysArea sysArea)
    {
        try {
            // 第一层 省
            List<SysArea> provinceAreas = sysAreaService.selectSysAreaList(sysArea);
            for (SysArea provinceArea : provinceAreas) {
                logger.info("进行中的省 : " + provinceArea.getAreaName());
                SysArea param1 = new SysArea();
                param1.setParentCode(provinceArea.getAreaCode());
                // 第二层 市
                List<SysArea> cityAreas = sysAreaService.selectSysAreaList(param1);
                for (SysArea cityArea : cityAreas){
                    SysArea param2 = new SysArea();
                    param2.setParentCode(cityArea.getAreaCode());
                    // 第三层 区
                    List<SysArea> countryAreas = sysAreaService.selectSysAreaList(param2);
                    for (SysArea countryArea : countryAreas){
                        SysArea param3 = new SysArea();
                        param3.setParentCode(countryArea.getAreaCode());
                        // 第三层 街道
                        List<SysArea> streetAreas = sysAreaService.selectSysAreaList(param3);
                        countryArea.setChild(streetAreas);
                    }
                    cityArea.setChild(countryAreas);
                }
                provinceArea.setChild(cityAreas);
            }
            return provinceAreas;
        }catch (Exception e){
            logger.error(ExceptionUtil.getExceptionMessage(e));
            return AjaxResult.error(e.getMessage());
        }

    }

    @PostMapping("/app/list")
    @ResponseBody
    public AjaxResult appList(@RequestBody SysArea sysArea)
    {
        try {
            return AjaxResult.success(sysAreaService.selectSysAreaList(sysArea));
        }catch (Exception e){
            logger.error(ExceptionUtil.getExceptionMessage(e));
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 新增保存区域
     */
    @Log(title = "区域管理", businessType = BusinessType.INSERT)
//    @RequiresPermissions("system:area:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated @RequestBody SysArea sysArea)
    {
        if (UserConstants.AREA_CODE_NOT_UNIQUE.equals(sysAreaService.checkAreaCodeUnique(sysArea)))
        {
            return error("新增区域'" + sysArea.getAreaName() + "'失败，区域编码已存在");
        }
        sysArea.setCreateBy(getLoginName());
        return toAjax(sysAreaService.insertSysArea(sysArea));
    }

    /**
     * 修改保存区域
     */
    @Log(title = "区域管理", businessType = BusinessType.UPDATE)
//    @RequiresPermissions("system:area:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated @RequestBody SysArea sysArea)
    {
        if (UserConstants.AREA_CODE_NOT_UNIQUE.equals(sysAreaService.checkAreaCodeUnique(sysArea)))
        {
            return error("修改区域'" + sysArea.getAreaName() + "'失败，区域编码已存在");
        }
        sysArea.setUpdateBy(getLoginName());
        return toAjax(sysAreaService.updateSysArea(sysArea));
    }

    /**
     * 删除
     */
    @Log(title = "区域管理", businessType = BusinessType.DELETE)
//    @RequiresPermissions("system:area:remove")
    @GetMapping("/remove/{areaId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("areaId") Long areaId)
    {
        if (sysAreaService.selectAreaCount(areaId) > 0)
        {
            return AjaxResult.warn("存在下级区域,不允许删除");
        }
        return toAjax(sysAreaService.deleteSysAreaByIds(areaId.toString()));
    }


    @RequiresPermissions("system:area:view")
    @GetMapping()
    public String area() {
        return prefix + "/area";
    }


    /**
     * 新增下级区域
     */
    @GetMapping("/add/{parentCode}")
    public String add(@PathVariable("parentCode") String parentCode, ModelMap mmap) {
        mmap.put("sysCode", sysAreaService.selectByAreaCode(parentCode));
        return prefix + "/add";
    }

    /**
     * 修改区域
     */
    @RequiresPermissions("system:area:edit")
    @GetMapping("/edit/{areaId}")
    public String edit(@PathVariable("areaId") Long areaId, ModelMap mmap) {
        SysArea sysArea = sysAreaService.selectById(areaId);
        mmap.put("sysArea", sysArea);
        return prefix + "/edit";
    }


}
