package com.yeejoin.amos.boot.module.hygf.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.fasterxml.jackson.databind.ObjectMapper;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.hygf.api.Enum.PowerStationNodeEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.PowerStationProcessStateEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.TaskTypeStationEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
import com.yeejoin.amos.boot.module.hygf.api.fegin.IdxFeginService;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PersonnelBusinessMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.SurveyInformationMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.ToDoTasksMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.UserMessageMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IPowerStationService;
import com.yeejoin.amos.boot.module.hygf.api.service.ISurveyInformationService;
import com.yeejoin.amos.boot.module.hygf.api.util.BeanDtoUtils;
import com.yeejoin.amos.boot.module.hygf.api.dto.DesignInformationDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.DesignInformation;
import com.yeejoin.amos.boot.module.hygf.biz.feign.WorkflowFeignClient;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

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

/**
 * 勘察信息服务实现类
 *
 * @author system_generator
 * @date 2023-07-07
 */
@Service
@Slf4j
public class SurveyInformationServiceImpl extends BaseService<SurveyInformationDto,SurveyInformation,SurveyInformationMapper> implements ISurveyInformationService {


    @Autowired
    SurveyDetailsServiceImpl surveyDetailsService;

    @Autowired
    InformationServiceImpl informationService;

    @Autowired
    ExtendedInformationServiceImpl extendedInformationService;

    @Autowired
    CommercialServiceImpl commercialService;

    @Autowired
    PeasantHouseholdServiceImpl peasantHouseholdServiceImpl;

    @Autowired
    DesignInformationServiceImpl designInformationService;

    @Autowired
    WorkflowFeignClient workflowFeignClient;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    IdxFeginService idxFeginService;

    @Autowired
    IPowerStationService powerStationService;
    @Autowired
    ToDoTasksMapper toDoTasksMapper;
    @Autowired
    UserMessageMapper userMessageMapper;
    @Value("${power.station.examine.pageId}")
    private long pageId;
    @Autowired
    protected EmqKeeper emqKeeper;
    @Value("${power.station.examine.planId}")
    private String planId;

    private static final String regionRedis="app_region_redis";
    private static final String OPERATION_TYPE_SUBMIT="submit";
    private static final String OPERATION_TYPE_APPLY="apply";
    private static final String IDX_REQUEST_STATE="200";
    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;
    /**
     * 分页查询
     */
    public Page<SurveyInformationDto> queryForSurveyInformationPage(Page<SurveyInformationDto> page)   {
        return this.queryForPage(page, "rec_date", false);
    }

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

    @Transactional
    public SurveyInfoAllDto saveSurveyInfo(SurveyInfoAllDto surveyInfoAllDto,String operationType)   {
        try {


        JSONArray regionName = getRegionName();
        List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);

        //更新勘察基本信息
        SurveyInformation surveyInformation = BeanDtoUtils.convert(surveyInfoAllDto.getSurveyInformation(), SurveyInformation.class);
        surveyInformation.setReview(0);
        this.saveOrUpdate(surveyInformation);

        //更新扩展信息
        ExtendedInformation extendedInformation = BeanDtoUtils.convert(surveyInfoAllDto.getExtendedInformation(), ExtendedInformation.class);
        extendedInformation.setSurveyInformationId(surveyInformation.getSequenceNbr());
        extendedInformationService.saveOrUpdate(extendedInformation);

        //更新勘察明细信息
        SurveyDetailsDto oldSurveyDetails = surveyInfoAllDto.getSurveyDetails();
        SurveyDetails surveyDetails = BeanDtoUtils.convert(oldSurveyDetails, SurveyDetails.class);
        surveyDetails.setSurveyInformationId(surveyInformation.getSequenceNbr());
        surveyDetailsService.saveOrUpdate(surveyDetails);

        //更新商务信息
        CommercialDto oldCommercial = surveyInfoAllDto.getCommercial();
        Commercial commercial = BeanDtoUtils.convert(oldCommercial, Commercial.class);
        // 处理省市县
        String paddressName = "";
        for (Integer reg : surveyInfoAllDto.getSurveyInformation().getProjectAddress()) {
            for (RegionModel re : list) {
                if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                    paddressName = paddressName + re.getRegionName() + "/";
                }
            }
        }
        commercial.setProjectAddressName(paddressName.substring(0, paddressName.length() - 2));
        commercial.setSurveyInformationId(surveyInformation.getSequenceNbr());
        commercialService.saveOrUpdate(commercial);

