package com.yeejoin.amos.boot.module.ugp.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.ugp.api.Enum.OrgEnum;
import com.yeejoin.amos.boot.module.ugp.api.Enum.ProjectInitiationEnum;
import com.yeejoin.amos.boot.module.ugp.api.Enum.WhetherItPassEnum;
import com.yeejoin.amos.boot.module.ugp.api.constants.XJConstant;
import com.yeejoin.amos.boot.module.ugp.api.dto.*;
import com.yeejoin.amos.boot.module.ugp.api.entity.*;
import com.yeejoin.amos.boot.module.ugp.api.mapper.AttachmentMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.ProjectMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.ProjectResourceMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.SuperviseRuleMapper;
import com.yeejoin.amos.boot.module.ugp.api.service.IProjectService;
import com.yeejoin.amos.boot.module.ugp.biz.framework.BusinessIdentify;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 项目信息表服务实现类
 *
 * @author system_generator
 * @date 2022-09-22
 */
@Service
public class ProjectServiceImpl extends BaseService<ProjectDto, Project, ProjectMapper> implements IProjectService {

    @Autowired
    ProjectMapper projectMapper;

    @Autowired
    ProjectResourceServiceImpl projectResourceService;

    @Autowired
    AttachmentServiceImpl attachmentService;

    @Autowired
    ProjectInitiationServiceImpl projectInitiationService;

    @Autowired
    EquipmentServiceImpl equipmentService;

    @Autowired
    OrgServiceImpl orgService;

    @Autowired
    SuperviseRuleServiceImpl superviseRuleService;

    @Autowired
    ProjectResourceMapper projectResourceMapper;

    @Autowired
    AttachmentServiceImpl attachmentServiceImpl;

    @Autowired
    WeldServiceImpl weldServiceImpl;
    @Autowired
    SuperviseRuleMapper superviseRuleMapper;

    @Autowired
    OrgServiceImpl orgServiceImpl;

    @Autowired
    IPipeServiceImpl pipeService;

    @Autowired
    AttachmentMapper attachmentMapper;

    static final String symbolKey = "Symbol_key";
    static final String status = "status";

