package com.dk.mdm.service.mst;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dk.common.infrastructure.annotaiton.Pagination;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.infrastructure.enums.ErrorCodeEnum;
import com.dk.common.model.pojo.PageList;
import com.dk.common.response.ResponseCodeEnum;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.mdm.infrastructure.convert.mst.OrgConvert;
import com.dk.mdm.mapper.mst.OrgMacMapper;
import com.dk.mdm.mapper.mst.OrgWhMapper;
import com.dk.mdm.model.pojo.mst.Org;
import com.dk.mdm.mapper.mst.OrgMapper;
import com.dk.common.service.BaseService;
import com.dk.common.mapper.BaseMapper;
import com.dk.mdm.model.pojo.mst.OrgMac;
import com.dk.mdm.model.pojo.mst.OrgWh;
import com.dk.mdm.model.query.mst.OrgQuery;
import com.dk.common.model.response.mst.OrgResponse;
import com.dk.common.model.vo.mst.OrgVO;
import com.dk.mdm.model.response.mst.MoneyAccountResponse;
import com.dk.mdm.service.common.CommonService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Transactional
public class OrgService extends BaseService<Org> {
    /**
     * @desc : 重写主键
     * @author : 王英杰
     * @date : 2023/1/9 10:39
     */
    @Override
    public String getPrimaryKey() {
        return "org_id";
    }

    @Override
    public BaseMapper<Org> getRepository() {
        return orgMapper;
    }

    @Autowired
    private OrgMapper orgMapper;

    @Autowired
    private OrgConvert orgConvert;
    @Autowired
    private CommonService commonService;

    @Autowired
    private OrgWhMapper orgWhMapper;

    @Autowired
    private OrgMacMapper orgMacMapper;

    /**
     * @desc : 条件查询
     * @author : 王英杰
     * @date : 2023/1/10 17:19
     */
    @Pagination
    public ResponseResultVO<PageList<OrgResponse>> selectByCond(OrgQuery orgQuery) {
        List<OrgResponse> list = orgMapper.selectByCond(orgQuery);
        if (orgQuery.getParentId() != null) { //说明传这个id就是部门档案查三级部门以下有没有子级
            for (OrgResponse item : list) {
                OrgQuery qry = new OrgQuery();
                qry.setParentId(item.getOrgId());
                item.setItemDataLength(orgMapper.countByCond(qry));
            }
        }
        return super.mergeListWithCount(orgQuery, list,
                orgMapper.countByCond(orgQuery));
    }

    /**
     * @desc : 条件查询
     * @author : 王英杰
     * @date : 2023/1/10 17:19
     */
    @Pagination
    public ResponseResultVO<List<OrgResponse>> selectByCondTree(OrgQuery orgQuery) {
        List<OrgResponse> list = new ArrayList<>();
        list = orgMapper.selectByCondTree(orgQuery);
        if (orgQuery.getParentId() != null) { //说明传这个id就是部门档案查三级部门以下有没有子级
            for (OrgResponse item : list) {
                OrgQuery qry = new OrgQuery();
                qry.setParentId(item.getOrgId());
                item.setItemDataLength(orgMapper.countByCond(qry));
            }
        }

        return ResponseResultUtil.success(list);
    }

    /**
     * @desc : 通过ID查询 带出对应的 组织资金账户 以及组织仓库
     * @author : 王英杰
     * @date : 2023/2/29 10:40
     */
    @Pagination
    public ResponseResultVO getById(String id) {
        Org orgResponse = orgMapper.selectById(id);
        orgResponse.setWarehouseBeanList(orgWhMapper.selectByCond(new OrgWh().setOrgId(id)));
        orgResponse.setMacBeanList(orgMacMapper.selectByCond(new OrgMac().setOrgId(id)));
        return ResponseResultUtil.success(orgResponse);
    }

