package com.pusong.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.pusong.business.domain.bo.DicDataBo;
import com.pusong.business.domain.bo.PsContractBusinessBo;
import com.pusong.business.domain.bo.PsContractBusinessDetailBo;
import com.pusong.business.domain.vo.PsContractBusinessDetailVo;
import com.pusong.business.domain.vo.PsContractBusinessVo;
import com.pusong.business.service.IPsContractBusinessDetailService;
import com.pusong.business.service.IPsContractBusinessService;
import com.pusong.business.service.IServiceConfigService;
import com.pusong.common.core.exception.ServiceException;
import com.pusong.common.core.utils.StringUtils;
import com.pusong.system.domain.bo.SysDictDataBo;
import com.pusong.system.domain.vo.SysDictDataVo;
import com.pusong.system.mapper.SysDictDataMapper;
import com.pusong.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 字典 业务层
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class IServiceConfigServiceImpl implements IServiceConfigService {
    private final SysDictDataMapper dictDataMapper;
    private final ISysDictDataService dictDataService;

    //服务类型
    private final String SERVICE_TYPE = "contract_type";
    //服务项目
    private final String SERVICE_PROJECT = "service_project";
    //子项目
    private final String CHILD_PROJECT = "child_project";
    //连接符
    private final String JOIN = "_";
    private final IPsContractBusinessService businessService;
    private final IPsContractBusinessDetailService detailService;
    /**
     *  获取全部配置信息
     * @return
     */
    @Override
    public JSONArray getAllConfig() {
        SysDictDataBo dictData = new SysDictDataBo();
        dictData.setInDictType(List.of(SERVICE_TYPE,SERVICE_PROJECT,CHILD_PROJECT));
        List<SysDictDataVo> list = dictDataService.selectDictDataList(dictData);
        //分组排序
        Map<String, List<SysDictDataVo>> map = list.stream().collect(Collectors.groupingBy(SysDictDataVo::getDictType));
        map.entrySet().forEach(entry->{
            entry.setValue(entry.getValue().stream().sorted(Comparator.comparingInt(SysDictDataVo::getDictSort)).collect(Collectors.toList()));
        });
        JSONArray serviceArray = new JSONArray();
        map.get(SERVICE_TYPE).forEach(item->{
            //服务类型
            JSONObject serviceObject = JSON.parseObject(JSON.toJSONString(item));
            //服务项目
            List<SysDictDataVo> projectList = map.get(SERVICE_PROJECT).stream().filter(it -> (it.getDictValue().indexOf(item.getDictValue()+JOIN) == 0)).collect(Collectors.toList());
            JSONArray projectArray = new JSONArray();
            if(projectList == null){projectList = new ArrayList<>();}
            //子项目
            projectList.forEach(project->{
                JSONObject projectObject = JSON.parseObject(JSON.toJSONString(project));
                List<SysDictDataVo> childList = map.get(CHILD_PROJECT).stream().filter(it -> (it.getDictValue().indexOf(project.getDictValue()+JOIN) == 0)).collect(Collectors.toList());
                //服务项目中装填子项目
                projectObject.put("children", childList);
                projectObject.put("remarkMap",StringUtils.isBlank(projectObject.getString("remark"))?null:JSON.parseObject(projectObject.getString("remark")));
                projectObject.remove("remark");
                projectArray.add(projectObject);
            });
            serviceObject.put("children", projectArray);
            serviceArray.add(serviceObject);
        });
        return serviceArray;
    }
    /**
     *  新增配置
     * @return
     */
    @Override
    public void add(DicDataBo bo) {
        String type =null ;
        //父级字典对象
        SysDictDataVo parent = new SysDictDataVo();
        //找到当前新增的字典类型
        if(bo.getParentDictCode() == null){
            type = SERVICE_TYPE;
        }else{
             parent = dictDataService.selectDictDataById(bo.getParentDictCode());
            if(StringUtils.equals(SERVICE_TYPE,parent.getDictType())){
                type =SERVICE_PROJECT;
            }else if(StringUtils.equals(SERVICE_PROJECT,parent.getDictType())){
                type =CHILD_PROJECT;
            }else{
                throw new ServiceException("不支持的类型");
            }
        }
        //查询当前类型的所有字典数据
        SysDictDataBo query = new SysDictDataBo();
        query.setInDictType(List.of(type));
        List<SysDictDataVo> list = dictDataService.selectDictDataList(query);
        //找到当前字典编码的最大值并加一（当作当前新增数据的字典编码）
        int num = 1;
        if(CollectionUtils.isNotEmpty(list)){
            String val = parent.getDictValue();
            //过滤找到属于父级的子类型，然后找到最大的编码值
            SysDictDataVo maxData = list.stream().filter(item->(StringUtils.isNotBlank(val)? item.getDictValue().indexOf(val) ==0 : !item.getDictValue().contains(JOIN)))
                    .max(Comparator.comparingInt(item -> Integer.parseInt(!item.getDictValue().contains(JOIN) ?item.getDictValue():
                            item.getDictValue().substring(val.length()+1)))).orElse(null);
            //最大编码值加一
            if(maxData != null){
                num = Integer.parseInt(maxData.getDictValue().contains(JOIN) ? maxData.getDictValue().substring(val.length()+1)
                        : maxData.getDictValue())+1 ;
            }
        }

        //组装dto数据
        SysDictDataBo dictData = new SysDictDataBo();
        dictData.setListClass("primary");
        dictData.setIsDefault("N");
        dictData.setDictSort(bo.getDictSort());
        dictData.setDictType(type);
        dictData.setDictLabel(bo.getDictLabel());
        dictData.setDictValue(parent == null || parent.getDictCode() == null ? num+"" : parent.getDictValue()+JOIN+num);
        dictData.setRemark(bo.getRemarkMap()!=null?JSON.toJSONString(bo.getRemarkMap()):null);
        dictDataService.insertDictData(dictData);
    }
    /**
     *  修改配置
     * @return
     */
    @Override
    public void edit(DicDataBo bo) {
        SysDictDataVo dict = dictDataService.selectDictDataById(bo.getDictCode());
        validEntity(dict);
        SysDictDataBo sysDictDataBo = new SysDictDataBo();
        sysDictDataBo.setDictCode(dict.getDictCode());
        sysDictDataBo.setDictType(dict.getDictType());
        sysDictDataBo.setDictLabel(bo.getDictLabel());
        sysDictDataBo.setRemark(bo.getRemarkMap()!=null?JSON.toJSONString(bo.getRemarkMap()):null);
        sysDictDataBo.setDictSort(bo.getDictSort());
        dictDataService.updateDictData(sysDictDataBo);
    }
    /**
     *  删除配置
     * @return
     */
    @Override
    public void delete(Long dictCode) {
        SysDictDataVo dict = dictDataService.selectDictDataById(dictCode);
        //开始校验
        validEntity(dict);
        //开始删除（不进行物理删除）
        SysDictDataBo sysDictDataBo = new SysDictDataBo();
        sysDictDataBo.setDictCode(dict.getDictCode());
        sysDictDataBo.setDictType(dict.getDictType()+"-delete");
        dictDataService.updateDictData(sysDictDataBo);
    }
    private void validEntity(SysDictDataVo dict ){
        if(dict == null){
            throw new ServiceException("无此数据请刷新页面");
        }
        //修改服务类型
        if(StringUtils.equals(SERVICE_TYPE,dict.getDictType())){
            PsContractBusinessBo psContractBusinessBo = new PsContractBusinessBo();
            psContractBusinessBo.setBusinessType(dict.getDictValue());
            List<PsContractBusinessVo> list = businessService.queryList(psContractBusinessBo);
            if(CollectionUtils.isNotEmpty(list)){throw new ServiceException("服务类型已使用不可修改");}
            //修改服务项目
        }else if(StringUtils.equals(SERVICE_PROJECT,dict.getDictType())){
            PsContractBusinessDetailBo detailBo = new PsContractBusinessDetailBo();
            detailBo.setBusinessProject(dict.getDictValue());
            List<PsContractBusinessDetailVo> list = detailService.queryList(detailBo);
            if(CollectionUtils.isNotEmpty(list)){throw new ServiceException("服务项目已使用不可修改");}
            //修改服务子项目
        }else if(StringUtils.equals(CHILD_PROJECT,dict.getDictType())){
            PsContractBusinessDetailBo detailBo = new PsContractBusinessDetailBo();
            detailBo.setExtentInfo(dict.getDictValue());
            List<PsContractBusinessDetailVo> list = detailService.queryList(detailBo);
            if(CollectionUtils.isNotEmpty(list)){throw new ServiceException("服务子项目已使用不可修改");}
        }
    }
    /**
     * 根据合同编码查询资料配置信息
     * @param contractCode
     */
    public List<String> getByContractCode(String contractCode){
        SysDictDataBo dictData = new SysDictDataBo();
        dictData.setInDictType(List.of(SERVICE_PROJECT));
        List<SysDictDataVo> configList = dictDataService.selectDictDataList(dictData);
        //分组排序
        Map<String, String> map = configList.stream().collect(Collectors.toMap(SysDictDataVo::getDictValue, SysDictDataVo::getRemark));
        PsContractBusinessDetailBo bo = new PsContractBusinessDetailBo();
        bo.setContractCode(contractCode);
        List<PsContractBusinessDetailVo> list = detailService.queryList(bo);
        List<String> restList = new ArrayList<>();
        list.forEach(item ->{
            String bp = map.get(item.getBusinessProject());
            if(StringUtils.isNotBlank(bp)){
                String cb = JSON.parseObject(bp).getString("cb");
                if(StringUtils.isNotBlank(cb)){
                    restList.addAll(List.of(cb.split(",")));
                }
            }
        });
        return restList;
    }
}
