package cn.estsh.i3plus.core.apiservice.controller.busi;

import cn.estsh.i3plus.core.api.iservice.busi.ISysDictionaryService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.StringTool;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.bean.BaseConstWords;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SessionUser;
import cn.estsh.i3plus.pojo.platform.bean.SysDictionary;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description : 字典管理服务
 * @Reference :
 * @Author : yunhao
 * @Date : 2018-10-28 23:54
 * @Modify :
 **/
@RestController
@Api(description = "字典管理服务")
@RequestMapping(PlatformConstWords.BASE_URL +"/sys-dictionary")
public class SysDictionaryController extends CoreBaseController{
    public static final Logger LOGGER = LoggerFactory.getLogger(SysConfigController.class);

    @Autowired
    public ISysDictionaryService sysDictionaryService;

    @PostMapping("/insert")
    @ApiOperation(value = "添加字典",notes = "添加字典")
    public ResultBean insertSysDictionary(SysDictionary sysDictionary) {
        try {
            // 条件验证
            ValidatorBean.beginValid(sysDictionary)
                    .notNull("name",sysDictionary.getName())
                    .notNull("dictionarySoftType",sysDictionary.getDictionarySoftType())
                    .notNull("dictionaryCode",sysDictionary.getDictionaryCode())
                    .notNull("dictionaryValue",sysDictionary.getDictionaryValue());

            //新增初始化
            sysDictionary.setIsDefault(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());

            sysDictionaryService.insertSysDictionary(sysDictionary);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改字典",notes = "修改字典")
    public ResultBean updateSysDictionary(SysDictionary sysDictionary) {
        try {
            // 登录用户
            SessionUser user = AuthUtil.getSessionUser();

            // 条件验证
            ValidatorBean.beginValid(sysDictionary)
                    .notNull("name",sysDictionary.getName())
                    .notNull("dictionarySoftType",sysDictionary.getDictionarySoftType())
                    .notNull("dictionaryCode",sysDictionary.getDictionaryCode())
                    .notNull("dictionaryValue",sysDictionary.getDictionaryValue());

            //修改初始化
            ConvertBean.modelUpdate(sysDictionary,user);

            sysDictionaryService.updateSysDictionary(sysDictionary);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据id删除字典",notes = "根据id删除字典")
    public ResultBean updateSysDictionary(@PathVariable("id") String idStr) {
        try {
            // 条件验证
            ValidatorBean.checkNotNull(idStr,"id不能为空");
            SysDictionary sysDictionary = sysDictionaryService.getSysDictionaryById(Long.parseLong(idStr));
            if(sysDictionary == null){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("字典不存在")
                        .setErrorSolution("请重新选择")
                        .build();
            }else if(sysDictionary.getIsDefault().intValue() == CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("默认字典不能删除")
                        .setErrorSolution("请重新选择")
                        .build();
            }

            sysDictionaryService.deleteSysDictionaryById(Long.parseLong(idStr));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "查询所有字典", notes = "查询所有字典")
    public ResultBean findSysDictionaryAll() {
        try {
            List<SysDictionary> sysDictionaryList = sysDictionaryService.listSysDictionary();
            return ResultBean.success("操作成功").setResultList(sysDictionaryList)
                            .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/get/{id}")
    @ApiOperation(value = "根据id查询字典", notes = "根据id查询字典")
    public ResultBean getSysDictionaryById(@PathVariable("id") String id) {
        try {
            // 条件判断
            ValidatorBean.checkNotNull(id,"id不能为空");

            SysDictionary sysDictionary = sysDictionaryService.getSysDictionaryById(Long.parseLong(id));
            if (sysDictionary != null) {
                return ResultBean.success("操作成功").setResultObject(sysDictionary).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }else {
                return ResultBean.fail("字典不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/find/{softType}/{code}")
    @ApiOperation(value = "根据微服务与父级code查询字典项", notes = "根据微服务与父级code查询字典项")
    public ResultBean findSysDictionaryByParentCode(@PathVariable("softType")Integer softType,@PathVariable("code") String code) {
        try {
            List<SysDictionary> sysDictionaryList = sysDictionaryService.findSysDictionaryBySoftTypeAndParentCode(softType,code);
            return ResultBean.success("操作成功").setResultList(sysDictionaryList).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/find/user-info")
    @ApiOperation(value = "查询跟用户相关所有字典")
    public ResultBean findSysDictionaryUserInfo() {
        try {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("1", sysDictionaryService.findSysDictionaryBySoftTypeAndParentCode(
                    CommonEnumUtil.SOFT_TYPE.CORE.getValue(), BaseConstWords.DICTIONARY_SEX));
            resultMap.put("2", sysDictionaryService.findSysDictionaryBySoftTypeAndParentCode(
                    CommonEnumUtil.SOFT_TYPE.CORE.getValue(), BaseConstWords.DICTIONARY_FILE_TYPE));
            resultMap.put("3", sysDictionaryService.findSysDictionaryBySoftTypeAndParentCode(
                    CommonEnumUtil.SOFT_TYPE.CORE.getValue(), BaseConstWords.DICTIONARY_MARRIAGE));
            resultMap.put("4", sysDictionaryService.findSysDictionaryBySoftTypeAndParentCode(
                    CommonEnumUtil.SOFT_TYPE.CORE.getValue(), BaseConstWords.DICTIONARY_EDUCATION));
            resultMap.put("5", sysDictionaryService.findSysDictionaryBySoftTypeAndParentCode(
                    CommonEnumUtil.SOFT_TYPE.CORE.getValue(), BaseConstWords.DICTIONARY_NATIONALITY));
            resultMap.put("6", sysDictionaryService.findSysDictionaryBySoftTypeAndParentCode(
                    CommonEnumUtil.SOFT_TYPE.CORE.getValue(), BaseConstWords.DICTIONARY_CERTIFICATE_TYPE));
            resultMap.put("7", sysDictionaryService.findSysDictionaryBySoftTypeAndParentCode(
                    CommonEnumUtil.SOFT_TYPE.CORE.getValue(), BaseConstWords.DICTIONARY_EMPLOYEE_GRADE));
            resultMap.put("8", sysDictionaryService.findSysDictionaryBySoftTypeAndParentCode(
                    CommonEnumUtil.SOFT_TYPE.CORE.getValue(), BaseConstWords.DICTIONARY_POLITICAL_STATUS));
            resultMap.put("9", sysDictionaryService.findSysDictionaryBySoftTypeAndParentCode(
                    CommonEnumUtil.SOFT_TYPE.CORE.getValue(), BaseConstWords.DICTIONARY_EMPLOYEE_TYPE));

            return ResultBean.success("操作成功").setResultMap(resultMap).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping("/query")
    @ApiOperation(value = "字典复杂查询，分页，排序",notes = "字典复杂查询，分页，排序")
    public ResultBean querySysDictionaryByPager(SysDictionary sysDictionary, Pager pager) {
        try {
            ListPager sysDictionaryListPager = sysDictionaryService.querySysDictionaryByPager(sysDictionary,pager);
            return  ResultBean.success("操作成功").setListPager(sysDictionaryListPager).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ResultBean.fail(e).setCode(ImppExceptionEnum.SYSTEM_EXCEPTION.getCode());
        }
    }

    @GetMapping("/find-top")
    @ApiOperation(value = "查询顶级字典项",notes = "查询顶级字典项")
    public ResultBean findSysDictionaryByTop() {
        try {
            List<SysDictionary> sysDictionaryList = sysDictionaryService.findSysDictionaryByTop();
            return  ResultBean.success("操作成功").setResultList(sysDictionaryList).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping("/batch-delete")
    @ApiOperation(value = "批量删除消息",notes = "批量删除消息")
    public ResultBean deleteSysDictionaryByIds(String[] ids){
        try{
            if(ids.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要删除的资源。")
                        .build();
            }
            sysDictionaryService.deleteSysDictionaryByIds(StringTool.getArrayLong(ids));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping("/default/{id}")
    @ApiOperation(value = "设置默认字典值",notes = "根据id设置默认字典值")
    public ResultBean updateSysDictionaryDefaultById(@PathVariable("id") String idStr){
        try {
            //条件验证
            ValidatorBean.checkNotNull(idStr,"id不能为空");

            sysDictionaryService.updateSysDictionaryDefaultById(Long.parseLong(idStr));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping("/tree")
    @ApiOperation(value = "查询字典树",notes = "查询字典树")
    public ResultBean findSysDictionaryTree(){
        try {
            // 根据软件类型分组
            Map group = sysDictionaryService.findSysDictionaryByTop().stream().collect(Collectors.groupingBy(SysDictionary::getDictionarySoftType));

            List<Map<String,Object>> dictTree = new ArrayList<>();
            Map child;
            for (CommonEnumUtil.SOFT_TYPE softType :CommonEnumUtil.SOFT_TYPE.values()) {
                if(group.containsKey(softType.getValue())){
                    child = new HashMap();
                    child.put("id",softType.getValue());
                    child.put("name",softType.getCode());
                    child.put("childList",group.get(softType.getValue()));
                    dictTree.add(child);
                }
            }

            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(dictTree);
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping("/find-soft-type")
    @ApiOperation(value = "根据模块查询顶级字典",notes = "根据模块查询顶级字典")
    public ResultBean findSysDictionaryByTopBySoftType(Integer softType){
        try {
            List<SysDictionary> dictionaryList = sysDictionaryService.findSysDictionaryByTopBySoftType(softType);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(dictionaryList);
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }
}
