package cn.com.countrygarden.bi.main.service.districtReport.impl;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.districtReport.RdDistrictInfoMapper;
import cn.com.countrygarden.bi.main.dao.districtReport.RdDistrictPrincipalMapper;
import cn.com.countrygarden.bi.main.dao.districtReport.RdDistrictProjectMpMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.ManagerMapForErpMapper;
import cn.com.countrygarden.bi.main.dto.districtReport.RdDistrictInfoDTO;
import cn.com.countrygarden.bi.main.dto.districtReport.RdDistrictInfoDelDTO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.districtReport.RdDistrictInfo;
import cn.com.countrygarden.bi.main.model.districtReport.RdDistrictPrincipal;
import cn.com.countrygarden.bi.main.model.districtReport.RdDistrictProjectMp;
import cn.com.countrygarden.bi.main.model.dup.DupComm;
import cn.com.countrygarden.bi.main.model.dup.DupOrgan;
import cn.com.countrygarden.bi.main.service.districtReport.RdDistrictInfoService;
import cn.com.countrygarden.bi.main.service.districtReport.RdProjectpermissionService;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import com.github.pagehelper.PageRowBounds;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.transaction.Transactional;
import java.util.*;

/**
 * 片区信息-业务逻辑层实现
 *
 * @author 吕伟峰
 * @email www.justintoforest@gamail.com
 * @url 
 * @date 2019-08-14
 */
@Service
@Transactional
public class RdDistrictInfoServiceImpl implements RdDistrictInfoService{
    @Autowired
    private RdDistrictInfoMapper rdDistrictInfoMapper;

    @Autowired
    private ManagerMapForErpMapper managerMapForErpMapper;

    @Autowired
    private RdDistrictProjectMpMapper rdDistrictProjectMpMapper;

    @Autowired
    private RdProjectpermissionService rdProjectpermissionService;

    @Autowired
    private RdDistrictPrincipalMapper rdDistrictPrincipalMapper;

