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

import cn.hutool.core.bean.BeanUtil;
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 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.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;

    @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 -> 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;
    }
}