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

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.jg.api.dto.JgInstallationNoticeDto;
import com.yeejoin.amos.boot.module.jg.api.entity.JgInstallationNotice;
import com.yeejoin.amos.boot.module.jg.api.entity.JgRelationEquip;
import com.yeejoin.amos.boot.module.jg.api.enums.FlowStatusEnum;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgInstallationNoticeMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgRelationEquipMapper;
import com.yeejoin.amos.boot.module.jg.api.service.IJgInstallationNoticeService;
import com.yeejoin.amos.boot.module.jg.api.dto.JgInstallationNoticeDto;
import com.yeejoin.amos.boot.module.tcm.api.enums.ApplicationFormTypeEnum;
import com.yeejoin.amos.boot.module.tcm.api.service.ICreateCodeService;
import com.yeejoin.amos.feign.workflow.Workflow;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.AjaxResult;
import com.yeejoin.amos.boot.module.jg.biz.service.ICommonService;
import com.yeejoin.amos.feign.workflow.Workflow;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.AjaxResult;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.typroject.tyboot.core.rdbms.service.BaseService;

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

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2023-12-12
 */
@Service
public class JgInstallationNoticeServiceImpl extends BaseService<JgInstallationNoticeDto, JgInstallationNotice, JgInstallationNoticeMapper> implements IJgInstallationNoticeService {

    public static final String SUBMIT_TYPE_FLOW = "1";
    public static final String PROCESS_DEFINITION_KEY = "installationNotification";
    public static final String TABLE_PAGE_ID = "1734141426742095873";


    @Autowired
    private JgInstallationNoticeMapper jgInstallationNoticeMapper;

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     * @return 安装告知
     */
    public Map<String, Map<String, Object>> queryBySequenceNbr(Long sequenceNbr) {
        // 安装告知信息
        JgInstallationNotice notice = jgInstallationNoticeMapper.selectById(sequenceNbr);
        Map<String, Object> installationInfo = BeanUtil.beanToMap(notice);

        installationInfo.put("province", notice.getProvince() + "_" + notice.getProvinceName());
        installationInfo.put("city", notice.getCity() + "_" + notice.getCityName());
        installationInfo.put("county", notice.getCounty() + "_" + notice.getCountyName());

        // 设备信息
        List<Map<String, Object>> equipmentInfos = jgInstallationNoticeMapper.queryEquipInformation(sequenceNbr);

        return new HashMap<String, Map<String, Object>>() {{
            this.put("installationInfo", installationInfo);
            this.put("equipmentInfo", equipmentInfos.get(0));
        }};
    }