    public ProjectDto saveProjectInfo(ProjectDto model,String submitType){
        String regionName = "",regionCode = "";
        Map<String,String> map = getInfo(regionName,regionCode,Long.valueOf(model.getInstallRegionCode()));
        model.setSubmitDate(new Date());
        getUnitName(model);
        model.setInstallRegion(map.get("regionName"));
        model.setInstallRegionCode(map.get("regionCode"));
        Project project = new Project();
        BeanUtils.copyProperties(model, project);
//		model.setCode(getCode());
        if(ValidationUtil.isEmpty(model.getSequenceNbr())) {
            model = this.createWithModel(model);
        } else {
            this.updateById(project);
        }
        pipeService.addPipeMessage(JSON.toJSONString(model.getPipeSubForm()),model.getSequenceNbr());
        //提交触发流程
        if(WhetherItPassEnum.PASS.getCode().equals(submitType)) {
            String token = RequestContext.getToken();
            String appKey = RequestContext.getAppKey();
            String product = RequestContext.getProduct();
            //分支线程执行流程
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    RequestContext.setToken(token);
                    RequestContext.setAppKey(appKey);
                    RequestContext.setProduct(product);
                    projectInitiationService.start(project);
                }
            });
            t1.start();
        }
        return model;
    }

    /**
     * 根据id获取单位名称
     * @param model
     */
    public void getUnitName(ProjectDto model){
        if(!ValidationUtil.isEmpty(model.getInstallationUnitId())) {
            model.setInstallationUnit(orgServiceImpl.getOrgUsrById(String.valueOf(model.getInstallationUnitId())).getBizOrgName());
        }
        if(!ValidationUtil.isEmpty(model.getDesignUnitId())) {
            model.setDesignUnit(orgServiceImpl.getOrgUsrById(String.valueOf(model.getDesignUnitId())).getBizOrgName());
        }
        if(!ValidationUtil.isEmpty(model.getConstructionUnitId())) {
            model.setConstructionUnit(orgServiceImpl.getOrgUsrById(String.valueOf(model.getConstructionUnitId())).getBizOrgName());
        }
        if(!ValidationUtil.isEmpty(model.getTestingUnitId())) {
            model.setTestingUnit(orgServiceImpl.getOrgUsrById(String.valueOf(model.getTestingUnitId())).getBizOrgName());
        }
        if(!ValidationUtil.isEmpty(model.getSupervisionUnitId())) {
            model.setSupervisionUnit(orgServiceImpl.getOrgUsrById(String.valueOf(model.getSupervisionUnitId())).getBizOrgName());
        }
        if(!ValidationUtil.isEmpty(model.getChargePersonId())) {
            model.setChargePerson(orgServiceImpl.getOrgUsrById(String.valueOf(model.getChargePersonId())).getBizOrgName());
        }
        if(!ValidationUtil.isEmpty(model.getInstallUnitChargerId())) {
            model.setInstallUnitCharger(orgServiceImpl.getOrgUsrById(String.valueOf(model.getInstallUnitChargerId())).getBizOrgName());
        }
    }

    /**
     * 根据项目id获取项目详情
     */
    public ProjectDto selectById(Long sequenceNbr){
        ProjectDto projectDto = this.queryBySeq(sequenceNbr);
        LambdaQueryWrapper<Pipe> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Pipe::getProjectId,sequenceNbr);
        List<Pipe> pipeList = pipeService.list(wrapper);
        List<PipeDto> pipeDtoList = new ArrayList<>();
        for(Pipe pipe:pipeList){
            PipeDto pipeDto = new PipeDto();
            BeanUtils.copyProperties(pipe,pipeDto);
            if(pipe.getStartPosition().contains(",")) {
                String[] position = pipe.getStartPosition().split(",");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("latitude",position[0]);
                jsonObject.put("longitude",position[1]);
                jsonObject.put("address",pipe.getStartName());
                pipeDto.setStartPositionObject(jsonObject);
            }
            if(pipe.getEndPosition().contains(",")) {
                String[] position = pipe.getEndPosition().split(",");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("latitude",position[0]);
                jsonObject.put("longitude",position[1]);
                jsonObject.put("address",pipe.getEndName());
                pipeDto.setEndPositionObject(jsonObject);
            }
            pipeDtoList.add(pipeDto);
        }
        projectDto.setPipeSubForm(pipeDtoList);
        return projectDto;
    }

    // 静态变量存储最大值
    private static final AtomicInteger atomicNum = new AtomicInteger();
    private static final Integer INIT_CODE_NUM = 0;
    public String getCode(){
        String date = new SimpleDateFormat("yyyy").format(new Date());
        String code = "XM"+date+"-";
        String format="";
        String projectCode = "";
        LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Project::getCode);
        List<Project> list = this.list(wrapper);
        if(!ValidationUtil.isEmpty(list)){
            projectCode =list.iterator().next().getCode();

            if(!ValidationUtil.isEmpty(projectCode)){
                String proDate = projectCode.substring(projectCode.indexOf("M")+1,projectCode.length() - 5);
                if (proDate.equals(date)){
                    String substring = projectCode.substring(projectCode.length() - 4);
                    atomicNum.set(Integer.parseInt(substring));
                }else {
                    atomicNum.set(INIT_CODE_NUM);
                }
                format = String.format("%04d", atomicNum.incrementAndGet());
            }
        }else {
            format = String.format("%04d", atomicNum.incrementAndGet());
        }
        return code+format;
    }

    public Map<String,String> getInfo(String regionName,String regionCode,Long sequenceNbr){
        RegionModel region = Systemctl.regionClient.getRegion(sequenceNbr).getResult();
        regionName = region.getRegionName() + regionName;
        if(ValidationUtil.isEmpty(regionCode)){
            regionCode = String.valueOf(region.getRegionCode());
        } else {
            regionCode = region.getRegionCode() +"#" +regionCode;
        }
        Map<String,String> map = new HashMap();
        if(region.getParentId() != 0L){
            map = getInfo(regionName,regionCode,region.getParentId());
        } else {
            map.put("regionName",regionName);
        }
        map.put("regionCode",regionCode);
        return map;
    }

    /**
     * 分页查询
     */
    public Page<ProjectDto> queryForProjectPage(Page<ProjectDto> page ,String name,String constructionUnit) {
        Page<ProjectDto> projectDtoPage = this.queryForPage(page, null, false,name,constructionUnit);
        List<ProjectDto> projects = projectDtoPage.getRecords();
        for(ProjectDto project:projects){
            getProjectState(project);
        }
        return projectDtoPage;
    }

    private void getProjectState(ProjectDto project) {
        String state = "",insDep = "",insPerson = "",insDepId = "";
        //新立项的项目 分支流程原因还没有instanceId 默认给值
        if(ValidationUtil.isEmpty(project.getInstanceId())){
            state=ProjectInitiationEnum.提交资料.getTaskDetailStatus();
        }

        LambdaQueryWrapper<ProjectInitiation> lambdaQueryWrap = new LambdaQueryWrapper<>();
        lambdaQueryWrap.eq(ProjectInitiation::getInstanceId,project.getInstanceId())
//                .eq(ProjectInitiation ::getTaskName, ProjectInitiationEnum.平台审核.getName())
                .orderByDesc(ProjectInitiation::getSequenceNbr);

        List<ProjectInitiation> projectInitiationList = projectInitiationService.list(lambdaQueryWrap);
        if(!ValidationUtil.isEmpty(projectInitiationList)){
            ProjectInitiation projectInitiation = projectInitiationList.iterator().next();
            JSONObject jsonObject = JSON.parseObject(projectInitiation.getContext());
            if( ProjectInitiationEnum.监检科室分配.getName().equals(project.getStatus()) || ProjectInitiationEnum.监检员分配.getName().equals(project.getStatus()) || ProjectInitiationEnum.监检员审核.getName().equals(project.getStatus()) || ProjectInitiationEnum.流程结束.getName().equals(project.getStatus())){
                if(!ValidationUtil.isEmpty(jsonObject)){
                    insDepId = jsonObject.getString(XJConstant.INS_DEPID);
                    state = jsonObject.getString(XJConstant.PROCESS_PROJECT_STATE);
                    insDep = jsonObject.getString(XJConstant.INS_DEP);
                    insPerson = jsonObject.getString(XJConstant.INS_PRESON);
                }
            } else {
                state = ProjectInitiationEnum.getTaskDetailStatusMap.get(project.getStatus());
            }
        }

        project.setExamineProjectState(state);
        project.setInsDep(insDep);
        project.setInsPerson(insPerson);
        project.setInsDepId(insDepId);

    }


    /**
     * 列表查询 示例
     */
    public List<ProjectDto> queryForProjectList() {
        return this.queryForList("", false);
    }

    /**
     * 查询项目名称
     */
    @BusinessIdentify
    public List<JSONObject> selectName() {
        List<JSONObject> names = new ArrayList<>();

        Long companySequenceNbr = orgService.getReginParams().getBusinessInfo().getCompanySequenceNbr();
        LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Project::getCompanyId,companySequenceNbr);
        //查询所有项目
        List<Project> projects = projectResourceService.getProjectList();
        for (Project i : projects) {
            JSONObject name = new JSONObject();
            name.put("name", i.getName());
            name.put("sequenceNbr", i.getSequenceNbr());
            names.add(name);
        }

        return names;
    }


    /**
     * 通过多个主键sequence_nbr查询数据
     * @param ids
     * @return
     */
    public List<Project> selectByidList(List<Long> ids){
        return projectMapper.selectBatchIds(ids);
    }

    @BusinessIdentify
    public ProjectDto getDetail(Long sequenceNbr){

        ProjectDto project = projectMapper.getDetail(sequenceNbr);
        LambdaQueryWrapper<Attachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Attachment::getSourceId,sequenceNbr);
        Attachment attachment = attachmentService.getOne(wrapper);