    /**
     * @desc : 微信小程序 查询选择部门数据
     * @author : 宋扬
     * @date : 2023/2/29 10:40
     */
    @Pagination
    public ResponseResultVO<List<OrgResponse>> selectChooseOrg(OrgQuery orgQuery) {
        // 查出当前部门，进行过滤
        if (orgQuery.getOrgId() != null) {
            Org org = orgMapper.selectById(orgQuery.getOrgId()); //查出部门的 层级代码
            orgQuery.setLevelCode(org.getLevelCode());
            orgQuery.setFilterFlag("ok");
        }
        String parentId = orgQuery.getParentId();
        List<OrgResponse> orgResponseList = orgMapper.selectChooseOrg(orgQuery.setParentId(null));
        return ResponseResultUtil.success(orgResponseList.stream().
                filter(it -> !it.getOrgId().equals(parentId)).collect(Collectors.toList()));
    }

    /**
     * @desc : 新建组织机构
     * @author : 王英杰
     * @date : 2024/2/27 9:17
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> insert(OrgVO orgVO) {
        // 转化实体
        Org organization = orgConvert.convertToPo(orgVO);
        // 如果父级部门的是业务部门标识，就不能有子级
        if(organization.getParentId() != null ){
            Org checkOrg = orgMapper.selectById(organization.getParentId());
            if(checkOrg != null && checkOrg.getFlgBusiness() != null && checkOrg.getFlgBusiness()){
                //系统预制 无法编辑
                return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ORG_PARENT_IS_BUSINESS.getMessage());
            }
        }
        Map<String, Object> codeMap = commonService.getUniqueNoteCode(Constant.docNameConstant.ORG.getName(), true);
        // 获取编码和主键UuId
        organization.setOrgId(codeMap.get("outId").toString());
        organization.setOrgCode(codeMap.get("outNote").toString());

        //查询 本次要加的 部门的 父级下 最大的DisplayNo  然后加1  就是现在要加的DisplayNo
        Map<String, Object> param = new HashMap<>();
        param.put("otherCond", "parent_id = #{parentID} ::uuid");
        param.put("parentId", organization.getParentId());
        organization.setDisplayNo(commonService.getMaxDisplayNo(Constant.DisplayNoTable.ORG, param));
        if (organization.getParentId() != null) {
            Org org = orgMapper.selectById(organization.getParentId());
            //插入TOPid
            organization.setTopId(org.getTopId());
        }

        // 插入组织部门数据
        super.insert(organization);
        //执行函数
        orgMapper.resetLevelOrg(new Org().setTopId(organization.getTopId()).setCpId(organization.getCpId()));

        // 添加组织仓库
        if (orgVO.getWarehouseList() != null && orgVO.getWarehouseList().size() > 0) {
            for (Map<String, Object> map : orgVO.getWarehouseList()) {
                // 获取显示顺序
                Map<String, Object> paramOrgWh = new HashMap<>();
                paramOrgWh.put("noFlgValid", true);
                Integer orgWhDisplayNo = commonService.getMaxDisplayNo(Constant.DisplayNoTable.ORGWH, paramOrgWh);
                OrgWh orgWh = new OrgWh();
                orgWh.setOrgId(organization.getOrgId()).setWhId(map.get("whId").toString()).setDisplayNo(orgWhDisplayNo)
                        .setFlgDefault(Boolean.parseBoolean(map.get("ownerFlag").toString()));
                orgWhMapper.insert(orgWh);
            }
        }

        // 添加组织资金账户
        if (orgVO.getMacList() != null && orgVO.getMacList().size() > 0) {
            for (Map<String, Object> map : orgVO.getMacList()) {
                // 获取显示顺序
                Map<String, Object> paramOrgMac = new HashMap<>();
                paramOrgMac.put("noFlgValid", true);
                Integer orgMacDisplayNo = commonService.getMaxDisplayNo(Constant.DisplayNoTable.ORGMAC, paramOrgMac);
                OrgMac orgMac = new OrgMac();
                orgMac.setOrgId(organization.getOrgId()).setMacId(map.get("macId").toString()).setDisplayNo(orgMacDisplayNo)
                        .setFlgDefault(Boolean.parseBoolean(map.get("ownerFlag").toString()));
                orgMacMapper.insert(orgMac);
            }
        }
        return ResponseResultUtil.success();
        //        return result == 1 ? ResponseResultUtil.success(organization) :
//                ResponseResultUtil.error(ResponseCodeEnum.INSERT_FAIL);
    }


    /**
     * @desc : 新建组织机构
     * @author : 王英杰
     * @date : 2024/2/27 9:17
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> insertFeignOrg(OrgVO orgVO) {
        // 转化实体
        Org organization = orgConvert.convertToPo(orgVO);
        // 获取显示顺序
        Map<String, Object> codeMap = commonService.getUniqueNoteCode(
                Constant.docNameConstant.ORG.getName(), orgVO.getCpId(), true);
        // 获取编码和主键UuId
        organization.setDisplayNo(0);
        organization.setOrgId(codeMap.get("outId").toString());
        organization.setOrgCode(codeMap.get("outNote").toString());
        // 插入组织部门数据
        super.insert(organization);
        //执行函数
        // orgMapper.resetLevelOrg(new Org().setTopId(organization.getParentId()).setCpId(organization.getCpId()));
        return ResponseResultUtil.success(organization);
    }

    /**
     * @desc : 编辑方法
     * @author : 宋扬
     * @date : 2024/3/22 17:15
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<Boolean> update(OrgVO orgVO) {
        // 转化实体
        Org org = orgConvert.convertToPo(orgVO);

        // 如果是业务部门标识，那么不能有子级
        if (org.getFlgBusiness() != null && org.getFlgBusiness()) {
            Long childCount = orgMapper.countByCond(new OrgQuery().setParentId(org.getOrgId()));
            if (childCount > 0) {
                // 部门有子级不允许修改为业务部门
                return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ORG_BUSINESS_HAS_CHILD.getMessage());
            }
        }
        // 如果父级部门的是业务部门标识，就不能有子级
        if(org.getParentId() != null ){
            Org checkOrg = orgMapper.selectById(org.getParentId());
            if(checkOrg != null && checkOrg.getFlgBusiness() != null && checkOrg.getFlgBusiness()){
                //系统预制 无法编辑
                return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ORG_PARENT_IS_BUSINESS.getMessage());
            }
        }
        // 修改组织机构
        super.update(org, new UpdateWrapper<Org>().lambda().eq(Org::getOrgId,
                UUID.fromString(org.getOrgId())));
        if (orgVO.getParentId() != null) {
            Org org_ = orgMapper.selectById(orgVO.getParentId());
            //插入TOPid
            org.setTopId(org_.getTopId());
        }
        //执行函数
        orgMapper.resetLevelOrg(new Org().setTopId(org.getTopId()).setCpId(org.getCpId()));
        //删除组织仓库和组织资金账户
        orgWhMapper.deleteByOrgId(org.getOrgId());
        orgMacMapper.deleteByOrgId(org.getOrgId());
        // 添加组织仓库
        if (orgVO.getWarehouseList() != null && orgVO.getWarehouseList().size() > 0) {
            for (Map<String, Object> map : orgVO.getWarehouseList()) {
                // 获取显示顺序
                Map<String, Object> paramOrgWh = new HashMap<>();
                paramOrgWh.put("noFlgValid", true);
                Integer orgWhDisplayNo = commonService.getMaxDisplayNo(Constant.DisplayNoTable.ORGWH, paramOrgWh);
                OrgWh orgWh = new OrgWh();
                orgWh.setOrgId(org.getOrgId()).setWhId(map.get("whId").toString()).setDisplayNo(orgWhDisplayNo)
                        .setFlgDefault(Boolean.parseBoolean(map.get("ownerFlag").toString()));
                orgWhMapper.insert(orgWh);
            }
        }

        // 添加组织资金账户
        if (orgVO.getMacList() != null && orgVO.getMacList().size() > 0) {
            for (Map<String, Object> map : orgVO.getMacList()) {
                // 获取显示顺序
                Map<String, Object> paramOrgMac = new HashMap<>();
                paramOrgMac.put("noFlgValid", true);
                Integer orgMacDisplayNo = commonService.getMaxDisplayNo(Constant.DisplayNoTable.ORGMAC, paramOrgMac);
                OrgMac orgMac = new OrgMac();
                orgMac.setOrgId(org.getOrgId()).setMacId(map.get("macId").toString()).setDisplayNo(orgMacDisplayNo)
                        .setFlgDefault(Boolean.parseBoolean(map.get("ownerFlag").toString()));
                orgMacMapper.insert(orgMac);
            }
        }

        return ResponseResultUtil.success();
    }
}
