package com.chinaweal.aiccs.aiccs.dict.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.dict.entity.CascadeTreeNode;
import com.chinaweal.aiccs.aiccs.dict.entity.CmsDictCode;
import com.chinaweal.aiccs.aiccs.dict.service.CmsDictCodeService;
import com.chinaweal.aiccs.aiccs.punishment.service.TridmakerService;
import com.chinaweal.aiccs.aiccs.punishment.util.BusTridMakeUtil;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.entity.Tridmaker;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 字典代码 前端控制器
 * </p>
 *
 * @author Lee
 * @since 2021-11-17
 */
@Transactional
@RestController
@RequestMapping("/cmsDictCode")
public class CmsDictCodeController extends BaseController {

    @Autowired
    private CmsDictCodeService cmsDictCodeService;
    @Autowired
    private TridmakerService tridmakerService;

    /**
     * 违法行为大类保存
     * @param label     违法行为大类名称
     * @param isValid  是否停用
     * @return
     */
    @PostMapping("saveIllegalAct")
    public RestResult<?> saveIllegalAct(String label, String isValid, String sort, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);

        CmsDictCode cmsDictCode = new CmsDictCode();
        cmsDictCode.setLabel(label);
        cmsDictCode.setIsValid(isValid);
        if(StringUtils.isNotEmpty(sort)) {
            cmsDictCode.setSort(Integer.valueOf(sort));
        }else {
            cmsDictCode.setSort(0);
        }
        cmsDictCode.setType("illegalAct");
        // 先获取目前编码数
        Tridmaker illegalAct = tridmakerService.getById("illegalAct");
        if(illegalAct != null){
            Integer curnum = illegalAct.getCurnum();
            curnum += 1;
            illegalAct.setCurnum(curnum);
            String code = beforeZeroFill(curnum, 2);
            cmsDictCode.setCode(code);
        }
        cmsDictCode.setLevel(0);
        cmsDictCode.setCreateBy(user.getPrimaryKey());
        cmsDictCode.setCreateTime(LocalDateTime.now());
        boolean save = cmsDictCodeService.save(cmsDictCode);
        tridmakerService.updateById(illegalAct);
        return RestResult.ok(save);

    }

    /**
     * 违法行为中、小类保存
     * @param label     违法行为中、小类保存
     * @param isValid  是否停用
     * @return
     */
    @PostMapping("saveIllegalActM")
    public RestResult<?> saveIllegalActM(String label, String isValid, String sort,String parentid,String parentCode,Integer parentLevel, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        AssertUtils.isNotBlank(parentid,parentCode);
        // 先获取目前编码数
        Tridmaker tridmakerDB = tridmakerService.getById("illegalAct" + parentCode);
        CmsDictCode cmsDictCode = new CmsDictCode();
        cmsDictCode.setLabel(label);
        cmsDictCode.setIsValid(isValid);
        cmsDictCode.setType("illegalAct");
        if(StringUtils.isNotEmpty(sort)) {
            cmsDictCode.setSort(Integer.valueOf(sort));
        }else {
            cmsDictCode.setSort(0);
        }
        if(tridmakerDB == null){// 设置第一个子类时开始编码计数
            Tridmaker tridmaker = new Tridmaker();
            tridmaker.setMakerid("illegalAct" + parentCode);
            tridmaker.setCurnum(1);
            boolean save = tridmakerService.save(tridmaker);
            if(save) {
                tridmakerDB = tridmaker;
            }
        }else {
            Integer curnum = tridmakerDB.getCurnum();
            curnum += 1;
            tridmakerDB.setCurnum(curnum);
            tridmakerService.updateById(tridmakerDB);
        }
        String code = beforeZeroFill(tridmakerDB.getCurnum(), 2);
        cmsDictCode.setCode(parentCode + code);

        cmsDictCode.setLevel(parentLevel+1);
        cmsDictCode.setParentId(parentid);
        cmsDictCode.setCreateBy(user.getPrimaryKey());
        cmsDictCode.setCreateTime(LocalDateTime.now());
        boolean save = cmsDictCodeService.save(cmsDictCode);

        return RestResult.ok(save);

    }

    /**
     * 违法行为更新
     * @param cmsDictCode
     * @param request
     * @return
     */
    @PostMapping("updateDictCode")
    public RestResult<?> updateDictCode(@RequestBody CmsDictCode cmsDictCode, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);

        AssertUtils.isNotNull(cmsDictCode);
        if(StringUtils.isNotEmpty(cmsDictCode.getId())) {
            cmsDictCode.setUpdateBy(user.getPrimaryKey());
            cmsDictCode.setUpdateTime(LocalDateTime.now());
            boolean update = cmsDictCodeService.updateById(cmsDictCode);
            return RestResult.ok(update);
        }else{
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }

    }

    /**
     * 获取字典对应级联选项数组
     * @param type
     * @return
     */
    @GetMapping("getDictTreeList")
    public RestResult<?> getDictTreeList(String type){
        List<CascadeTreeNode> list = cmsDictCodeService.getList(0, type);
        List<CascadeTreeNode> resultList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)){
            resultList = addChild(list);
        }
        return RestResult.ok(resultList);
    }

    private List<CascadeTreeNode> addChild(List<CascadeTreeNode> parentList){

        for (CascadeTreeNode cascadeTreeNode : parentList) {
            List<CascadeTreeNode> childList = cmsDictCodeService.getChildList(cascadeTreeNode.getId());
            if(CollectionUtils.isNotEmpty(childList)) {
                cascadeTreeNode.setChildren(childList);
            }
            addChild(childList);
        }
        return parentList;
    }

    /**
     * 根据类型获取字典代码列表
     * @param pageRequestDto
     * @param request
     * @return
     */
    @PostMapping("codeListPageByType")
    public RestResult<?> codeListPageByType(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request){
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        AssertUtils.isNotNull(pageRequestDto,pageRequestDto.getCustomParamMap());
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();

        IPage<CmsDictCode> page = cmsDictCodeService.getCodeListPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), paramMap);
        return RestResult.ok(page);
    }


    /**
     * 根据id获取子列表
     * @param pageRequestDto
     * @return
     */
    @PostMapping("codeChildrenList")
    public RestResult<?> codeChildrenList(@RequestBody PageRequestDto pageRequestDto){
        AssertUtils.isNotNull(pageRequestDto,pageRequestDto.getCustomParamMap());
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        String id = StringUtils.tranObject(paramMap.get("id"));
        AssertUtils.isNotBlank(id);
        LambdaQueryWrapper<CmsDictCode> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CmsDictCode::getParentId,id)
                .orderByAsc(CmsDictCode::getCode);
        Page<CmsDictCode> page = cmsDictCodeService.page(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), wrapper);
        return RestResult.ok(page);
    }

    /**
     * @param number 需要填充0的数字
     * @param length 需要多少位
     * @return
     */
    private String beforeZeroFill(int number, int length) {
        return beforeZeroFill(String.valueOf(number), length);
    }
    private String beforeZeroFill(String number, int length) {
        String tmp = number;
        for (int i = 0; i < length - number.length(); i++) {
            tmp = "0" + tmp;
        }
        return tmp;
    }
}