    /**
     * 更新安装告知
     *
     * @param noticeDto 安装告知
     */
    @SuppressWarnings("rawtypes")
    public JgInstallationNoticeDto updateInstallationNotice(JgInstallationNoticeDto noticeDto, String op) {
        this.convertField(noticeDto);

        ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
        dto.setProcessDefinitionKey("installationNotification");
        dto.setBusinessKey("1");
        AjaxResult ajaxResult;
        try {
            ajaxResult = Workflow.taskClient.startByVariable(dto);
            String instanceId = ((Map) ajaxResult.get("data")).get("id").toString();
            noticeDto.setInstanceId(instanceId);
            noticeDto.setStatus(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()));
            noticeDto.setNoticeStatus(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()));
            JgInstallationNotice bean = new JgInstallationNotice();
            BeanUtils.copyProperties(noticeDto, bean);
            jgInstallationNoticeMapper.updateById(bean);
        } catch (Exception e) {
            log.error("提交失败：{}", e);
        }

        ajaxResult = Workflow.taskClient.getTask(noticeDto.getInstanceId());
        JSONObject dataObject = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")));
        String taskId = dataObject.getString("id");
        //组装信息
        TaskResultDTO taskResultDTO = new TaskResultDTO();
        taskResultDTO.setResultCode("approvalStatus");
        taskResultDTO.setTaskId(taskId);
        taskResultDTO.setComment("提交流程");
        HashMap<String, Object> map = new HashMap<>();
        map.put("approvalStatus", op);
        taskResultDTO.setVariable(map);
        //执行流程
        AjaxResult ajaxResult1;
        try {
            ajaxResult1 = Workflow.taskClient.completeByTask(taskId, taskResultDTO);
            if (ObjectUtils.isEmpty(ajaxResult1)) {
                noticeDto.setStatus(String.valueOf(FlowStatusEnum.REJECTED.getCode()));
                JgInstallationNotice bean = new JgInstallationNotice();
                BeanUtils.copyProperties(dto,bean);
                jgInstallationNoticeMapper.updateById(bean);
            }
        } catch (Exception e) {
            log.error("提交失败：{}", e);
        }
        return noticeDto;
    }

    @Autowired
    private ICreateCodeService iCreateCodeService;
    @Autowired
    JgRelationEquipMapper jgRelationEquipMapper;

    /**
     * 分页查询
     *
     * @param page  分页对象
     * @param model 查询参数
     * @param type  类型：enterprise-企业端、supervision-监管端
     * @return 安装告知列表
     */
    public Page<JgInstallationNoticeDto> queryForJgInstallationNoticePage(Page<JgInstallationNotice> page, JgInstallationNoticeDto model, String type) {
        Page<JgInstallationNotice> noticePage = jgInstallationNoticeMapper.queryForPage(page, model, type);

        // 将Page<JgInstallationNotice>转化为Page<JgInstallationNoticeDto>
        Page<JgInstallationNoticeDto> noticeDtoPage = new Page<>();
        BeanUtils.copyProperties(noticePage, noticeDtoPage, "records");
        List<JgInstallationNoticeDto> records = noticePage.getRecords().stream().map(notice -> {
            JgInstallationNoticeDto noticeDto = new JgInstallationNoticeDto();
            BeanUtils.copyProperties(notice, noticeDto);
            if (Objects.nonNull(notice.getNoticeStatus())) {
                String noticeStatusDesc = FlowStatusEnum.getNameByType(Long.valueOf(notice.getNoticeStatus()));
                noticeDto.setNoticeStatusDesc(noticeStatusDesc);
            }
            return noticeDto;
        }).collect(java.util.stream.Collectors.toList());
        noticeDtoPage.setRecords(records);

        return noticeDtoPage;
    }

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

    /**
     * 批量删除
     *
     * @param sequenceNbrs 主键
     * @return 是否删除成功
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteForBatch(Long[] sequenceNbrs) {
        if (Objects.isNull(sequenceNbrs) || sequenceNbrs.length == 0) {
            return false;
        }
        Collection<JgInstallationNotice> jgInstallationNotices = this.listByIds(Arrays.asList(sequenceNbrs));
        jgInstallationNotices.forEach(notice -> {
            if (StringUtils.hasText(notice.getInspectUnitId())) {
                throw new IllegalStateException("所选数据已存在流程，不能删除！");
            }
            notice.setIsDelete(true);
        });
        return this.updateBatchById(jgInstallationNotices);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveNotice(String submitType, Map<String, JgInstallationNoticeDto> jgInstallationNoticeDtoMap) {
        JgInstallationNoticeDto model = jgInstallationNoticeDtoMap.get(TABLE_PAGE_ID);
        // 字段转换
        convertField(model);

        // 获取告知设备列表
        List<Map<String, Object>> deviceList = model.getDeviceList();
        if (CollectionUtils.isEmpty(deviceList)) {
            return;
        }

        // 获取告知单号
        List<String> applyNoList = iCreateCodeService.createApplicationFormCode(ApplicationFormTypeEnum.GZ.getCode(), deviceList.size());
        if (CollectionUtils.isEmpty(applyNoList)) {
            return;
        }

        // 判断当前是否为提交
        List<String> instanceIdList = new ArrayList<>();
        if (SUBMIT_TYPE_FLOW.equals(submitType)) {
            // 发起流程
            ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
            for (int i = 0 ; i< deviceList.size(); i++) {
                dto.setProcessDefinitionKey(PROCESS_DEFINITION_KEY);
                AjaxResult ajaxResult = null;
                try {
                    ajaxResult = Workflow.taskClient.startByVariable(dto);
                    String instanceId = ((Map) ajaxResult.get("data")).get("id").toString();
                    instanceIdList.add(instanceId);
                } catch (Exception e) {
                    log.error("流程启动失败：{}", e);
                }
            }
        }

        List<JgInstallationNotice> list = new ArrayList<>();
        List<JgRelationEquip> equipList = new ArrayList<>();
        deviceList.forEach(obj -> {
            JgRelationEquip jgRelationEquip = new JgRelationEquip();
            JgInstallationNotice dto = new JgInstallationNotice();
            BeanUtils.copyProperties(model, dto);
            int i = deviceList.indexOf(obj);
            String applyNo = applyNoList.get(i);
            dto.setApplyNo(applyNo);
            dto.setEquList(String.valueOf(obj.get("SEQUENCE_NBR")));
            jgRelationEquip.setEquipId(String.valueOf(obj.get("SEQUENCE_NBR")));
            jgRelationEquip.setApplyNo(applyNo);
            jgRelationEquip.setBusinessType("GZ");
            if (!CollectionUtils.isEmpty(instanceIdList)) {
                dto.setInstanceId(instanceIdList.get(i));
                dto.setStatus(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()));
            } else {
                dto.setStatus(String.valueOf(FlowStatusEnum.TO_BE_SUBMITTED.getCode()));
            }
            list.add(dto);
            equipList.add(jgRelationEquip);
        });

        jgInstallationNoticeMapper.insertBatchSomeColumn(list);

        List<JgRelationEquip> jgRelationEquipList = equipList.stream().map(jgRelationEquip -> {
            List<JgInstallationNotice> collect = list.stream().filter(jgInstallationNotice -> jgRelationEquip.getApplyNo().equals(jgInstallationNotice.getApplyNo())).collect(Collectors.toList());
            Long sequenceNbr = collect.get(0).getSequenceNbr();
            return jgRelationEquip.setBusinessId(String.valueOf(sequenceNbr));
        }).collect(Collectors.toList());

        jgRelationEquipMapper.insertBatchSomeColumn(jgRelationEquipList);

    }

    private void convertField(JgInstallationNoticeDto model) {
        // 处理图片
        String proxyStatementAttachment = convertImageUrl(model.getInstallContractAttachmentList());
        String installContractAttachment = convertImageUrl(model.getProxyStatementAttachmentList());
        model.setProxyStatementAttachment(proxyStatementAttachment);
        model.setInstallContractAttachment(installContractAttachment);

        // 分割省市区字段
        String province = model.getProvince();
        if (!ObjectUtils.isEmpty(province)) {
            String[] provinceList = province.split("_");
            if (provinceList.length > 1) {
                model.setProvince(provinceList[0]);
                model.setProvinceName(provinceList[1]);
            }
        }

        String city = model.getCity();
        if (!ObjectUtils.isEmpty(city)) {
            String[] cityList = city.split("_");
            if (cityList.length > 1) {
                model.setCity(cityList[0]);
                model.setCityName(cityList[1]);
            }
        }

        String county = model.getCounty();
        if (!ObjectUtils.isEmpty(county)) {
            String[] countyList = county.split("_");
            if (countyList.length > 1) {
                model.setCounty(countyList[0]);
                model.setCountyName(countyList[1]);
            }
        }

        // 分割单位
        String useUnitId = model.getUseUnitId();
        if (!ObjectUtils.isEmpty(useUnitId)) {
            String[] useUnitList = useUnitId.split("_");
            if (useUnitList.length > 1) {
                model.setUseUnitId(useUnitList[0]);
                model.setUseUnitName(useUnitList[1]);
            }
        }

        String receiveOrgId = model.getReceiveOrgId();
        if (!ObjectUtils.isEmpty(receiveOrgId)) {
            String[] receiveOrgIdList = receiveOrgId.split("_");
            if (receiveOrgIdList.length > 1) {
                model.setReceiveOrgId(receiveOrgIdList[0]);
                model.setReceiveOrgName(receiveOrgIdList[1]);
            }
        }

        String inspectUnitId = model.getInspectUnitId();
        if (!ObjectUtils.isEmpty(inspectUnitId)) {
            String[] inspectUnitIdList = inspectUnitId.split("_");
            if (inspectUnitIdList.length > 1) {
                model.setInspectUnitId(inspectUnitIdList[0]);
                model.setInspectUnitName(inspectUnitIdList[1]);
            }
        }
    }

    private String convertImageUrl(List<Map<String, String>> urlList) {
        String urls = "";
        if (!CollectionUtils.isEmpty(urlList)) {
            urls = urlList.stream().map(map -> map.get("url")).collect(Collectors.joining(","));
        }
        return urls;
    }
}