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.CkCleanerExternaldisplayMapper;
import cn.com.countrygarden.bi.main.dao.ck.CkCleanerFieldConfigMapper;
import cn.com.countrygarden.bi.main.dao.ck.CkCleanerRecordingMapper;
import cn.com.countrygarden.bi.main.dao.ck.green.CkGreenBasicMapper;
import cn.com.countrygarden.bi.main.dao.ck.green.CkGreenExpandMapper;
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.green.CkGreenBasic;
import cn.com.countrygarden.bi.main.model.ck.green.CkGreenExpand;
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.CkGreenExpandService;
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.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;

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 CkGreenExpandServiceImpl implements CkGreenExpandService {
    @Autowired
    private CkCleanerFieldConfigMapper ckCleanerFieldConfigMapper;
    @Autowired
    private CkGreenBasicMapper ckGreenBasicMapper;
    @Autowired
    private CkGreenExpandMapper ckGreenExpandMapper;

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

    @Autowired
    private TbHsprCommunityMapper communityMapper;

    @Autowired
    private TbSysUserMapper tbSysUserMapper;

    @Autowired
    private CkCleanerRecordingMapper ckCleanerRecordingMapper;

    @Autowired
    private CkGreenExpandService ckGreenExpandService;

    @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")) {
            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 = ckGreenExpandMapper.selectListData(cleanerQueyr);

        String authority=null;
        String lockingCode=null;

        if (rolesList.contains("ck_project_admin")){
            lockingCode="ck_project_admin";
        }

        if (rolesList.contains("ck_region_admin")){
            authority="ck_region_admin";
            lockingCode="ck_region_admin";
        }

        if (rolesList.contains("ck_admin")){
            lockingCode="ck_admin";
        }


        if(list.size()!=0){
            list.get(0).setAuthority(authority);
            list.get(0).setLockingCode(lockingCode);
        }
        //构建空数据
        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);
            ckCleanerTableVo.setLockingCode(lockingCode);
            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();
        CkGreenBasic ckCleerBas = null;
        int count = 0;
        ckCleerBas = new CkGreenBasic();
        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());
        ckCleerBas.setLocking(0);
        CkGreenBasic ckCleanerBasic = new CkGreenBasic();
        BeanUtils.copyProperties(vo, ckCleanerBasic);
        List<CkGreenBasic> basicList=new ArrayList<>();
        if(vo.getBasicId()==null){
            basicList=ckGreenBasicMapper.statisPr(ckCleerBas);
            if(basicList.size()==0){
                ckGreenBasicMapper.insert(ckCleerBas);
                ckCleanerBasic.setId(ckCleerBas.getId());
            }
        }else {
            ckCleanerBasic.setId(vo.getBasicId());
        }
 /*       if (vo.getBasicId() != null) {
            ckCleanerBasic.setId(vo.getBasicId());
        }
        ckCleanerBasic = ckGreenBasicMapper.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 = ckGreenBasicMapper.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())) {
            CkGreenExpand expand = null;
            for (CkCleanerFieldConfigVo v : vo.getChildren()) {
                expand = new CkGreenExpand();
                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 += ckGreenExpandMapper.insertGreenExpand(expand);
                    recording.setBasicId(ckCleanerBasic.getId());
                    recording.setOperatingType("新增");
                } else {
                    recording.setDataClassification(Classification);
                    Condition condition = new Condition(CkCleanerExpand.class);
                    Example.Criteria criteria = condition.createCriteria();
                    criteria.andEqualTo("basicId", ckCleanerBasic.getId()).andEqualTo("fieldCode", expand.getFieldCode());
                    count += ckGreenExpandMapper.updateByConditionSelective(expand, condition);
                    recording.setOperatingType("修改");
                    recording.setBasicId(ckCleanerBasic.getId());
                }
            }

        }
        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) {
        CkGreenBasic ceerBas = new CkGreenBasic();
        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<CkGreenBasic> basList = ckGreenBasicMapper.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<CkGreenBasic> basicList=ckGreenBasicMapper.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());

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

        condition = new Condition(CkCleanerExpand.class);
        criteria = condition.createCriteria();
        criteria.andIn("basicId", ids);
        CkGreenExpand ckCleanerExpand = new CkGreenExpand();
        ckCleanerExpand.setStatus(2);
        ckCleanerExpand.setUpdateBy(accessToken.getUserCode());
        ckCleanerExpand.setUpdateTime(new Date());
        ckGreenExpandMapper.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<CkRegionVo> 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("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 ckRegionVoList;
    }


    @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");
        Example.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(CkGreenBasic ckCleanerBasic) {
        ckCleanerBasic.setCommCode(StringUtil.isBlank(ckCleanerBasic.getCommCode()) ? "empty" : ckCleanerBasic.getCommCode());
        CkGreenBasic basic = ckGreenBasicMapper.inheritBasicInfo(ckCleanerBasic);
        ;
        if (basic == null) {
            return new CkCleanerTableVo();
        }
        ckCleanerBasic = basic;
        CkCleanerQueyr cleanerQueyr = new CkCleanerQueyr();
        cleanerQueyr.setBasicId(ckCleanerBasic.getId());
        List<CkCleanerTableVo> list = ckGreenExpandMapper.selectListData(cleanerQueyr);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return new CkCleanerTableVo();
    }

    @Autowired
    private CkCleanerExternaldisplayMapper ckCleanerExternaldisplayMapper;

    @Override
    public int addckexpand(Integer basicId,String data, AccessToken accessToken) {
 /*       JSONArray jsonArray= JSON.parseArray(data);
        if(jsonArray.size()!=0) {*/
        CkCleanerExternaldisplay nExt=new CkCleanerExternaldisplay();
        nExt.setBasicId(basicId);
        ckCleanerExternaldisplayMapper.delete(nExt);
        CkCleanerExternaldisplay ckCleanExt=new CkCleanerExternaldisplay();
        ckCleanExt.setBasicId(basicId);
        ckCleanExt.setDataConfig(data);
        ckCleanerExternaldisplayMapper.insert(ckCleanExt);
         /*   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());
            String data=ckexpandkedKeys.get(0).getDataConfig();
            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"));

            }
        }


        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())){
                    map.put(CleanerFieldCof.get(j).getFieldCode(),CleanerFieldCof.get(j).getValue());
                }
            }
            mapList.add(map);
        }
        return mapList;
    }

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

        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=ckGreenExpandMapper.tatisticsProject(YesValue,MonthValue);
        int commNum=ckGreenExpandMapper.ckCleanerCont(YesValue,MonthValue);
        int nocommNum=0;
        if(commNum!=0){
            nocommNum=commNum-pojNum;
        }
        return Response.response(MonthValue+"月已录入项目"+pojNum+"个，未录入项目"+commNum+"个");
    }

    @Override
    public Result statisProjDetad(Integer year,Integer month,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=ckGreenExpandMapper.statisProjDetad(YesValue,MonthValue);
            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=ckGreenBasicMapper.statisProjDetadNot(YesValue,MonthValue);
            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 = ckGreenExpandMapper.selectListDataNoChild(cleanerQueyr);
        List<String> baseIds=new ArrayList<>();
        for (CkCleanerTableVo t : list) {
            baseIds.add(t.getId()+"");
            t.setChildren(new ArrayList<>());
        }
//      区域数据分组统计
        List<CkFiledValueVo> configVos = ckGreenExpandMapper.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;
    }

    @Override
    public Result locking(CkGreenBasic ckGreenBasic, AccessToken accessToken) {
        CkCleanerRecording recording=new CkCleanerRecording();
        recording.setOperatingType("锁定");
        recording.setDataClassification("绿化数据");
        recording.setCommCode(ckGreenBasic.getCommCode());
        recording.setCommName(ckGreenBasic.getCommName());
        recording.setOrgCode(ckGreenBasic.getOrgCode());
        recording.setOrgName(ckGreenBasic.getOrgName());
        recording.setStatus(1);
        recording.setYear(ckGreenBasic.getYear());
        recording.setMonth(ckGreenBasic.getMonth());
        recording.setOperatingBy(accessToken.getUserCode());
        recording.setOperatingTime(new Date());
        recording.setCreateTime(new Date());
        TbSysUser tbSysUser=tbSysUserMapper.findByUserCodeNew(accessToken.getUserCode());
        recording.setOperatingName(tbSysUser.getUserName());
        List<String> rolesList = queryRoleCodes(null, accessToken.getUserCode());
        if (rolesList.contains("ck_admin")){
            ckGreenBasic.setLockingRole("ck_admin");
            ckGreenBasic.setLockingRoleName("总部管理员");
            ckGreenBasic.setLocking(1);
            ckGreenBasic.setLockingBy(accessToken.getUserCode());
            ckGreenBasic.setLockingName(tbSysUser.getUserName());
            ckGreenBasic.setUpdateBy(accessToken.getUserCode());
            ckGreenBasic.setUpdateName(tbSysUser.getUserName());
            ckGreenBasic.setUpdateTime(new Date());
            ckGreenBasicMapper.updateBylocking(ckGreenBasic);

            recording.setBasicId(ckGreenBasic.getId());
            ckCleanerRecordingMapper.insert(recording);
            return Response.response("数据已锁定");
        }
        if (rolesList.contains("ck_region_admin")){
            ckGreenBasic.setLockingRole("ck_region_admin");
            ckGreenBasic.setLockingRoleName("区域管理员");
            ckGreenBasic.setLocking(1);
            ckGreenBasic.setLockingBy(accessToken.getUserCode());
            ckGreenBasic.setLockingName(tbSysUser.getUserName());
            ckGreenBasic.setUpdateBy(accessToken.getUserCode());
            ckGreenBasic.setUpdateTime(new Date());
            ckGreenBasic.setUpdateName(tbSysUser.getUserName());
            ckGreenBasicMapper.updateBylocking(ckGreenBasic);

            recording.setBasicId(ckGreenBasic.getId());
            ckCleanerRecordingMapper.insert(recording);
            return Response.response("数据已锁定");
        }
        return null;
    }

    @Override
    public Result unlock(CkGreenBasic ckGreenBasic, AccessToken accessToken) {
        TbSysUser tbSysUser=tbSysUserMapper.findByUserCodeNew(accessToken.getUserCode());
        CkCleanerRecording recording=new CkCleanerRecording();
        recording.setOperatingType("解锁");
        recording.setDataClassification("绿化数据");
        recording.setCommCode(ckGreenBasic.getCommCode());
        recording.setCommName(ckGreenBasic.getCommName());
        recording.setOrgCode(ckGreenBasic.getOrgCode());
        recording.setOrgName(ckGreenBasic.getOrgName());
        recording.setStatus(1);
        recording.setYear(ckGreenBasic.getYear());
        recording.setMonth(ckGreenBasic.getMonth());
        recording.setOperatingBy(accessToken.getUserCode());
        recording.setOperatingTime(new Date());
        recording.setCreateTime(new Date());
        recording.setOperatingName(tbSysUser.getUserName());
        ckGreenBasic.setLockingRole(null);
        ckGreenBasic.setLockingRoleName(null);
        ckGreenBasic.setLocking(0);
        ckGreenBasic.setLockingBy(null);
        ckGreenBasic.setLockingName(null);
        ckGreenBasic.setUpdateBy(accessToken.getUserCode());
        ckGreenBasic.setUpdateTime(new Date());
        ckGreenBasic.setUpdateName(tbSysUser.getUserName());
        ckGreenBasicMapper.updateBylocking(ckGreenBasic);
        recording.setBasicId(ckGreenBasic.getId());
        ckCleanerRecordingMapper.insert(recording);
        return Response.response("数据已解锁");
    }

    @Override
    public Result batchLock(String basicIds, AccessToken accessToken) {

        String[] idString=basicIds.split(",");
        List<String> bacIds= Arrays.asList(idString);
        TbSysUser tbSysUser=tbSysUserMapper.findByUserCodeNew(accessToken.getUserCode());

        List<String> rolesList = queryRoleCodes(null, accessToken.getUserCode());
        if (rolesList.contains("ck_admin")){
            for (int i = 0; i < bacIds.size(); i++) {
                List<CkGreenBasic> ckGreenBasicList=ckGreenBasicMapper.selectByIds(bacIds.get(i));
                if (ckGreenBasicList.get(0).getLocking().equals(1)) {
                    return Response.responseFail("区域："+ckGreenBasicList.get(0).getOrgName()+
                            ",项目："+ckGreenBasicList.get(0).getCommName()+
                            ",年份："+ckGreenBasicList.get(0).getYear()+",月份："+ckGreenBasicList.get(0).getMonth()+",已锁定，请勿重复操作！！");
                }
                CkCleanerRecording recording=new CkCleanerRecording();
                recording.setOperatingBy(accessToken.getUserCode());
                recording.setOperatingTime(new Date());
                recording.setCreateTime(new Date());
                recording.setOperatingName(tbSysUser.getUserName());
                recording.setOperatingType("锁定");
                recording.setDataClassification("绿化数据");
                recording.setStatus(1);
                recording.setCommCode(ckGreenBasicList.get(0).getCommCode());
                recording.setCommName(ckGreenBasicList.get(0).getCommName());
                recording.setOrgCode(ckGreenBasicList.get(0).getOrgCode());
                recording.setOrgName(ckGreenBasicList.get(0).getOrgName());
                recording.setYear(ckGreenBasicList.get(0).getYear());
                recording.setMonth(ckGreenBasicList.get(0).getMonth());

                CkGreenBasic basic=new CkGreenBasic();
                basic.setId(Integer.valueOf(bacIds.get(i)));
                basic.setLockingRole("ck_admin");
                basic.setLockingRoleName("总部管理员");
                basic.setLocking(1);
                basic.setLockingBy(accessToken.getUserCode());
                basic.setLockingName(tbSysUser.getUserName());
                basic.setUpdateBy(accessToken.getUserCode());
                basic.setUpdateTime(new Date());
                basic.setUpdateName(tbSysUser.getUserName());
                ckGreenBasicMapper.updateBylocking(basic);
                recording.setBasicId(Integer.valueOf(bacIds.get(i)));
                ckCleanerRecordingMapper.insert(recording);
            }
            return Response.response("数据已锁定");
        }
        if (rolesList.contains("ck_region_admin")){
            for (int i = 0; i < bacIds.size(); i++) {
                List<CkGreenBasic> ckGreenBasicList=ckGreenBasicMapper.selectByIds(bacIds.get(i));
                if (ckGreenBasicList.get(0).getLocking().equals(1)) {
                    return Response.responseFail("区域："+ckGreenBasicList.get(0).getOrgName()+
                            ",项目："+ckGreenBasicList.get(0).getCommName()+
                            ",年份："+ckGreenBasicList.get(0).getYear()+",月份："+ckGreenBasicList.get(0).getMonth()+",已锁定，请勿重复操作！！");
                }

                CkCleanerRecording recording=new CkCleanerRecording();
                recording.setOperatingBy(accessToken.getUserCode());
                recording.setOperatingTime(new Date());
                recording.setCreateTime(new Date());
                recording.setOperatingName(tbSysUser.getUserName());
                recording.setOperatingType("锁定");
                recording.setDataClassification("绿化数据");
                recording.setStatus(1);
                recording.setCommCode(ckGreenBasicList.get(0).getCommCode());
                recording.setCommName(ckGreenBasicList.get(0).getCommName());
                recording.setOrgCode(ckGreenBasicList.get(0).getOrgCode());
                recording.setOrgName(ckGreenBasicList.get(0).getOrgName());
                recording.setYear(ckGreenBasicList.get(0).getYear());
                recording.setMonth(ckGreenBasicList.get(0).getMonth());

                CkGreenBasic basic=new CkGreenBasic();
                basic.setId(Integer.valueOf(bacIds.get(i)));
                basic.setLockingRole("ck_region_admin");
                basic.setLockingRoleName("区域管理员");
                basic.setLocking(1);
                basic.setLockingBy(accessToken.getUserCode());
                basic.setLockingName(tbSysUser.getUserName());
                basic.setUpdateBy(accessToken.getUserCode());
                basic.setUpdateTime(new Date());
                basic.setUpdateName(tbSysUser.getUserName());
                ckGreenBasicMapper.updateBylocking(basic);
                recording.setBasicId(Integer.valueOf(bacIds.get(i)));
                ckCleanerRecordingMapper.insert(recording);
            }

            return Response.response("数据已锁定");
        }
        return null;
    }

}