    @Override
    public Result queryPageList(RdDistrictInfoDTO rdDistrictInfoDTO, int page, int size,AccessToken accessToken) {
        // 获取登录人的角色授权
        Map<String, Object> rolesMap = rdProjectpermissionService.findRoleInfoMap(accessToken.getUserCode());

        List<String> organCodeString=new ArrayList<>();
        List<String> principaString=new ArrayList<>();
        List<Integer> paixu=rdProjectpermissionService.roleInfoList(rolesMap);
        for (int i=0;i<paixu.size();i++) {
             if (paixu.get(i)==1||paixu.get(i)==2){
                 break;
             }else if (paixu.get(i)==3){
                 principaString=rdProjectpermissionService.principalList(accessToken.getUserCode());
                 break;
             }else if(paixu.get(i)==4||paixu.get(i)==5){
                 organCodeString=managerMapForErpMapper.organCodeString(accessToken.getUserCode(),null);
                 if(organCodeString==null||organCodeString.size()==0){
                     return null;
                 }
                 break;
             }else if(paixu.get(i)==5){
                 throw new ServiceException("项目进度_项目用户,无法使用此模块");
             }
        }


        try {
            if(StringUtil.isBlank(rdDistrictInfoDTO.getPrincipalName())){
                PageRowBounds pageRowBounds = new PageRowBounds(page,size);
                List<RdDistrictInfoDTO> queryPageList=rdDistrictInfoMapper.queryPageList(rdDistrictInfoDTO,pageRowBounds,organCodeString,principaString);
                for (RdDistrictInfoDTO districtInfoDTO:queryPageList){
                    Condition condition=new Condition(RdDistrictProjectMp.class);
                    condition.excludeProperties("districtCode");
                    Example.Criteria criteria = condition.createCriteria();
                    criteria.andEqualTo("districtCode",districtInfoDTO.getDistrictCode());
                    criteria.andEqualTo("enable",1);
                    districtInfoDTO.setProjectMpList(rdDistrictProjectMpMapper.selectByCondition(condition));

                    Condition conditionPal=new Condition(RdDistrictPrincipal.class);
                    condition.excludeProperties("districtCode");
                    Example.Criteria criteriaPal = conditionPal.createCriteria();
                    criteriaPal.andEqualTo("districtCode",districtInfoDTO.getDistrictCode());
                    criteriaPal.andEqualTo("enable",1);
                    districtInfoDTO.setPrincipalList(rdDistrictPrincipalMapper.selectByCondition(conditionPal));
                }
                PageData pageData = new PageData(queryPageList,pageRowBounds);
                return Response.response(pageData);
            }else {
                PageRowBounds pageRowBounds = new PageRowBounds(page,size);
                List<RdDistrictInfoDTO> queryPageList=rdDistrictInfoMapper.queryPrincipalList(rdDistrictInfoDTO,pageRowBounds,organCodeString,principaString);
                for (RdDistrictInfoDTO districtInfoDTO:queryPageList){
                    Condition condition=new Condition(RdDistrictProjectMp.class);
                    condition.excludeProperties("districtCode");
                    Example.Criteria criteria = condition.createCriteria();
                    criteria.andEqualTo("districtCode",districtInfoDTO.getDistrictCode());
                    criteria.andEqualTo("enable",1);
                    districtInfoDTO.setProjectMpList(rdDistrictProjectMpMapper.selectByCondition(condition));

                    Condition conditionPal=new Condition(RdDistrictPrincipal.class);
                    condition.excludeProperties("districtCode");
                    Example.Criteria criteriaPal = conditionPal.createCriteria();
                    criteriaPal.andEqualTo("districtCode",districtInfoDTO.getDistrictCode());
                    criteriaPal.andEqualTo("enable",1);
                    districtInfoDTO.setPrincipalList(rdDistrictPrincipalMapper.selectByCondition(conditionPal));
                }
                PageData pageData = new PageData(queryPageList,pageRowBounds);
                return Response.response(pageData);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
       return null;
    }

    @Override
    public Result queryById(Integer id) {
        return Response.response(rdDistrictInfoMapper.queryById(id));
    }

    @Override
    public Result addonePrincipale(Integer id) {
        return Response.response(rdDistrictInfoMapper.addonePrincipale(id));
    }

    @Override
    public Result add(RdDistrictInfoDTO rdDistrictInfoDTO, AccessToken accessToken) {

        RdDistrictInfo count=rdDistrictInfoMapper.countList(rdDistrictInfoDTO);
        List<DupComm> comms=new ArrayList<>();
        if(count==null){
            RdDistrictInfo rdDistrictInfo=new RdDistrictInfo();
            rdDistrictInfo.setRegionCode(rdDistrictInfoDTO.getRegionCode());
            rdDistrictInfo.setRegionName(rdDistrictInfoDTO.getRegionName());
            rdDistrictInfo.setDistrictName(rdDistrictInfoDTO.getDistrictName());
            rdDistrictInfo.setDistrictCode(rdDistrictInfoDTO.getRegionCode()+"_"+String.valueOf(new Date().getTime()));
            rdDistrictInfo.setEnable(1);
            rdDistrictInfo.setType(1);
            rdDistrictInfo.setCreateBy(accessToken.getUserCode());
            rdDistrictInfo.setCreateName(rdDistrictInfoDTO.getCreateName());
            rdDistrictInfo.setCreateTime(new Date());
            int index=rdDistrictInfoMapper.insert(rdDistrictInfo);
        if(index>0){
                String[] projectNameList=rdDistrictInfoDTO.getProjectNameList().split(",");

                List<String> strsToList1= Arrays.asList(projectNameList);
                Set<String> strsTSet=new HashSet<>(strsToList1);

                 String[] strsTrue = strsTSet.toArray(new String[strsTSet.size()]);

                for (int i=0;i<strsTrue.length;i++){
                    comms.addAll(managerMapForErpMapper.queryAllCommCaseDistrict(null,strsTrue[i],null,null,null));
                }
                List<RdDistrictProjectMp> list=new ArrayList<>();
            for  ( int  i  =   0 ; i  <  comms.size()  -   1 ; i ++ ) {//检查是否重复数据
                for (int j = comms.size() - 1; j > i; j--) {
                    if (comms.get(j).getCommName().equals(comms.get(i).getCommName())) {
                        comms.remove(j);
                    }
                }
            }
                for (int i=0;i<comms.size();i++){
                    RdDistrictProjectMp rdDistrictProjectMp=new RdDistrictProjectMp();
                    rdDistrictProjectMp.setDistrictCode(rdDistrictInfo.getDistrictCode());
                    rdDistrictProjectMp.setProjectCode(comms.get(i).getCommId());
                    rdDistrictProjectMp.setProjectName(comms.get(i).getCommName());
                    rdDistrictProjectMp.setEnable(1);
                    rdDistrictProjectMp.setCreateBy(accessToken.getUserCode());
                    rdDistrictProjectMp.setCreateName(rdDistrictInfoDTO.getCreateName());
                    rdDistrictProjectMp.setCreateTime(new Date());
                    list.add(rdDistrictProjectMp);
                }
                rdDistrictProjectMpMapper.insertList(list);
            }
            return Response.response();
        }else {
            String[] projectNameList=rdDistrictInfoDTO.getProjectNameList().split(",");
            rdDistrictProjectMpMapper.deletePoj(count.getDistrictCode(),accessToken.getUserCode());
            for (int i=0;i<projectNameList.length;i++){
                comms.addAll(managerMapForErpMapper.queryAllCommCaseDistrict(null,projectNameList[i],null,null,null));
            }
            List<RdDistrictProjectMp> list=new ArrayList<>();
            for (int i=0;i<comms.size();i++){
                RdDistrictProjectMp rdDistrictProjectMp=new RdDistrictProjectMp();
                rdDistrictProjectMp.setDistrictCode(count.getDistrictCode());
                rdDistrictProjectMp.setProjectCode(comms.get(i).getCommId());
                rdDistrictProjectMp.setProjectName(comms.get(i).getCommName());
                rdDistrictProjectMp.setEnable(1);
                rdDistrictProjectMp.setCreateBy(accessToken.getUserCode());
                rdDistrictProjectMp.setCreateName(rdDistrictInfoDTO.getCreateName());
                rdDistrictProjectMp.setCreateTime(new Date());
                list.add(rdDistrictProjectMp);
            }
            rdDistrictProjectMpMapper.insertList(list);
          return Response.response();
        }
    }

    @Override
    public Result addPrincipal(RdDistrictPrincipal rdDistrictPrincipal, AccessToken accessToken) {
        rdDistrictPrincipal.setAuthorizationTime(new Date());
        rdDistrictPrincipal.setCreateBy(accessToken.getUserCode());
        rdDistrictPrincipal.setCreateTime(new Date());
        rdDistrictPrincipal.setEnable(1);
        rdDistrictPrincipalMapper.insert(rdDistrictPrincipal);
        return Response.response();
    }

    @Override
    public Result prCommId(String commName) {
        List<RdDistrictInfoDelDTO> prCommId=rdDistrictInfoMapper.prCommId(commName);
        if(prCommId.get(0).getNum()!=0){
            return Response.responseFail("此项目和其他功能关联，不可删除");
        }else {
            return Response.response();
        }
    }


    @Override
    public Result edit(RdDistrictInfoDTO rdDistrictInfoDTO, AccessToken accessToken) {

        try{
            if(StringUtils.isBlank(rdDistrictInfoDTO.getProjectNameList())){
                return Response.responseFail("项目不能为空");
            }
            RdDistrictInfo rdDistrictInfo=new RdDistrictInfo();
            rdDistrictInfo.setId(rdDistrictInfoDTO.getId());
            rdDistrictInfo.setDistrictName(rdDistrictInfoDTO.getDistrictName());
            rdDistrictInfo.setEnable(1);
            rdDistrictInfo.setUpdateBy(rdDistrictInfoDTO.getCreateBy());
            rdDistrictInfo.setUpdateTime(new Date());
            int index=rdDistrictInfoMapper.update(rdDistrictInfo);
            List<DupComm> comms=new ArrayList<>();
            if(index>0){
                rdDistrictProjectMpMapper.deletePoj(rdDistrictInfoDTO.getDistrictCode(),accessToken.getUserCode());
                String[] projectNameList=rdDistrictInfoDTO.getProjectNameList().split(",");

                List<String> strsToList1= Arrays.asList(projectNameList);
                Set<String> strsTSet=new HashSet<>(strsToList1);

                String[] strsTrue = strsTSet.toArray(new String[strsTSet.size()]);

                for (int i=0;i<strsTrue.length;i++){
                    comms.addAll(managerMapForErpMapper.queryAllCommCaseDistrictCommName(strsTrue[i],null,null));
                }
                List<RdDistrictProjectMp> list=new ArrayList<>();
                for  ( int  i  =   0 ; i  <  comms.size()  -   1 ; i ++ ) {//检查是否重复数据
                    for (int j = comms.size() - 1; j > i; j--) {
                        if (comms.get(j).getCommName().equals(comms.get(i).getCommName())) {
                            comms.remove(j);
                        }
                    }
                }
                for (int i=0;i<comms.size();i++){
                    RdDistrictProjectMp rdDistrictProjectMp=new RdDistrictProjectMp();
                    rdDistrictProjectMp.setDistrictCode(rdDistrictInfoDTO.getDistrictCode());
                    rdDistrictProjectMp.setProjectCode(comms.get(i).getCommId());
                    rdDistrictProjectMp.setProjectName(comms.get(i).getCommName());
                    rdDistrictProjectMp.setEnable(1);
                    rdDistrictProjectMp.setCreateBy(accessToken.getUserCode());
                    rdDistrictProjectMp.setCreateName(rdDistrictInfoDTO.getCreateName());
                    rdDistrictProjectMp.setCreateTime(new Date());
                    list.add(rdDistrictProjectMp);
                }
                rdDistrictProjectMpMapper.insertList(list);
            }
            return Response.response();
        }catch (Exception e){
            e.printStackTrace();
        }
        return Response.responseFail("编辑失败");
    }

    @Override
    public Result del(Integer id,AccessToken accessToken,String updateName) {
        List<RdDistrictInfoDTO> rd=rdDistrictInfoMapper.queryById(id);
        List<RdDistrictInfoDelDTO> RdDistrictInfoDelCheck=rdDistrictInfoMapper.RdDistrictInfoDelCheck(rd.get(0).getDistrictCode());

        if (RdDistrictInfoDelCheck.get(0)!=null){
              if (RdDistrictInfoDelCheck.get(0).getRcDiCode()!=null||RdDistrictInfoDelCheck.get(0).getRdsDiCode()!=null||RdDistrictInfoDelCheck.get(0).getRnDiCode()!=null
              ||RdDistrictInfoDelCheck.get(0).getRpDiCode()!=null||RdDistrictInfoDelCheck.get(0).getRuDiCode()!=null){
                  return Response.responseFail("此片区和其他功能关联，不可删除");
              }
        }
        RdDistrictPrincipal rdDistrictPrincipal=new RdDistrictPrincipal();
        rdDistrictPrincipal.setDistrictCode(rd.get(0).getDistrictCode());
        rdDistrictPrincipal.setEnable(0);
        rdDistrictPrincipal.setUpdateBy(accessToken.getUserCode());
        rdDistrictPrincipal.setUpdateTime(new Date());
        rdDistrictPrincipalMapper.delUpdatePr(rdDistrictPrincipal);
        rdDistrictProjectMpMapper.deleupda(rd.get(0).getDistrictCode(),accessToken.getUserCode(),updateName);
        int count = rdDistrictInfoMapper.deleteUpdate(id,accessToken.getUserCode(),updateName);
        return Response.response(count);
    }

    @Override
    public Result deletePrincipal(Integer id, AccessToken accessToken) {
        RdDistrictPrincipal rdDistrictPrincipal=new RdDistrictPrincipal();
        rdDistrictPrincipal.setId(id);
        rdDistrictPrincipal.setEnable(0);
        rdDistrictPrincipal.setUpdateTime(new Date());
        rdDistrictPrincipal.setUpdateBy(accessToken.getUserCode());
        rdDistrictPrincipalMapper.delUpdate(rdDistrictPrincipal);
        return Response.response();
    }

    @Override
    public List<DupOrgan> findDupCommByUserCode(String userCode, String organCode, boolean isManager) {

        // 获取登录人的角色授权
        Map<String, Object> rolesMap = rdProjectpermissionService.findRoleInfoMap(userCode);

        List<String> organCodeString=new ArrayList<>();
        List<String> commIdString=new ArrayList<>();
        List<String> principaString=new ArrayList<>();
        List<Integer> paixu=rdProjectpermissionService.roleInfoList(rolesMap);

        for (int i=0;i<paixu.size();i++) {
            if (paixu.get(i)==1||paixu.get(i)==2){
                break;
            }else if (paixu.get(i)==3){
                principaString=rdProjectpermissionService.principalRegionList(userCode);
                break;
            }else if(paixu.get(i)==4||paixu.get(i)==5){
                organCodeString=managerMapForErpMapper.organCodeString(userCode,null);
                if(organCodeString==null||organCodeString.size()==0){
                    return null;
                }
                break;
            }else if(paixu.get(i)==6){
                commIdString=managerMapForErpMapper.commIdString(userCode);
                if(commIdString==null||commIdString.size()==0){
                    return null;
                }
                organCodeString=managerMapForErpMapper.organCodeString(userCode,commIdString);
                if(organCodeString==null||organCodeString.size()==0){
                    return null;
                }
            }
        }

         List<DupOrgan> result =managerMapForErpMapper.queryAllRegionRdInfo(null,organCodeString,principaString);
        for (DupOrgan organ : result) {
            //查项目
            List<DupComm> comms=managerMapForErpMapper.queryAllCommCaseDistrict(organ.getOrganCode(),null,commIdString,null,null);
            organ.setComms(comms);
        }
         return  result;
    }

    @Override
    public Result delpiliang(String ids,AccessToken accessToken,String updateName) {

        String[] idString=ids.split(",");
        List<String> rids =  Arrays.asList(idString);
        List<RdDistrictInfoDTO> rd=new ArrayList<>();
        for (int i=0;i<rids.size();i++){
            rd.addAll(rdDistrictInfoMapper.queryById(Integer.parseInt(rids.get(i))));
        }
        RdDistrictPrincipal rdDistrictPrincipal=null;
        for (int i=0;i<rd.size();i++){
            List<RdDistrictInfoDelDTO> RdDistrictInfoDelCheck=rdDistrictInfoMapper.RdDistrictInfoDelCheck(rd.get(i).getDistrictCode());
            if (RdDistrictInfoDelCheck.get(0)!=null){
                if (RdDistrictInfoDelCheck.get(0).getRcDiCode()!=null||RdDistrictInfoDelCheck.get(0).getRdsDiCode()!=null||RdDistrictInfoDelCheck.get(0).getRnDiCode()!=null
                        ||RdDistrictInfoDelCheck.get(0).getRpDiCode()!=null||RdDistrictInfoDelCheck.get(0).getRuDiCode()!=null){
                    return Response.responseFail("此片区和其他功能关联，不可删除");
                }
            }
            rdDistrictProjectMpMapper.deleupda(rd.get(i).getDistrictCode(),accessToken.getUserCode(),updateName);
            rdDistrictPrincipal=new RdDistrictPrincipal();
            rdDistrictPrincipal.setDistrictCode(rd.get(i).getDistrictCode());
            rdDistrictPrincipal.setEnable(0);
            rdDistrictPrincipal.setUpdateBy(accessToken.getUserCode());
            rdDistrictPrincipal.setUpdateTime(new Date());
            rdDistrictPrincipalMapper.delUpdatePr(rdDistrictPrincipal);
        }
        rdDistrictInfoMapper.delpingliangtag(rids,accessToken.getUserCode(),updateName);
        return Response.response("删除成功");
    }

    @Override
    public Result rdDistrictInfoBown(String regionCode,AccessToken accessToken) {
        // 获取登录人的角色授权
        Map<String, Object> rolesMap = rdProjectpermissionService.findRoleInfoMap(accessToken.getUserCode());
        List<Integer> paixu=new ArrayList<>();
        List<String> principaString=new ArrayList<>();
        for (Map.Entry<String, Object> entry : rolesMap.entrySet()) {
            if(entry.getKey().equals("project_manager_principalAdmin")){
                paixu.add(2);
            }
        }
        for (int i=0;i<paixu.size();i++) {
            if (paixu.get(i)==2) {
                principaString=rdProjectpermissionService.principalList(accessToken.getUserCode());
                break;
            }
        }
       List<RdDistrictInfo> rdDistrictInfoBown=rdDistrictInfoMapper.rdDistrictInfoBown(regionCode,principaString);
        return Response.response(rdDistrictInfoBown);
    }

    @Override
    public Result projectMp(String districtCode,AccessToken accessToken) {

        // 获取登录人的角色授权
        Map<String, Object> rolesMap = rdProjectpermissionService.findRoleInfoMap(accessToken.getUserCode());

        List<String> organCodeString=new ArrayList<>();
        List<String> commIdString=new ArrayList<>();
        List<Integer> paixu=rdProjectpermissionService.roleInfoList(rolesMap);

        for (int i=0;i<paixu.size();i++) {
            if (paixu.get(i)==1||paixu.get(i)==2){
                break;
            }else if(paixu.get(i)==4||paixu.get(i)==5){
                organCodeString=managerMapForErpMapper.organCodeString(accessToken.getUserCode(),null);
                if(organCodeString==null||organCodeString.size()==0){
                    return null;
                }
                break;
            }else if(paixu.get(i)==6){
                organCodeString=managerMapForErpMapper.organCodeString(accessToken.getUserCode(),null);
                if(organCodeString==null||organCodeString.size()==0){
                    return null;
                }
                commIdString=managerMapForErpMapper.commIdString(accessToken.getUserCode());
                if(commIdString==null||commIdString.size()==0){
                    return null;
                }
            }
        }
        return Response.response(rdDistrictProjectMpMapper.listProject(districtCode,commIdString));
    }

    @Override
    public Result districtNameMp(String districtName, AccessToken accessToken) {
        return Response.response(rdDistrictInfoMapper.districtNameMp(districtName));
    }

    @Override
    public Result rdDistrictInfoAddOne(String regionCode, String districtName) {
        List<RdDistrictInfoDTO> rdDistrictInfoAddOne=rdDistrictInfoMapper.rdDistrictInfoAddOne(regionCode,districtName);
        return Response.response(rdDistrictInfoAddOne);
    }

    @Override
    public List<DupOrgan> findAllDupCommByUserCode(String userCode, Object o, boolean b) {
        List<DupOrgan> result =managerMapForErpMapper.queryAllRegionRdName();
        for (DupOrgan organ : result) {
            //查项目
            List<DupComm> comms=managerMapForErpMapper.queryAllCommName(organ.getOrganCode());
            organ.setComms(comms);
        }
        return  result;
    }

}