        //更新资料归档信息
        Information information = BeanDtoUtils.convert(surveyInfoAllDto.getInformation(), Information.class);
        information.setSurveyInformationId(surveyInformation.getSequenceNbr());
        informationService.saveOrUpdate(information);

        //勘察后，更新状态
        QueryWrapper<PeasantHousehold> peasantHouseholdQueryWrapper = new QueryWrapper<>();
        peasantHouseholdQueryWrapper.eq("survey_information_id", surveyInformation.getSequenceNbr());
        PeasantHousehold peasantHousehold = peasantHouseholdServiceImpl.getBaseMapper().selectOne(peasantHouseholdQueryWrapper);

        peasantHousehold.setOwnersName(surveyInfoAllDto.getSurveyInformation().getOwnersName());
        peasantHousehold.setTelephone(surveyInfoAllDto.getSurveyInformation().getTelephone());
        peasantHousehold.setIdCard(surveyInfoAllDto.getSurveyInformation().getIdCard());
        peasantHousehold.setMailbox(surveyInfoAllDto.getSurveyInformation().getMailbox());
        peasantHousehold.setProjectAddress(surveyInfoAllDto.getSurveyInformation().getProjectAddress());
        peasantHousehold.setProjectAddressDetail(surveyInfoAllDto.getSurveyInformation().getProjectAddressDetail());
        peasantHousehold.setPermanentAddress(surveyInfoAllDto.getSurveyInformation().getPermanentAddress());
        peasantHousehold.setPermanentAddressDetail(surveyInfoAllDto.getSurveyInformation().getPermanentAddressDetail());
        peasantHousehold.setPermanentAddressDetail(surveyInfoAllDto.getSurveyInformation().getPermanentAddressDetail());