//        try{
        JSONObject jsonObject = null;
        if(!ValidationUtil.isEmpty(attachment)){
            jsonObject  =  JSON.parseObject(attachment.getInfo());
        }


        JSONArray installSubForm = JSON.parseArray(XJConstant.INSTALL_SUB_FORM);
        JSONArray designSubForm = JSON.parseArray(XJConstant.DESIGN_SUB_FORM);
        if(!ValidationUtil.isEmpty(jsonObject)){
            installSubForm = jsonObject.getJSONArray("installSubForm");
            designSubForm = jsonObject.getJSONArray("designSubForm");
        }
        project.setInstallSubForm(installSubForm);
        project.setDesignSubForm(designSubForm);
//            project.setSubForm(jsonArray);
//        }catch (Exception e) {
//            System.out.println("该项目暂无附件");
//        }
        project.getInstanceId();
        getProjectState(project);

        project.setCompanyType(orgService.getReginParams().getBusinessInfo().getCompanyType());
        return project;
    }


    public String saveOrUpdateFile(JSONObject jsonObject){
        JSONArray installSubForm = jsonObject.getJSONArray("installSubForm");
        JSONArray designSubForm = jsonObject.getJSONArray("designSubForm");
        JSONObject subForm = new JSONObject();
        subForm.put("installSubForm",installSubForm);
        subForm.put("designSubForm",designSubForm);
        Long sequenceNbr = jsonObject.getLong("sequenceNbr");
        LambdaQueryWrapper<Attachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Attachment::getSourceId,sequenceNbr);
        Attachment attachment = attachmentService.getOne(wrapper);
        if(ValidationUtil.isEmpty(attachment)){
            equipmentService.saveProjectAttachment(subForm,sequenceNbr);
        }else {
            attachment.setInfo(JSON.toJSONString(subForm));
            attachmentService.updateById(attachment);
        }
        if(ValidationUtil.isEmpty(jsonObject.getString(XJConstant.PROCESS_PROJECT_STATE))){
            jsonObject.put(XJConstant.PROCESS_PROJECT_STATE,"资料已上传");
        }
        Project project = this.getById(sequenceNbr);
        ProjectDto projectDto = new ProjectDto();
        BeanUtils.copyProperties(project,projectDto);
        projectDto.setInsDep(jsonObject.getString("insDep"));
        projectDto.setInsDep(jsonObject.getString("insPerson"));
        projectDto.setProcessProjectState(jsonObject.getString(XJConstant.PROCESS_PROJECT_STATE));
        boolean design=false,install=false;
        for(Object object:installSubForm){
            JSONObject jo = JSON.parseObject(JSON.toJSONString(object));
            String type = jo.getString("type");
            String info = jo.getString("info");
            if (OrgEnum.安装单位.getName().equals(type) && !ValidationUtil.isEmpty(info)){
                install=true;
            }else {
                install=false;
                break;
            }
        }
        for(Object object:designSubForm){
            JSONObject jo = JSON.parseObject(JSON.toJSONString(object));
            String type = jo.getString("type");
            String info = jo.getString("info");
            if (OrgEnum.设计单位.getName().equals(type) && !ValidationUtil.isEmpty(info)){
                design=true;
            }else {
                design=false;
                break;
            }
        }

        //若为null则为保存 不执行流程
        String type = jsonObject.getString("type");
        if (!ValidationUtil.isEmpty(type)) {
            if (design && install) {
                projectInitiationService.execute(project.getInstanceId(), projectDto, "1",null);
                return "over";
            }else {
                return "fail";
            }
        }
        return "ok";
    }

