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

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.ck.*;
import cn.com.countrygarden.bi.main.dao.sys.UserRolesMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbHsprCommunityMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysOrganMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysUserMapper;
import cn.com.countrygarden.bi.main.dto.advise.ProjectListVO;
import cn.com.countrygarden.bi.main.dto.advise.RegionListVO;
import cn.com.countrygarden.bi.main.dto.ck.*;
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.ck.*;
import cn.com.countrygarden.bi.main.model.ck.ksh.CkKshBasic;
import cn.com.countrygarden.bi.main.model.sys.UserRoles;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.ck.CkCleanerExpandService;
import cn.com.countrygarden.bi.main.util.PageDataCkCleaner;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 木木子
 * @Description: 基础数据表-业务逻辑层实现
 * @email 944528607@qq.com
 * @date 2020/4/27  15:47
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class CkCleanerExpandServiceImpl implements CkCleanerExpandService {
    @Autowired
    private CkCleanerFieldConfigMapper ckCleanerFieldConfigMapper;
    @Autowired
    private CkCleanerBasicMapper ckCleanerBasicMapper;
    @Autowired
    private CkCleanerExpandMapper ckCleanerExpandMapper;

    @Autowired
    private TbSysOrganMapper tbSysOrganMapper;
    @Autowired
    private UserRolesMapper userRolesMapper;

    @Autowired
    private CkCleanerExternaldisplayMapper ckCleanerExternaldisplayMapper;

    @Autowired
    private TbHsprCommunityMapper communityMapper;

    @Autowired
    private TbSysUserMapper tbSysUserMapper;

    @Autowired
    private CkCleanerRecordingMapper ckCleanerRecordingMapper;

    @Override
    public Result getDTableConfig(String role, AccessToken accessToken) {
        CkCleanerVo ckCleanerVo = new CkCleanerVo();
        ckCleanerVo.setStatus(1);
        List<String> rolesList = null;
        if (StringUtil.isEmpty(role)) {
            rolesList = queryRoleCodes(null, accessToken.getUserCode());
        } else {
            String[] roles = role.split(",");
            rolesList = Arrays.asList(roles);
        }
        ckCleanerVo.setRolesList(rolesList);
        List<CkCleanerFieldConfigVo> ckCleanerFieldConfigs = formulaConfig(ckCleanerVo, null);
        return Response.response(ckCleanerFieldConfigs);
    }

    @Override
    public Result queryPageList(CkCleanerQueyr cleanerQueyr, AccessToken accessToken) {
        List<String> rolesList = queryRoleCodes(null, accessToken.getUserCode());
        if (StringUtil.isNotBlank(cleanerQueyr.getSearchStr())) {
            Map<String, String> map = JSON.parseObject(cleanerQueyr.getSearchStr(), Map.class);
            if (map != null && map.size() > 0) {
                cleanerQueyr.setSearchMap(map);
            }
        }
        List<CkRegionVo> ckRegionVoList = null;
        List<CkCleanerTableVo> list = null;
        if (rolesList.contains("admin") || rolesList.contains("ck_region_admin") || rolesList.contains("ck_project_admin") || rolesList.contains("ck_data_admin")) {
            if (rolesList.contains("ck_region_admin") || rolesList.contains("admin")) {
                String code=null;
                if(rolesList.contains("admin")){
                    code=null;
                }else {
                    code=accessToken.getUserCode();
                    List<RegionListVO> areaList = tbSysOrganMapper.findArea(null, code);
                    cleanerQueyr.setCkRegionRole(true);
                    cleanerQueyr.setRegionList(areaList);
                }

            }else {
                List<ProjectListVO> projectList = tbSysOrganMapper.findProject(null,accessToken.getUserCode(), null,null,null);
                cleanerQueyr.setCkProjectRole(true);
                cleanerQueyr.setProjectList(projectList);
            }
        }
        Page<Object> pageList = PageHelper.startPage(cleanerQueyr.getPage(), cleanerQueyr.getSize());
        list = ckCleanerExpandMapper.selectListData(cleanerQueyr);

        String authority = null;
        if (rolesList.contains("ck_region_admin")) {
            authority = "ck_region_admin";
        }
        if (rolesList.contains("ck_data_admin")) {
            authority = "ck_data_admin";
        }
        if (list.size() != 0) {
            list.get(0).setAuthority(authority);
        }
        //构建空数据
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
            CkCleanerFieldConfigVo configVo = new CkCleanerFieldConfigVo();
            CkCleanerTableVo ckCleanerTableVo = new CkCleanerTableVo();
            List<CkCleanerFieldConfigVo> configVoList = new ArrayList<>();
            configVoList.add(configVo);
            ckCleanerTableVo.setChildren(configVoList);
            ckCleanerTableVo.setAuthority(authority);
            list.add(ckCleanerTableVo);
        }
        int i = 0;
        int a = 0;
        for (CkCleanerTableVo vo : list) {
            vo.setBasicIndex(i++);
            if (CollectionUtils.isNotEmpty(vo.getChildren())) {
                for (CkCleanerFieldConfigVo configVo : vo.getChildren()) {
                    configVo.setChildrenIndex(a++);
                }
            }
        }


        PageData data = new PageData(pageList);
        data.setData(list);
        return Response.response(data);
    }


    @Override
    public Result addOrEdit(String data, AccessToken accessToken) {

        CkCleanerTableVo vo = JSON.parseObject(data, CkCleanerTableVo.class);
//      校验入参对象是否正确
        int inde = validateVo(vo);
        if (inde == 1) {
            return Response.responseFail("请勿添加重复区域项目");
        }

        TbSysUser tbSysUser = tbSysUserMapper.findByUserCodeNew(accessToken.getUserCode());
        CkCleanerRecording recording = new CkCleanerRecording();
        CkCleanerBasic ckCleerBas = null;
        int count = 0;
        ckCleerBas = new CkCleanerBasic();
        ckCleerBas.setOrgCode(vo.getOrgCode());
        ckCleerBas.setOrgName(vo.getOrgName());
        ckCleerBas.setCommCode(StringUtil.isBlank(vo.getCommCode()) ? "empty" : vo.getCommCode());
        ckCleerBas.setCommName(vo.getCommName());
        ckCleerBas.setYear(vo.getYear());
        ckCleerBas.setMonth(vo.getMonth());
        ckCleerBas.setStatus(1);
        ckCleerBas.setCreateTime(new Date());
        ckCleerBas.setCreateBy(accessToken.getUserCode());
        ckCleerBas.setCreateName(tbSysUser.getUserName());

        CkCleanerBasic ckCleanerBasic = new CkCleanerBasic();
        BeanUtils.copyProperties(vo, ckCleanerBasic);
        List<CkCleanerBasic> basicList = new ArrayList<>();
        if (vo.getBasicId() == null) {
            basicList = ckCleanerBasicMapper.statisPr(ckCleerBas);
            if (basicList.size() == 0) {
                ckCleanerBasicMapper.insert(ckCleerBas);
                ckCleanerBasic.setId(ckCleerBas.getId());
            }
        } else {
            ckCleanerBasic.setId(vo.getBasicId());
        }
 /*       if (vo.getBasicId() != null) {
            ckCleanerBasic.setId(vo.getBasicId());
        }
        ckCleanerBasic = ckCleanerBasicMapper.inheritBasicInfo(ckCleanerBasic);
        if (ckCleanerBasic != null) {
            return Response.responseFail("保存失败：" + vo.getOrgName() + "--" + vo.getCommName() + vo.getYear() + "年" + vo.getMonth() + "月份的数据已存在，");
        }*/

        if (basicList.size() != 0) {
            ckCleanerBasic.setId(basicList.get(0).getId());
        }
        ckCleanerBasic.setCommCode(StringUtil.isBlank(ckCleanerBasic.getCommCode()) ? "" : ckCleanerBasic.getCommCode());
        ckCleanerBasic.setCommName(StringUtil.isBlank(ckCleanerBasic.getCommName()) ? "" : ckCleanerBasic.getCommName());
        ckCleanerBasic.setYear(vo.getYear());
        ckCleanerBasic.setCreateTime(new Date());
        ckCleanerBasic.setCreateBy(accessToken.getUserCode());
        ckCleanerBasic.setCreateName(tbSysUser.getUserName());
        ckCleanerBasic.setUpdateBy(accessToken.getUserCode());
        ckCleanerBasic.setUpdateName(tbSysUser.getUserName());
        ckCleanerBasic.setUpdateTime(new Date());
        ckCleanerBasic.setStatus(1);
        count = ckCleanerBasicMapper.updateByPrimaryKeySelective(ckCleanerBasic);

        recording.setCommCode(ckCleanerBasic.getCommCode());
        recording.setCommName(ckCleanerBasic.getCommName());
        recording.setOrgCode(ckCleanerBasic.getOrgCode());
        recording.setOrgName(ckCleanerBasic.getOrgName());
        recording.setStatus(1);
        recording.setYear(ckCleanerBasic.getYear());
        recording.setMonth(ckCleanerBasic.getMonth());
        String Classification = vo.getDataClassification();
        if (CollectionUtils.isNotEmpty(vo.getChildren())) {
            CkCleanerExpand expand = null;
            for (CkCleanerFieldConfigVo v : vo.getChildren()) {
                expand = new CkCleanerExpand();
                expand.setFieldCode(v.getFieldCode());
                expand.setValue(StringUtil.isBlank(v.getValue()) ? "" : v.getValue());
                ckCleanerBasic.setUpdateName(tbSysUser.getUserName());
                expand.setUpdateBy(accessToken.getUserCode());
                expand.setUpdateTime(new Date());
                if (v.getId() == null) {
                    recording.setDataClassification(Classification);
                    expand.setBasicId(ckCleanerBasic.getId());
                    expand.setStatus(1);
                    ckCleanerBasic.setCreateName(tbSysUser.getUserName());
                    expand.setCreateBy(accessToken.getUserCode());
                    expand.setCreateTime(new Date());
                    count += ckCleanerExpandMapper.insertSelective(expand);
                    recording.setBasicId(ckCleanerBasic.getId());
                    recording.setOperatingType("新增");
                } else {
                    recording.setDataClassification(Classification);
                    Condition condition = new Condition(CkCleanerExpand.class);
                    Criteria criteria = condition.createCriteria();
                    criteria.andEqualTo("basicId", ckCleanerBasic.getId()).andEqualTo("fieldCode", expand.getFieldCode());
                    if (expand.getFieldCode().equals("followustryd")) {
                        System.out.println(expand.getFieldCode());
                    }
                    count += ckCleanerExpandMapper.updateByConditionSelective(expand, condition);
                    recording.setBasicId(ckCleanerBasic.getId());
                    recording.setOperatingType("修改");
                }
            }

        }
        recording.setOperatingName(tbSysUser.getUserName());
        recording.setOperatingBy(accessToken.getUserCode());
        recording.setOperatingTime(new Date());
        recording.setCreateTime(new Date());
        ckCleanerRecordingMapper.insert(recording);
        return Response.response(count);
    }

    private int validateVo(CkCleanerTableVo vo) {
        CkCleanerBasic ceerBas = new CkCleanerBasic();
        ceerBas.setOrgCode(vo.getOrgCode());
        ceerBas.setCommCode(vo.getCommCode());
        ceerBas.setYear(vo.getYear());
        ceerBas.setMonth(vo.getMonth());
        ceerBas.setStatus(1);
        //编辑状态下排除本身
        if (vo.getBasicId() != null) {
            ceerBas.setId(vo.getBasicId());
        }
        List<CkCleanerBasic> basList = ckCleanerBasicMapper.selectBasic(ceerBas);
        if (basList.size() > 0) {
            return 1;
        }
        return 0;
    }


    @Override
    public Result del(List<Integer> ids, String dataClassification, AccessToken accessToken) {
        TbSysUser tbSysUser = tbSysUserMapper.findByUserCodeNew(accessToken.getUserCode());
        List<CkCleanerBasic> basicList = ckCleanerBasicMapper.selectByIds(ids.get(0).toString());
        CkCleanerRecording recording = new CkCleanerRecording();

        recording.setCommCode(basicList.get(0).getCommCode());
        recording.setCommName(basicList.get(0).getCommName());
        recording.setOrgCode(basicList.get(0).getOrgCode());
        recording.setOrgName(basicList.get(0).getOrgName());
        recording.setStatus(1);
        recording.setYear(basicList.get(0).getYear());
        recording.setMonth(basicList.get(0).getMonth());

        CkCleanerBasic ckCleanerBasic = new CkCleanerBasic();
        ckCleanerBasic.setStatus(0);
        ckCleanerBasic.setUpdateTime(new Date());
        ckCleanerBasic.setUpdateBy(accessToken.getUserCode());
        Condition condition = new Condition(CkCleanerBasic.class);
        Criteria criteria = condition.createCriteria();
        criteria.andIn("id", ids);
        int count = ckCleanerBasicMapper.updateByConditionSelective(ckCleanerBasic, condition);

        condition = new Condition(CkCleanerExpand.class);
        criteria = condition.createCriteria();
        criteria.andIn("basicId", ids);
        CkCleanerExpand ckCleanerExpand = new CkCleanerExpand();
        ckCleanerExpand.setStatus(2);
        ckCleanerExpand.setUpdateBy(accessToken.getUserCode());
        ckCleanerExpand.setUpdateTime(new Date());
        ckCleanerExpandMapper.updateByConditionSelective(ckCleanerExpand, condition);


        recording.setBasicId(ids.get(0));
        recording.setOperatingType("删除");
        recording.setDataClassification(dataClassification);
        recording.setOperatingName(tbSysUser.getUserName());
        recording.setOperatingBy(accessToken.getUserCode());
        recording.setOperatingTime(new Date());
        recording.setCreateTime(new Date());
        ckCleanerRecordingMapper.insert(recording);
        return Response.response(count);
    }

    @Override
    public List<RegionListVO> getRegionDate(AccessToken accessToken) {
//        List<String> rolesList = queryRoleCodes(new String[]{"admin", "ck_admin", "ck_region_admin", "ck_project_admin"}, accessToken.getUserCode());
        List<String> rolesList = queryRoleCodes(null, accessToken.getUserCode());
        List<RegionListVO> areaList = null;
        List<CkRegionVo> ckRegionVoList = new ArrayList<>();
        CkRegionVo ckRegionVo = null;
        List<ProjectListVO> projectList = null;
        List<ProjectListVO> projects = null;
        if (rolesList.contains("admin") || rolesList.contains("ck_region_admin") || rolesList.contains("ck_project_admin") || rolesList.contains("ck_data_admin")){
            String userCode=null;
            if (rolesList.contains("admin")) {
                userCode=null;
            }else {
                userCode=accessToken.getUserCode();
            }
            areaList = tbSysOrganMapper.findArea(null, userCode);
        }
        /* if (!rolesList.contains("ck_region_admin") && !rolesList.contains("ck_project_admin")) {
            areaList = tbSysOrganMapper.findArea(null, null);
            for (RegionListVO vo : areaList) {
                ckRegionVo = new CkRegionVo();
                BeanUtils.copyProperties(vo, ckRegionVo);
                projectList = tbSysOrganMapper.findProject(vo.getOrganCode(), null,null,null,null);
                if (CollectionUtils.isNotEmpty(projectList)) {
                    ckRegionVo.setProjectList(projectList);
                    ckRegionVoList.add(ckRegionVo);
                }
            }
        } else if (rolesList.contains("ck_region_admin")) {
            areaList = tbSysOrganMapper.findArea(null, accessToken.getUserCode());
            for (RegionListVO vo : areaList) {
                ckRegionVo = new CkRegionVo();
                BeanUtils.copyProperties(vo, ckRegionVo);
                projectList = tbSysOrganMapper.findProject(vo.getOrganCode(), null,null,null,null);
                if (CollectionUtils.isNotEmpty(projectList)) {
                    ckRegionVo.setProjectList(projectList);
                    ckRegionVoList.add(ckRegionVo);
                }
            }
        } else {
            projectList = tbSysOrganMapper.findProject(null,accessToken.getUserCode(), null,null,null);

            if (CollectionUtils.isNotEmpty(projectList)) {
                Map<String, ProjectListVO> projectMap = projectList.stream().collect(Collectors.toMap(ProjectListVO::getOrganCode, a -> a, (k1, k2) -> k1));

                if (projectMap != null && projectMap.size() > 0) {
                    for (String key : projectMap.keySet()) {
                        projects = new ArrayList<>();
                        ckRegionVo = new CkRegionVo();
                        ProjectListVO projectListVO = projectMap.get(key);
                        BeanUtils.copyProperties(projectListVO, ckRegionVo);
                        if (CollectionUtils.isNotEmpty(projectList)) {
                            for (ProjectListVO vo : projectList) {
                                if (key.equals(vo.getOrganCode())) {
                                    projects.add(vo);
                                    continue;
                                }
                            }
                        }

                        if (CollectionUtils.isNotEmpty(projects)) {
                            ckRegionVo.setProjectList(projects);
                            ckRegionVoList.add(ckRegionVo);
                            projectList.removeAll(projects);
                        }
                    }
                }
            }
        }*/
        return areaList;
    }


    @Override
    public List<CkCleanerFieldConfigVo> formulaConfig(CkCleanerVo query, List<CkCleanerFieldConfigVo> list) {
        CkCleanerVo ckCleanerVo = null;
        if (CollectionUtils.isEmpty(list)) {
            ckCleanerVo = new CkCleanerVo();
            BeanUtils.copyProperties(query, ckCleanerVo);
            ckCleanerVo.setParentId(query.getParentId() == null ? 0 : query.getParentId());
            list = ckCleanerFieldConfigMapper.selectListData(ckCleanerVo);
        }
        for (CkCleanerFieldConfigVo config : list) {
            ckCleanerVo = new CkCleanerVo();
            BeanUtils.copyProperties(query, ckCleanerVo);
            ckCleanerVo.setParentId(config.getId());
            List<CkCleanerFieldConfigVo> childList = ckCleanerFieldConfigMapper.selectListData(ckCleanerVo);
            if (CollectionUtils.isNotEmpty(childList)) {
                config.setChildren(childList);
                formulaConfig(query, childList);
            } else {
                continue;
            }
        }
        return list;
    }


    public List<String> queryRoleCodes(String[] roles, String userCode) {
        //保洁模块的权限问题：admin=ck_admin>区域>项目>其他
        Condition condition = new Condition(UserRoles.class);
        condition.selectProperties("roleCode");
        Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("userCode", userCode);
        if (roles != null && roles.length > 0) {
            criteria.andIn("roleCode", Arrays.asList(roles));
        }

        List<UserRoles> rolesList = userRolesMapper.selectByCondition(condition);
        if (CollectionUtils.isNotEmpty(rolesList)) {
            return rolesList.stream().map(e -> e.getRoleCode()).collect(Collectors.toList());
        }
        // 权限不足
        throw new ServiceException("权限不足");
    }

    @Override
    public CkCleanerTableVo inheritInfo(CkCleanerBasic ckCleanerBasic) {
        ckCleanerBasic.setCommCode(StringUtil.isBlank(ckCleanerBasic.getCommCode()) ? "empty" : ckCleanerBasic.getCommCode());
        CkCleanerBasic basic = ckCleanerBasicMapper.inheritBasicInfo(ckCleanerBasic);
        ;
        if (basic == null) {
            return new CkCleanerTableVo();
        }
        ckCleanerBasic = basic;
        CkCleanerQueyr cleanerQueyr = new CkCleanerQueyr();
        cleanerQueyr.setBasicId(ckCleanerBasic.getId());
        List<CkCleanerTableVo> list = ckCleanerExpandMapper.selectListData(cleanerQueyr);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return new CkCleanerTableVo();
    }

    @Override
    public int addckexpand(Integer basicId, String data, AccessToken accessToken) {
 /*       JSONArray jsonArray= JSON.parseArray(data);
        if(jsonArray.size()!=0) {*/
        CkCleanerExternaldisplay nExt = new CkCleanerExternaldisplay();
        if (basicId == null) {
            throw new ServiceException("参数有误，请再次确认！");
        }
        nExt.setBasicId(basicId);
        ckCleanerExternaldisplayMapper.delete(nExt);
        CkCleanerExternaldisplay ckCleanExt = new CkCleanerExternaldisplay();
        ckCleanExt.setBasicId(basicId);
        ckCleanExt.setDataConfig(data);
        ckCleanerExternaldisplayMapper.insert(ckCleanExt);

        TbSysUser tbSysUser = tbSysUserMapper.findByUserCodeNew(accessToken.getUserCode());
        List<CkCleanerBasic> list = ckCleanerBasicMapper.selectByIds(String.valueOf(basicId));

        CkCleanerRecording recording = new CkCleanerRecording();

        recording.setBasicId(basicId);
        recording.setCommCode(list.get(0).getCommCode());
        recording.setCommName(list.get(0).getCommName());
        recording.setOrgCode(list.get(0).getOrgCode());
        recording.setOrgName(list.get(0).getOrgName());
        recording.setStatus(1);
        recording.setYear(list.get(0).getYear());
        recording.setMonth(list.get(0).getMonth());
        if (data.equals("[]")) {
            recording.setOperatingType("删除");
        } else {
            recording.setOperatingType("新增");
        }
        recording.setDataClassification("服务可视化对外配置");
        recording.setOperatingName(tbSysUser.getUserName());
        recording.setOperatingBy(accessToken.getUserCode());
        recording.setOperatingTime(new Date());
        recording.setCreateTime(new Date());
        ckCleanerRecordingMapper.insert(recording);
         /*   for (int i = 0; i < jsonArray.size(); i++) {

                JSONObject jsonObject=jsonArray.getJSONObject(i);
                ckCleanExt.setFieldCode(jsonObject.getString("fieldCode"));
                ckCleanExt.setFieldName(jsonObject.getString("fieldName"));
                ckCleanExt.setParentId(jsonObject.getInteger("parentId"));
                ckCleanExt.setType(jsonObject.getInteger("type"));
                ckCleanExt.setSoft(jsonObject.getInteger("soft"));

            }*/
        return 1;
        //}
        //return 0;
    }

    @Override
    public List<CkCleanerExternaldisplay> ckexpandkedKeys(Integer basicId) {
        CkCleanerExternaldisplay ckCleanerExtern = new CkCleanerExternaldisplay();
        ckCleanerExtern.setBasicId(basicId);
        List<CkCleanerExternaldisplay> ckexpandkedKeys = ckCleanerExternaldisplayMapper.select(ckCleanerExtern);
        return ckexpandkedKeys;
    }

    @Override
    public List<Map<String, String>> ckexpand(Integer[] commId, Integer year, Integer month) {
        List<String> fieldCodeSrt = new ArrayList<>();
        List<String> numidex = new ArrayList<>();
        List<CkCleanerExternaldisplay> fieldt = new ArrayList<>();
  /*      if (ckexpandkedKeys.size()!=0&&ckexpandkedKeys!=null){
            for (int i = 0; i <ckexpandkedKeys.size() ; i++) {
                fieldCodeSrt.add(ckexpandkedKeys.get(i).getFieldCode());
            }
        }*/
        List<String> list = new ArrayList<>();
        for (int i = 0; i < commId.length; i++) {
            list.add(commId[i].toString());
        }
        CkCleanerBasicDTO basicdto = new CkCleanerBasicDTO();
        basicdto.setCommId(list);
        basicdto.setYear(year);
        basicdto.setMonth(month);

        List<CkKshBasic> ckList = ckCleanerExternaldisplayMapper.ckList(basicdto);
        if (ckList.size() != 0 && ckList != null) {
            List<CkCleanerExternaldisplay> ckexpandkedKeys = ckCleanerExternaldisplayMapper.selectAllSort(ckList.get(0).getId());
            if (ckexpandkedKeys.size() == 0) {
                return null;
            }
            String data = ckexpandkedKeys.get(0).getDataConfig();
            if (!data.equals("[]") || StringUtils.isBlank(data)) {
                JSONArray jsonArray = JSON.parseArray(data);
                for (int i = 0; i < jsonArray.size(); i++) {
                    CkCleanerExternaldisplay ckCleanExt = new CkCleanerExternaldisplay();
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    ckCleanExt.setFieldCode(jsonObject.getString("fieldCode"));
                    ckCleanExt.setFieldName(jsonObject.getString("fieldName"));
                    ckCleanExt.setParentId(jsonObject.getInteger("parentId"));
                    ckCleanExt.setType(jsonObject.getInteger("type"));
                    ckCleanExt.setSoft(jsonObject.getInteger("sort"));
                    fieldt.add(ckCleanExt);
                    numidex.add(String.valueOf(jsonObject.getInteger("sort")));
                    fieldCodeSrt.add(jsonObject.getString("fieldCode"));
                }
            } else {
                return null;
            }
        }


        List<CkCleanerTableVo> cleanerBasicList = ckCleanerExternaldisplayMapper.cleanerBasicList(basicdto);
        List<CkCleanerFieldConfigVo> CleanerFieldCof = ckCleanerExternaldisplayMapper.CleanerFieldCof(fieldCodeSrt, basicdto, null);
        for (int i = 0; i < CleanerFieldCof.size(); i++) {
            for (int j = 0; j < fieldt.size(); j++) {
                if (fieldt.get(j).getFieldCode().equals(CleanerFieldCof.get(i).getFieldCode())) {
                    CleanerFieldCof.get(i).setSoft(fieldt.get(j).getSoft());
                }
            }
        }
        Collections.sort(CleanerFieldCof);
        List<Map<String, String>> mapList = new ArrayList<>();
        for (int i = 0; i < cleanerBasicList.size(); i++) {
            Map<String, String> map = new LinkedHashMap();
            map.put("orgCode", cleanerBasicList.get(i).getOrgCode());
            map.put("orgName", cleanerBasicList.get(i).getOrgName());
            map.put("commCode", cleanerBasicList.get(i).getCommCode());
            map.put("commName", cleanerBasicList.get(i).getCommName());
            for (int j = 0; j < CleanerFieldCof.size(); j++) {
                if (cleanerBasicList.get(i).getId().equals(CleanerFieldCof.get(j).getBasicId())) {
                    if(StringUtils.isNotBlank(CleanerFieldCof.get(j).getValue())){
                        map.put(CleanerFieldCof.get(j).getFieldCode(), CleanerFieldCof.get(j).getValue());
                    }else {
                        map.put(CleanerFieldCof.get(j).getFieldCode(), "0");
                    }

                }
            }
            mapList.add(map);
        }
        return mapList;
    }

    @Override
    public Result allData(Integer year, Integer month, int page, int size, String updateDate) {
        SimpleDateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // HH表示24小时制；
        List<CkCleanerDataConfigDTO> dataConList = new ArrayList<>();

        Page<Object> pageList = PageHelper.startPage(page, size);
        List<CkCleanerTableVo> allBasic= ckCleanerExpandMapper.allBasic(year, month, updateDate);

        List<Map<String, String>> mapList = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(allBasic)) {
            for (int i = 0; i < allBasic.size(); i++) {
                CkCleanerTableVo tableVo = allBasic.get(i);
//              组装主数据
                CkCleanerBasicDTO basicdto = new CkCleanerBasicDTO();
                basicdto.setYear(year);
                basicdto.setMonth(month);
                basicdto.setBasicId(tableVo.getBasicId());
//              组装可视化配置中的字段
                List<CkCleanerFieldConfigVo> CleanerFieldCof = null;
                CleanerFieldCof=ckCleanerExternaldisplayMapper.CleanerFieldCof2(basicdto, null);
                if(CollUtil.isEmpty(CleanerFieldCof)){
                    continue;
                }
//              组装可视化数据设置
                CkCleanerDataConfigDTO configDTO = new CkCleanerDataConfigDTO();
                configDTO.setBasicId(tableVo.getBasicId());
                configDTO.setOrgCode(tableVo.getOrgCode());
                configDTO.setOrgName(tableVo.getOrgName());
                configDTO.setCommCode(tableVo.getCommCode());
                configDTO.setCommName(tableVo.getCommName());
                configDTO.setYear(tableVo.getYear());
                configDTO.setMonth(tableVo.getMonth());
                configDTO.setUpdateTime(tableVo.getUpdateTime());
                dataConList.add(configDTO);


                //              组装返回值
                Map<String, String> map = new LinkedHashMap();
                map.put("orgCode", tableVo.getOrgCode());
                map.put("orgName", tableVo.getOrgName());
                map.put("commCode", tableVo.getCommCode());
                map.put("commName", tableVo.getCommName());
                map.put("year", tableVo.getYear());
                map.put("month", tableVo.getMonth());
                map.put("updateDate", dFormat.format(tableVo.getUpdateTime()));
                mapList.add(map);
//              组装排序
                JSONArray array = JSON.parseArray(tableVo.getDataConfig());
                for (int b = 0; b < CleanerFieldCof.size(); b++) {
                    CleanerFieldCof.get(b).setSoft(findSoft(array,CleanerFieldCof.get(b).getFieldCode()));
                    if(StringUtils.isNotBlank(CleanerFieldCof.get(b).getValue())){
                        map.put(CleanerFieldCof.get(b).getFieldCode(), CleanerFieldCof.get(b).getValue());
                    }else {
                        map.put(CleanerFieldCof.get(b).getFieldCode(), "0");
                    }

                }
                Collections.sort(CleanerFieldCof);
                configDTO.setDataConfig(mapList);
            }
        }
        // Page<Object> pageList = PageHelper.startPage(page, size);
        // List<Map<String, String>> mapList1 = new ArrayList<>(mapList);

        PageDataCkCleaner data = new PageDataCkCleaner(pageList);
        data.setData(mapList);
        if(mapList.size()==0){
            data.setTotal(0L);
        }
        // data.setTotal(Long.valueOf(String.valueOf(mapList.size())));
        return Response.response(data);
    }

    @Override
    public List<ProjectListVO> getPojDate(AccessToken accessToken, String organCode) {
        String userCode=null;
        List<String> rolesList = queryRoleCodes(null, accessToken.getUserCode());
        if(rolesList.contains("ck_project_admin")){
            userCode=accessToken.getUserCode();
        }
        List<ProjectListVO> projectList = tbSysOrganMapper.findProject(organCode,userCode,null,null,null);

        return projectList;
    }

    private int findSoft(JSONArray array, String fieldCode) {
        if(CollUtil.isEmpty(array)){
            return 0;
        }
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = array.getJSONObject(i);
            if(object.getString("fieldCode").equals(fieldCode)){
                return object.getInteger("sort");
            }
        }
        return 0;
    }

    @Override
    public Result statisticsProject(Integer year, Integer month, String orgCode) {

        LocalDate date = LocalDate.now();
        int YesValue = 0;
        int MonthValue = 0;
        if (date.getMonthValue() - 1 == 0) {
            YesValue = date.getYear() - 1;
            MonthValue = 12;
        } else {
            YesValue = date.getYear();
            MonthValue = date.getMonthValue() - 1;
        }
        if (month != null && year != null) {
            YesValue = year;
            MonthValue = month;
            MonthValue = MonthValue - 1;
            if (MonthValue == 0) {
                MonthValue = 12;
                YesValue = YesValue - 1;
            }
        }
        int pojNum = ckCleanerExpandMapper.tatisticsProject(YesValue, MonthValue, orgCode);
        int commNum = ckCleanerExpandMapper.ckCleanerCont(YesValue, MonthValue, orgCode);
        int nocommNum = 0;
        if (commNum != 0) {
            nocommNum = commNum - pojNum;
        }
        return Response.response(MonthValue + "月已录入项目" + pojNum + "个，未录入项目" + commNum + "个");
    }

    @Override
    public Result statisProjDetad(Integer year, Integer month, String orgCode, String type, int page, int size) {

        LocalDate date = LocalDate.now();
        int YesValue = 0;
        int MonthValue = 0;
        if (date.getMonthValue() - 1 == 0) {
            YesValue = date.getYear() - 1;
            MonthValue = 12;
        } else {
            YesValue = date.getYear();
            MonthValue = date.getMonthValue() - 1;
        }

        if (month != null && year != null) {
            YesValue = year;
            MonthValue = month;
            MonthValue = MonthValue - 1;
            if (MonthValue == 0) {
                MonthValue = 12;
                YesValue = YesValue - 1;
            }
        }

        if (type.equals("已录入")) {
            Page<Object> pageList = PageHelper.startPage(page, size);
            List<CkCleanerTableVo> list = ckCleanerExpandMapper.statisProjDetad(YesValue, MonthValue, orgCode);
            PageData data = new PageData(pageList);
            data.setData(list);
            return Response.response(data);
        } else if (type.equals("未录入")) {
            Page<Object> pageList = PageHelper.startPage(page, size);
            List<CkCleanerTableVo> listNot = ckCleanerBasicMapper.statisProjDetadNot(YesValue, MonthValue, orgCode);
            for (int i = 0; i < listNot.size(); i++) {
                listNot.get(i).setCreateName("无");
            }
            PageData data = new PageData(pageList);
            data.setData(listNot);
            return Response.response(data);
        }
        return Response.response();
    }

    @Override
    public List<CkRegionFiledValueVo> getRegionData(CkCleanerQueyr cleanerQueyr, AccessToken accessToken) {
        cleanerQueyr.setPage(1);
        cleanerQueyr.setSize(Integer.MAX_VALUE);
        List<CkCleanerTableVo> list = ckCleanerExpandMapper.selectListDataNoChild(cleanerQueyr);
        List<String> baseIds = new ArrayList<>();
        for (CkCleanerTableVo t : list) {
            baseIds.add(t.getId() + "");
            t.setChildren(new ArrayList<>());
        }
//      区域数据分组统计
        List<CkFiledValueVo> configVos = ckCleanerExpandMapper.selectRegionByBaseIds(baseIds);
        Map<String, List<CkFiledValueVo>> regionData = new HashMap<>();
        for (int i = 0; i < configVos.size(); i++) {
            CkFiledValueVo configVo = configVos.get(i);
            List<CkFiledValueVo> valueVos = regionData.get(configVo.getOrgCode());
            if (CollUtil.isEmpty(valueVos)) {
                valueVos = new ArrayList<>();
            }
            valueVos.add(configVo);
            regionData.put(configVo.getOrgCode(), valueVos);
        }
        List<CkRegionFiledValueVo> ckRegionFiledValueVos = new ArrayList<>();
        for (String region : regionData.keySet()) {
            List<CkFiledValueVo> filedValueVoList = regionData.get(region);
            CkRegionFiledValueVo valueVo = new CkRegionFiledValueVo();
            valueVo.setBasicId(filedValueVoList.get(0).getBasicId());
            valueVo.setOrgCode(filedValueVoList.get(0).getOrgCode());
            valueVo.setOrgName(filedValueVoList.get(0).getOrgName());
            valueVo.setChildren(filedValueVoList);
            ckRegionFiledValueVos.add(valueVo);
        }
        return ckRegionFiledValueVos;
    }


}