        // 处理项目地址
        String projectAddressName = "";
        for (Integer reg : surveyInfoAllDto.getSurveyInformation().getProjectAddress()) {
            for (RegionModel re : list) {
                if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                    projectAddressName = projectAddressName + re.getRegionName() + "/";
                }
            }
        }
        peasantHousehold.setProjectAddressName(projectAddressName.substring(0, projectAddressName.length() - 2));
        //常住地址
        String permanentAddressName = "";
        for (Integer reg : surveyInfoAllDto.getSurveyInformation().getPermanentAddress()) {
            for (RegionModel re : list) {
                if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                    permanentAddressName = permanentAddressName + re.getRegionName() + "/";
                }
            }
        }
        peasantHousehold.setPermanentAddressName(permanentAddressName.substring(0, permanentAddressName.length() - 2));

        if(OPERATION_TYPE_SUBMIT.equals(operationType)){
            peasantHousehold.setSurveyOrNot(1);
        }else if(OPERATION_TYPE_APPLY.equals(operationType)){
            // 提交审核
            submitExamine(peasantHousehold);
            LambdaQueryWrapper<ToDoTasks> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ToDoTasks::getType, TaskTypeStationEnum.电站勘察.getCode());
            wrapper.eq(ToDoTasks::getState, "待办");
            wrapper.eq(ToDoTasks::getBusinessId, peasantHousehold.getSequenceNbr());
            ToDoTasks doTasks= toDoTasksMapper.selectOne(wrapper);
            if(doTasks!=null){
                doTasks.setState("已办");
                doTasks.setCompleteTime(new Date());
                toDoTasksMapper.updateById(doTasks);
                emqKeeper.getMqttClient().publish("TASK_MESSAGE" ,JSON.toJSONString(doTasks).getBytes(), 2 ,false);

                UserMessage userMessage=  new UserMessage( doTasks.getType(),  doTasks.getBusinessId(),  doTasks.getAmosUserId(),  new Date(),  doTasks.getTaskName()+"已完成",  doTasks.getAmosOrgCode());
                userMessageMapper.insert(userMessage);
                emqKeeper.getMqttClient().publish("MY_MESSAGE" ,JSON.toJSONString(userMessage).getBytes(), 2 ,false);

            }
        }
        peasantHouseholdServiceImpl.saveOrUpdate(peasantHousehold);



        }catch (Exception e){
            e.printStackTrace();
            throw new BadRequest("系统异常");
        }

        return surveyInfoAllDto;
    }

    private void submitExamine(PeasantHousehold peasantHousehold) {
        PowerStation powerStation = powerStationService.getObjByNhId(String.valueOf(peasantHousehold.getSequenceNbr()), PowerStationProcessStateEnum.作废.getCode());

        String taskId = null;
        Map<String, Object> objectMap = new HashMap<>(1);
        objectMap.put("describe", "经销商已上传信息");
        if (ObjectUtils.isNotEmpty(powerStation)) {
            // 工作流执行一步
            taskId = powerStation.getTaskId();
        } else {
            // 第一步启动工作流
            powerStation = new PowerStation();
        }
        // 保存并审核
        try {
            FeignClientResult<String> submit = idxFeginService.submit(pageId, taskId, planId, null, "STATION_AUDIT", null, objectMap);
            if (IDX_REQUEST_STATE.equals(String.valueOf(submit.getStatus()))) {
                peasantHousehold.setSurveyOrNot(2);
                peasantHousehold.setReview(1);
                String code = submit.getResult();
                // 插入记录表
                powerStation.setPlanInstanceId(planId);
                powerStation.setPowerStationCode(peasantHousehold.getPeasantHouseholdNo());
                powerStation.setOwnersName(peasantHousehold.getOwnersName());
                powerStation.setProjectAddress(peasantHousehold.getProjectAddressName());
                powerStation.setPeasantHouseholdId(String.valueOf(peasantHousehold.getSequenceNbr()));
                powerStation.setProcessStatus(PowerStationProcessStateEnum.进行中.getName());
                powerStation.setServiceAgent(peasantHousehold.getDeveloperName());
                log.info("流程执行成功：{}", code);
                // 获取流程信息
                FeignClientResult<JSONObject> record = idxFeginService.getRecord(code);
                if (IDX_REQUEST_STATE.equals(String.valueOf(record.getStatus()))) {
                    JSONObject resultObj = record.getResult();
                    String taskIdNew = String.valueOf(resultObj.get("taskId"));
                    String processInstanceId = String.valueOf(resultObj.get("processInstanceId"));
                    String flowTaskId = String.valueOf(resultObj.get("flowTaskId"));
                    powerStation.setTaskId(taskIdNew);
                    powerStation.setProcessInstanceId(processInstanceId);
                    powerStation.setFlowTaskId(flowTaskId);
                    powerStation.setNextProcessNode(PowerStationNodeEnum.设计审核.getCode());
                }
                powerStationService.savePowerStation(powerStation, true,powerStation.getOwnersName(),"");
            }
        } catch (Exception e){
            e.printStackTrace();
            throw new BaseException("获取工作流节点失败！","400","获取工作流节点失败！");
        }
    }

    public SurveyInfoAllDto querySurveyInfo(String surveyInformationId,String peasantHouseholdId,String processInstanceId,AgencyUserModel userInfo)   {

        SurveyInfoAllDto surveyInfoAllDto = new SurveyInfoAllDto();
        PeasantHousehold peasantHousehold = new PeasantHousehold();
        if(!StringUtils.isEmpty(peasantHouseholdId)){
            LambdaQueryWrapper<PeasantHousehold> peasantHouseholdWrapper = new LambdaQueryWrapper<>();
            peasantHouseholdWrapper.eq(PeasantHousehold::getSequenceNbr, peasantHouseholdId);
            peasantHousehold = peasantHouseholdServiceImpl.getBaseMapper().selectOne(peasantHouseholdWrapper);
            surveyInformationId = String.valueOf(peasantHousehold.getSurveyInformationId());
        }else {
            QueryWrapper<PeasantHousehold> peasantHouseholdQueryWrapper = new QueryWrapper<>();
            peasantHouseholdQueryWrapper.eq("survey_information_id", surveyInformationId);
            peasantHousehold = peasantHouseholdServiceImpl.getBaseMapper().selectOne(peasantHouseholdQueryWrapper);
        }
        //勘察基本信息
        LambdaQueryWrapper<SurveyInformation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SurveyInformation::getSequenceNbr, surveyInformationId);
        SurveyInformation surveyInformation = this.baseMapper.selectOne(queryWrapper);
        surveyInfoAllDto.setSurveyInformation(BeanDtoUtils.convert(surveyInformation, SurveyInformationDto.class));
        //农户信息


        //获取用户所在经销商单位
        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto(peasantHousehold.getDeveloperUserId());

        BeanUtils.copyProperties(peasantHousehold, surveyInfoAllDto.getSurveyInformation());
        surveyInfoAllDto.getSurveyInformation().setDeveloperName(userUnitInformationDto.getAmosDealerName());
        surveyInfoAllDto.getSurveyInformation().setDeveloperCode(userUnitInformationDto.getAmosDealerOrgCode());
        surveyInfoAllDto.getSurveyInformation().setDeveloperId(userUnitInformationDto.getAmosDealerId());
         if(surveyInfoAllDto.getSurveyInformation().getSalesmanId()==null){
          surveyInfoAllDto.getSurveyInformation().setSalesmanId(userInfo.getUserId());
          surveyInfoAllDto.getSurveyInformation().setSalesman(userInfo.getRealName());
          surveyInfoAllDto.getSurveyInformation().setCreator(userInfo.getRealName());
         }

        if (!StringUtils.isEmpty(peasantHousehold.getProjectAddressName())) {
            surveyInfoAllDto.getSurveyInformation().setProjectAddressText(Arrays.asList(peasantHousehold.getProjectAddressName().split("/")));
        }
        if(!StringUtils.isEmpty(peasantHousehold.getPermanentAddressName())){
            surveyInfoAllDto.getSurveyInformation().setPermanentAddressText(Arrays.asList(peasantHousehold.getPermanentAddressName().split("/")));
        }

        if(peasantHousehold.getPermanentAddress() ==null){
            surveyInfoAllDto.getSurveyInformation().setPermanentAddress(peasantHousehold.getProjectAddress());
            surveyInfoAllDto.getSurveyInformation().setIsPermanent("1");
        }


        surveyInfoAllDto.getSurveyInformation().setSequenceNbr(surveyInformation.getSequenceNbr());
        surveyInfoAllDto.getSurveyInformation().setCreatorTime(new Date());
        QueryWrapper<SurveyDetails> surveyDetailsQueryWrapper = new QueryWrapper<>();
        surveyDetailsQueryWrapper.eq("survey_information_id", surveyInformationId);
        SurveyDetails surveyDetails = surveyDetailsService.getBaseMapper().selectOne(surveyDetailsQueryWrapper);

        if(surveyDetails == null){
            surveyInfoAllDto.setSurveyDetails(new SurveyDetailsDto());
        }else {
            surveyInfoAllDto.setSurveyDetails(BeanDtoUtils.convert(surveyDetails, SurveyDetailsDto.class));
        }

        QueryWrapper<Information> informationQueryWrapper = new QueryWrapper<>();
        informationQueryWrapper.eq("survey_information_id", surveyInformationId);
        Information information = informationService.getBaseMapper().selectOne(informationQueryWrapper);

        if(information == null){
            surveyInfoAllDto.setInformation(new InformationDto());
        }else {
            surveyInfoAllDto.setInformation(BeanDtoUtils.convert(information, InformationDto.class));
        }
        QueryWrapper<Commercial> commercialQueryWrapper = new QueryWrapper<>();
        commercialQueryWrapper.eq("survey_information_id", surveyInformationId);
        Commercial commercial = commercialService.getBaseMapper().selectOne(commercialQueryWrapper);
        if(commercial==null){
            commercial=new   Commercial();
        }
        commercial.setApplicant(peasantHousehold.getOwnersName());
        commercial.setIdCard(peasantHousehold.getIdCard());
        commercial.setTelephone(peasantHousehold.getTelephone());
        commercial.setProjectAddress(peasantHousehold.getProjectAddress());
        commercial.setProjectAddressName(peasantHousehold.getProjectAddressName());
        commercial.setProjectAddressDetail(peasantHousehold.getProjectAddressDetail());
        commercial.setLegalContactTelephone(peasantHousehold.getTelephone());



        if(information == null){
            CommercialDto commercialDto = BeanDtoUtils.convert(commercial, CommercialDto.class);
            commercialDto.setType("zrr");
            commercialDto.setLegalType("zjdnhw");
            surveyInfoAllDto.setCommercial(commercialDto);
        }else {
            surveyInfoAllDto.setCommercial(BeanDtoUtils.convert(commercial, CommercialDto.class));
            if(commercial !=null && !StringUtils.isEmpty(commercial.getProjectAddressName())){
                surveyInfoAllDto.getCommercial().setProjectAddressText(Arrays.asList(commercial.getProjectAddressName().split("/")));
            }
        }

        QueryWrapper<ExtendedInformation> extendedInformationQueryWrapper = new QueryWrapper<>();
        extendedInformationQueryWrapper.eq("survey_information_id", surveyInformationId);
        ExtendedInformation extendedInformation = extendedInformationService.getBaseMapper().selectOne(extendedInformationQueryWrapper);
        if(information == null){
            surveyInfoAllDto.setExtendedInformation(new ExtendedInformationDto());
        }else {
            surveyInfoAllDto.setExtendedInformation(BeanDtoUtils.convert(extendedInformation, ExtendedInformationDto.class));
        }

        QueryWrapper<DesignInformation> designInformationQueryWrapper = new QueryWrapper<>();
        designInformationQueryWrapper.eq("peasant_household_id", peasantHousehold.getSequenceNbr());
        DesignInformation designInformation = designInformationService.getBaseMapper().selectOne(designInformationQueryWrapper);
        if(designInformation == null){
            surveyInfoAllDto.setDesignInformation(new DesignInformationDto());
        }else {
            surveyInfoAllDto.setDesignInformation(BeanDtoUtils.convert(designInformation, DesignInformationDto.class));
        }

        if(!StringUtils.isEmpty(processInstanceId)){
            try {
            Map<String, Object> flowLoggerMap = workflowFeignClient.getFlowLogger(processInstanceId).getResult();
            List<LinkedHashMap> flowLogger = (List<LinkedHashMap>) flowLoggerMap.get("flowLogger");
                List<LinkedHashMap> flowLoggernew =new ArrayList<>();
                for (LinkedHashMap linkedHashMap : flowLogger) {
                    if(linkedHashMap.get("operateDate")!=null&&!linkedHashMap.get("operateDate").toString().isEmpty()){
                        LinkedHashMap linke=new LinkedHashMap();
                        linke.put("approvalStatue",linkedHashMap.get("approvalStatue").toString().equals("0")?"通过":"驳回");
                        //审核意见
                        List<LinkedHashMap> approvalSuggestion = (List<LinkedHashMap>)linkedHashMap.get("approvalSuggestion");
                        if(approvalSuggestion!=null&&!approvalSuggestion.isEmpty()){
                            linke.put("approvalSuggestion",approvalSuggestion.get(0).get("message"));
                        }
                        linke.put("taskName",linkedHashMap.get("taskName").toString());
                        linke.put("operator",linkedHashMap.get("operator").toString());
                        linke.put("operateDate",linkedHashMap.get("operateDate").toString());
                        flowLoggernew.add(linke);
                    }
                }
            LoggerDto loggerDto =new  LoggerDto();
            loggerDto.setLogger(flowLoggernew);
            surveyInfoAllDto.setOrderTracking(loggerDto);
        } catch (Exception e){
            e.printStackTrace();
        }
        }
        return surveyInfoAllDto;
    }


    public JSONArray getRegionName(){
        JSONArray jsonArray = new JSONArray();
        if (redisUtils.hasKey(regionRedis)) {
            jsonArray= JSONArray.parseArray(redisUtils.get(regionRedis).toString());
        }else {
            Collection<RegionModel> regionChild = new ArrayList<>();
            RegionModel regionModel1 = new RegionModel();
            regionChild.add(regionModel1);
            FeignClientResult<Collection<RegionModel>> collectionFeignClientResult = Systemctl.regionClient.queryForTreeParent(610000L);
            Collection<RegionModel> result = collectionFeignClientResult.getResult();
            for (RegionModel regionModel : result) {
                if(regionModel.getChildren()!=null&&!regionModel.getChildren().isEmpty()){
                    for (RegionModel child : regionModel.getChildren()) {
                        if(child.getChildren()!=null&&!child.getChildren().isEmpty()){
                            for (RegionModel childChild : child.getChildren()) {
                                jsonArray.add(childChild);
                            }
                            child.setChildren(regionChild);
                            jsonArray.add(child);
                        }

                    }
                }

                regionModel.setChildren(regionChild);
                jsonArray.add(regionModel);
            }

            redisUtils.set(regionRedis,jsonArray);
        }
        return jsonArray;
    }
}