//    //项目模糊筛选
//    @Override
//    public Page<ProjectDto> queryProjectPage(Page<ProjectDto> page, Project project) {
//        Page<ProjectDto> projectDtoPage = projectMapper.queryProjectPage(page,project);
//        List<ProjectDto> projects = projectDtoPage.getRecords();
//        for(ProjectDto projectDto:projects){
//            getProjectState(projectDto);
//        }
//        return projectDtoPage;
//    }




    //项目模糊筛选

//    @BusinessIdentify
//    @Override
//    public IPage<ProjectDto> queryProjectPage(String current,String size, Project project) {
//        IPage<ProjectDto> page = new Page<>();
//        page.setCurrent(Long.parseLong(current));
//        page.setSize(Long.parseLong(size));
//        ReginParams reginParams = orgService.getReginParams();
//        String companyId = String.valueOf(reginParams.getBusinessInfo().getCompanySequenceNbr());
//        String roleName = reginParams.getRole().getRoleName();
//        LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>();
//        String reginCode = "";
//        if(OrgEnum.监察部门.getName().equals(roleName)){
//            wrapper.eq(SuperviseRule::getSuperviseDeptId,companyId);
//            reginCode = superviseRuleService.getOne(wrapper).getAdminRegion();
//        } else if(OrgEnum.监检机构.getName().equals(roleName)){
//            wrapper.eq(SuperviseRule::getInspectionUnitId,companyId);
//            reginCode = superviseRuleService.getOne(wrapper).getAdminRegion();
//        } else {
//            page =  projectMapper.queryProjectPage(page, project, roleName, companyId);
//        }
//        if(!ValidationUtil.isEmpty(reginCode)){
//            page = projectMapper.queryProjectPage(page, project, roleName, reginCode);
//        }
//        List<ProjectDto> projects = page.getRecords();
//        for(ProjectDto projectDto:projects){
//            getProjectState(projectDto);
//        }
//        return page;
//    }
//

    @BusinessIdentify
    @Override
    public IPage<ProjectDto> queryProjectPage(String current,String size, Project project) {
        IPage<ProjectDto> page = new Page<>();
        page.setCurrent(Long.parseLong(current));
        page.setSize(Long.parseLong(size));
        ReginParams reginParams = orgService.getReginParams();
        String companyId = String.valueOf(reginParams.getBusinessInfo().getCompanySequenceNbr());
        String roleName = reginParams.getRole().getRoleName();
        LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>();
        Set<String> codes = new HashSet<>();
        if(OrgEnum.监察部门.getName().equals(roleName)){
            wrapper.eq(SuperviseRule::getSuperviseDeptId,companyId);
            List<SuperviseRule> superviseRuleList = superviseRuleService.list(wrapper);
            for (SuperviseRule superviseRule :superviseRuleList){
                codes.add(String.valueOf(superviseRule.getAdminRegionCode()));
            }
        } else if(OrgEnum.监检机构.getName().equals(roleName)){
            wrapper.eq(SuperviseRule::getInspectionUnitId,companyId);
            List<SuperviseRule> superviseRuleList = superviseRuleService.list(wrapper);
            for (SuperviseRule superviseRule :superviseRuleList){
                codes.add(String.valueOf(superviseRule.getAdminRegionCode()));
            }
        } else {
            page =  projectMapper.queryProjectPage(page, project, roleName, companyId,codes);
        }
        if(!ValidationUtil.isEmpty(codes)){
            page = projectMapper.queryProjectPage(page, project, roleName,companyId,codes);
        }
        List<ProjectDto> projects = page.getRecords();
        for(ProjectDto projectDto:projects){
            getProjectState(projectDto);
            }
        List<ProjectDto> projectDtoList = getPage(projects);
        page.setRecords(projectDtoList);
        return page;
    }

   public List<ProjectDto> getPage(List<ProjectDto> projects){
       ArrayList<ProjectDto> list = Lists.newArrayList();
       for(ProjectDto projectDto:projects){
           if (ProjectInitiationEnum.监检员分配.getName().equals(projectDto.getStatus())) {
               if (!ValidationUtil.isEmpty(projectDto.getContext()) && JSONObject.parseObject(projectDto.getContext()).containsKey("insDepId")) {
                   String insDepId = JSONObject.parseObject(projectDto.getContext()).getString("insDepId");
                   if (!ValidationUtil.isEmpty(insDepId)) {
                       Map map = orgService.getdetialInfo(insDepId);
                       String fieldValue = (String)map.get("charge");
                       OrgUsr orgUsr = orgService.getOrgUsrById(fieldValue);
                       FeignClientResult<List<AgencyUserModel>> listFeignClientResult = Privilege.agencyUserClient.queryByRealName(orgUsr.getBizOrgName());
                       List<AgencyUserModel> resultList = listFeignClientResult.getResult();
                       for (AgencyUserModel agencyUserModel : resultList) {
                           String userId=agencyUserModel.getUserId();
                           projectDto.setUserId(userId);
                       }
                   }
               }
               list.add(projectDto);
           }else if (!ValidationUtil.isEmpty(projectDto.getContext()) && ProjectInitiationEnum.监检员审核.getName().equals(projectDto.getStatus())) {
               if (JSONObject.parseObject(projectDto.getContext()).containsKey("insPerson")) {
                   String insPerson = JSONObject.parseObject(projectDto.getContext()).getString("insPerson");
                   if (!ValidationUtil.isEmpty(insPerson)) {
                       FeignClientResult<List<AgencyUserModel>> listFeignClientResult = Privilege.agencyUserClient.queryByRealName(insPerson);
                       List<AgencyUserModel> resultList = listFeignClientResult.getResult();
                       for (AgencyUserModel agencyUserModel : resultList) {
                           String userId=agencyUserModel.getUserId();
                           projectDto.setUserId(userId);
                       }
                   }
               }
               list.add(projectDto);
           } else {
               list.add(projectDto);
           }
       }
       return list;
   }
    @BusinessIdentify
    public List<Map<String, String>> projectSchedule() {
        List<Project> projectList = projectResourceService.getProjectList();
        Set<Long> projectIds = new HashSet<>();
        if(!ValidationUtil.isEmpty(projectList)){
            for (Project project :projectList){
                projectIds.add(project.getSequenceNbr());
            }
        }
        return projectMapper.getProjectComplete(projectIds);
    }

    public List<Map<String,String>> projectOverview() {
        List<Map<String,String>> list = new LinkedList<>();
        ReginParams ReginParams = orgService.getReginParams();
        String companyType = ReginParams.getBusinessInfo().getCompanyType();
        Long companyId = ReginParams.getBusinessInfo().getCompanySequenceNbr();
        if (OrgEnum.监察部门.getKey().equals(companyType)) {
            Map<String,String> map1 = new HashMap<>();
            Map<String,String> map2 = new HashMap<>();
            String aLong1 = projectMapper.projectBuiltDept(companyId);
            String aLong2 = projectMapper.projectUnderConstructionDept(companyId);
            map1.put("name","已建");
            map1.put("value",aLong1);
            map2.put("name","在建");
            map2.put("value",aLong2);
            list.add(map1);
            list.add(map2);
            return list;
        } else if (OrgEnum.监检机构.getKey().equals(companyType)) {
            Map<String,String> map1 = new HashMap<>();
            Map<String,String> map2 = new HashMap<>();
            String aLong1 = projectMapper.projectBuiltUnit(companyId);
            String aLong2 = projectMapper.projectUnderConstructionUnit(companyId);
            map1.put("name","已建");
            map1.put("value",aLong1);
            map2.put("name","在建");
            map2.put("value",aLong2);
            list.add(map1);
            list.add(map2);
            return list;
        }
        return null;
    }

    @BusinessIdentify
    public JSONObject projectInProgress() {
        JSONObject object = new JSONObject();
        ArrayList<String> axisData = Lists.newArrayList();
        ArrayList<Integer> seriesData = Lists.newArrayList();
        ReginParams reginParams = orgService.getReginParams();
        String roleName = reginParams.getRole().getRoleName();
        Long companyId = reginParams.getBusinessInfo().getCompanySequenceNbr();
        LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>( );
        LambdaQueryWrapper<Project> wrapper1 = new LambdaQueryWrapper<>();

                List<Project> list = projectResourceService.getProjectList();
                for (Project project : list) {
                    ProjectProcessDto projectProcessDto = projectMapper.getProjectProcessDto(project.getSequenceNbr());
                    axisData.add(projectProcessDto.getProjectName());
                    seriesData.add(getProjectProcess(projectProcessDto));
                }

        object.put("axisData",axisData);
        object.put("seriesData",seriesData);
        return object;
    }



    public Integer getProjectProcess(ProjectProcessDto projectProcessDto)
    {
        Double projectProcess = projectProcessDto.getProjectProcess();
        if (projectProcess.compareTo(1.0) == 0 || projectProcess.compareTo(1.0) == 1) {
            return 100;
        }
        Integer  pass = new BigDecimal(projectProcess).multiply (new BigDecimal (100)).intValue();
        return Integer.valueOf(pass);
    }

    /**
     * 获取当前登陆人所在单位下的项目的项目信息（包含经纬度信息）
     * @return
     */
    public List<ProjectDto> getProjectLocation(){
        List<Project> projectList = projectResourceService.getProjectList();
        List<ProjectDto> projectDtoList = new ArrayList<>();
        if(!ValidationUtil.isEmpty(projectList)){
            for (Project project : projectList) {
                ProjectDto projectDto = new ProjectDto();
                BeanUtils.copyProperties(project,projectDto);
                List<Weld> weldList = weldServiceImpl.list(new LambdaQueryWrapper<Weld>().eq(Weld::getProjectId,project.getSequenceNbr()));
                if(!ValidationUtil.isEmpty(weldList)){
                    for (Weld weld : weldList) {
                        String longitude = weld.getLongitude();
                        String latitude = weld.getLatitude();
                        if (!ValidationUtil.isEmpty(longitude) && !ValidationUtil.isEmpty(latitude)) {
                            projectDto.setLongitude(longitude);
                            projectDto.setLatitude(latitude);
                            break;
                        }
                    }
                }
                projectDtoList.add(projectDto);
            }
        }
        return projectDtoList;
    }

    /**
     * 获取当前登陆人所在单位下的项目的项目信息（包含经纬度信息）
     * @return
     */
    public ProjectDto getProjectLocationOne(String projectId){
        Project project = this.getById(projectId);
        ProjectDto projectDto = new ProjectDto();
        if(!ValidationUtil.isEmpty(project)){
                BeanUtils.copyProperties(project,projectDto);
                List<Weld> weldList = weldServiceImpl.list(new LambdaQueryWrapper<Weld>().eq(Weld::getProjectId,project.getSequenceNbr()));
                if(!ValidationUtil.isEmpty(weldList)){
                    for (Weld weld : weldList) {
                        String longitude = weld.getLongitude();
                        String latitude = weld.getLatitude();
                        if (!ValidationUtil.isEmpty(longitude) && !ValidationUtil.isEmpty(latitude)) {
                            projectDto.setLongitude(longitude);
                            projectDto.setLatitude(latitude);
                            break;
                        }
                    }
                }
        }
        return projectDto;
    }


    public FileDto getInformationDetail(Long sequenceNbr) {
        FileDto fileDto = new FileDto();
        LambdaQueryWrapper<Attachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Attachment::getSourceId, sequenceNbr);
        Attachment attachment = attachmentService.getOne(wrapper);
        JSONObject jsonObject = null;
        ProjectDto detail = projectMapper.getDetail(sequenceNbr);
        if (!ObjectUtils.isEmpty(detail) && !ObjectUtils.isEmpty(detail.getInstanceId())){
            fileDto.setInstanceId(detail.getInstanceId());
        }
        JSONArray installSubForm = JSON.parseArray(XJConstant.INSTALL_SUB_FORM_NEW);
        JSONArray designSubForm = JSON.parseArray(XJConstant.DESIGN_SUB_FORM_NEW);

        if(!ValidationUtil.isEmpty(attachment)){
            jsonObject  =  JSON.parseObject(attachment.getInfo());
        }
        if (!ObjectUtils.isEmpty(jsonObject)) {
            installSubForm = jsonObject.getJSONArray("installSubForm");
            designSubForm = jsonObject.getJSONArray("designSubForm");
        }
        fileDto.setInstallSubForm(installSubForm);
        fileDto.setDesignSubForm(designSubForm);
        fileDto.setStatus(detail.getStatus());
        return fileDto;

    }

    public List<Map<String, Object>> getAuditInformationDetail(Long sequenceNbr) {
        ArrayList<Map<String, Object>> result = new ArrayList<>();
        LambdaQueryWrapper<Attachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Attachment::getSourceId, sequenceNbr);
        Attachment attachment = attachmentService.getOne(wrapper);
        if (!ObjectUtils.isEmpty(attachment) && !ObjectUtils.isEmpty(attachment.getInfo())) {
            Map<String, Object> map = JSON.parseObject(attachment.getInfo());
            List<Map<String, Object>> installSubForm = (List<Map<String, Object>>) map.get("installSubForm");
            data("subFormInstall", installSubForm, result, attachment.getRecDate());
            List<Map<String, Object>> designSubForm = (List<Map<String, Object>>) map.get("designSubForm");
            data("designSubForm", designSubForm, result, attachment.getRecDate());
        }
        return result;
    }

    private List<Map<String, Object>> data(String type, List<Map<String, Object>> data, List<Map<String, Object>> result, Date date) {

        data.forEach(item -> {
            HashMap<String, Object> messageData = new HashMap<>();
            messageData.put("companyName", item.get("type"));
            messageData.put(symbolKey, item.get(symbolKey));
            messageData.put("date", date);
            messageData.put("type", item.get(type));
            List<Map<String, Object>> infoList = (List<Map<String, Object>>) item.get("info");
            messageData.put("files", infoList);
            messageData.put(status, item.getOrDefault("auditStatus", "1"));
            result.add(messageData);
        });
        return result;
    }

    @Transactional
    public String informationSaveOrUpdate(List<Map<String, Object>> equipmentList,
                                          List<Map<String, Object>> welderList,
                                          List<Map<String, Object>> materialList,
                                          JSONObject fileJson,
                                          Long projectId,
                                          String type) {
        // 保存资源信息
        saveResourceMessage(equipmentList, welderList, materialList, projectId);
        // 文件信息
        Attachment attachment = new Attachment();
        attachment.setSourceId(projectId);
        attachment.setInfo(fileJson.toJSONString());
        attachment.setType("project");
        LambdaQueryWrapper<Attachment> attachmentLambda = new QueryWrapper<Attachment>().lambda();
        attachmentLambda.eq(Attachment::getSourceId, projectId);
        attachmentMapper.delete(attachmentLambda);
        attachmentService.save(attachment);
        if ("submit".equals(type)) {
            // 触发流程 todo
        }
        return "ok";

    }

    private void saveResourceMessage(List<Map<String, Object>> equipmentList,
                                     List<Map<String, Object>> welderList,
                                     List<Map<String, Object>> materialList,
                                     Long projectId) {

        ArrayList<ProjectResource> projectResources = new ArrayList<>();
        // 焊机信息
        if (!ObjectUtils.isEmpty(equipmentList)) {
            equipmentList.forEach(item -> {
                ProjectResource projectResource = new ProjectResource();
                projectResource.setProjectId(projectId);
                projectResource.setResourceId(Long.valueOf(String.valueOf(item.get("sequence_nbr"))));
                projectResource.setType("equipment");
                projectResource.setName(String.valueOf(item.get("name")));
                projectResource.setStatus(ObjectUtils.isEmpty(item.get(status)) ? "0" : String.valueOf(item.get(status)));
                projectResources.add(projectResource);
            });
        }
        // 焊工信息
        if (!ObjectUtils.isEmpty(welderList)) {
            welderList.forEach(item -> {
                ProjectResource projectResource = new ProjectResource();
                projectResource.setProjectId(projectId);
                projectResource.setResourceId(Long.valueOf(String.valueOf(item.get("sequenceNbr"))));
                projectResource.setType("welder");
                projectResource.setName(String.valueOf(item.get("name")));
                projectResource.setStatus(ObjectUtils.isEmpty(item.get(status)) ? "0" : String.valueOf(item.get(status)));
                projectResources.add(projectResource);
            });
        }
        // 管材信息
        if (!ObjectUtils.isEmpty(materialList)) {
            materialList.forEach(item -> {
                ProjectResource projectResource = new ProjectResource();
                projectResource.setProjectId(projectId);
                projectResource.setResourceId(Long.valueOf(String.valueOf(item.get("sequenceNbr"))));
                projectResource.setType("material");
                projectResource.setName(String.valueOf(item.get("name")));
                projectResource.setStatus(ObjectUtils.isEmpty(item.get(status)) ? "0" : String.valueOf(item.get(status)));
                projectResources.add(projectResource);
            });
        }
        LambdaQueryWrapper<ProjectResource> lambda = new QueryWrapper<ProjectResource>().lambda();
        lambda.eq(ProjectResource::getProjectId, projectId);
        if (!CollectionUtils.isEmpty(projectResources)) {
            projectResourceMapper.delete(lambda);
            projectResourceService.saveBatch(projectResources);
        }
    }

    @Transactional
    public String informationAudit(List<Map<String, Object>> equipmentList,
                                   List<Map<String, Object>> welderList,
                                   List<Map<String, Object>> materialList,
                                   List<Map<String, Object>> fileList,
                                   Long projectId,
                                   String type) {
        // 保存资源信息
        saveResourceMessage(equipmentList, welderList, materialList, projectId);
        // 文件信息
        LambdaQueryWrapper<Attachment> lambda = new QueryWrapper<Attachment>().lambda();
        lambda.eq(Attachment::getSourceId, projectId);
        List<Attachment> attachments = attachmentMapper.selectList(lambda);
        Attachment attachment = null;
        if (!ObjectUtils.isEmpty(attachments)){
            attachment = attachments.get(0);
        }
        if (!ObjectUtils.isEmpty(attachment) && !ObjectUtils.isEmpty(attachment.getInfo())) {
            Map<String, Object> map = JSON.parseObject(attachment.getInfo());
            List<Map<String, Object>> installSubForm = (List<Map<String, Object>>) map.get("installSubForm");
            // 文件信息json处理
            changeStatus(installSubForm, fileList);
            List<Map<String, Object>> designSubForm = (List<Map<String, Object>>) map.get("designSubForm");
            // 文件信息json处理
            changeStatus(designSubForm, fileList);
            attachment.setInfo(JSON.toJSONString(map));
            attachmentService.saveOrUpdate(attachment);
        }

        if ("submit".equals(type)) {
            // 触发流程 todo
        }
        return "ok";

    }

    private void changeStatus(List<Map<String, Object>> data, List<Map<String, Object>> fileList) {
        data.forEach(item -> {
            List<Map<String, Object>> collect = fileList.stream().filter(itemData -> itemData.get(symbolKey).equals(item.get(symbolKey))).collect(Collectors.toList());
            item.put("auditStatus", ObjectUtils.isEmpty(collect.get(0).get(status)) ? "" : collect.get(0).get(status));
        });
    }
}