package com.zcloud.service.eightwork.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.mapper.datasource.eightwork.*;
import com.zcloud.service.eightwork.ConfinedspaceService;
import com.zcloud.service.eightwork.HighworkService;
import com.zcloud.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author fangjiakai
 * @date 2024/01/17 11:30
 */
@Service
@Transactional //开启事物
public class ConfinedspaceServiceImpl implements ConfinedspaceService {

    @Autowired
    private HighworkService highworkService;
    @Autowired
    private ConfinedspaceMapper confinedspaceMapper;
    @Autowired
    private EightWorkTaskFlowMapper eightWorkTaskFlowMapper;
    @Autowired
    private EightWorkFlowLogMapper eightWorkFlowLogMapper;
    @Autowired
    private ConfinedspaceSignMapper confinedspaceSignMapper;
    @Autowired
    private ConfinedspaceToMeasuresMapper confinedspaceToMeasuresMapper;
    @Autowired
    private ConfinedSpaceGasMapper confinedspacegasMapper;
    @Autowired
    private EightWorkVideoManagerMapper eightworkvideomanagerMapper;
    @Autowired
    private Smb smb;
    @Autowired
    private SendMessageUtil sendMessageUtil;

    private final String primary_key = "CONFINEDSPACE_ID";
    private final String work_type = "CONFINEDSPACE";

    @Override
    @Transactional
    public void save(PageData pd) throws Exception {
        PageData pd2 = new PageData();
        Calendar calendar = Calendar.getInstance();
        DecimalFormat dft = new DecimalFormat("00");
        int year = calendar.get(Calendar.YEAR);
        String month = dft.format(calendar.get(Calendar.MONTH) + 1);
        String day = dft.format(calendar.get(Calendar.DAY_OF_MONTH));
        pd2.put("CREATDATE", year + "-" + month + "-" + day);
        pd2.put("CORPINFO_ID", pd.get("CORPINFO_ID"));
        pd2 = confinedspaceMapper.getCode(pd2);    //根据ID读取
        String code = "SX" + year + month + day + dft.format((Integer.parseInt(pd2.get("code").toString()) + 1));
        pd.put("CHECK_NO", code);
        pd.put(primary_key, UuidUtil.get32UUID());    //主键
        pd.put("CREATTIME", DateUtil.date2Str(new Date()));    //添加时间
        pd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
        pd.put("ISDELETE", "0");    //是否删除 1-是  0-否
        confinedspaceMapper.save(pd);

        if ("1".equals(pd.get("APPLY_STATUS"))) {
            if (Tools.notEmpty(pd.getString("SPECIAL_WORK"))) {

                // 关联作业票
                String[] specialWorks = pd.getString("SPECIAL_WORK").split(",");
                if (specialWorks.length != 0) {
                    for (int i = 0; i < specialWorks.length; i++) {
                        String[] workNameANo = specialWorks[i].split(" ");
                        highworkService.changeOtherWorkCard(workNameANo, pd.getString("CORPINFO_ID"), "受限作业 " + pd.getString("CHECK_NO"));
                    }
                }
            }
            PageData flow = getStep(pd.get("TASK_ID"), "1");
            saveLog(pd, pd.getString("CREATOR"), "1");
            saveNextSigner(pd, flow);
            if (Tools.notEmpty(pd.getString("PLS_ID"))) {
                setPosition(pd);
            }
        }
    }

    @Override
    @Transactional
    public void edit(PageData pd) throws Exception {
        pd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
        confinedspaceMapper.edit(pd);

        if (pd.get("APPLY_STATUS").equals("1")) {
            pd.put("STEP_ID", 1);
            confinedspaceMapper.editStep(pd);
            // 关联作业票
            String[] specialWorks = pd.getString("SPECIAL_WORK").split(",");
            if (specialWorks.length != 0) {
                for (int i = 0; i < specialWorks.length; i++) {
                    String[] workNameANo = specialWorks[i].split(" ");
                    highworkService.changeOtherWorkCard(workNameANo, pd.getString("CORPINFO_ID"), "受限作业 " + pd.getString("CHECK_NO"));
                }
            }
            PageData flow = getStep(pd.get("TASK_ID"), "1");
            saveLog(pd, pd.getString("CREATOR"), "1");
            saveNextSigner(pd, flow);
            if (Tools.notEmpty(pd.getString("PLS_ID"))) {
                setPosition(pd);
            }
        }
    }

    @Override
    public void delete(PageData pd) throws Exception {
        confinedspaceMapper.delete(pd);
    }

    @Override
    public List<PageData> list(Page page) throws Exception {
        return confinedspaceMapper.datalistPage(page);
    }


    /*
     * 下一步
     */
    @Override
    @Transactional
    public void nextStep(PageData pd, MultipartFile[] files) throws Exception {
        PageData work = this.findById(pd);
        work.putAll(pd);
        List<String> filePaths = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            //保存签名文件
            String ffile = DateUtil.getDays();
            String fileName = UuidUtil.get32UUID() + files[i].getOriginalFilename().substring(files[i].getOriginalFilename().lastIndexOf("."));
            smb.sshSftp(files[i], fileName, Const.FILEPATHFILE + work.getString("CORPINFO_ID") + "/" + ffile);
            filePaths.add(Const.FILEPATHFILE + work.getString("CORPINFO_ID") + "/" + ffile + "/" + fileName);
        }
        PageData flow = getStep(work.get("TASK_ID"), work.get("STEP_ID"));
        work.put("STEP_ID", flow.get("NEXT_STEP_ID"));
        confinedspaceMapper.editVideo(work);

        //保存签名信息
        PageData sign = new PageData();
        if (work.getString("IMG_PATH") != "") {
            sign.put("IMG_PATH", work.get("IMG_PATH"));
        }
        sign.put(primary_key, work.get(primary_key));
        sign.put("STEP_ID", work.get("STEP_ID"));
        sign.put("SIGN_USER_ID", work.get("USER_ID"));
        sign.put("SIGN_TIME", work.getString("SIGNTIME"));
        sign.put("SIGN_PATH", String.join(",", filePaths));
        sign.put("DESCR", work.get("DESCR"));

        confinedspaceSignMapper.edit(sign);

        if (work.get("MEASURES") != null && !work.get("MEASURES").equals("")) { //安全措施确认步骤
            saveMeasures(work);
        }

        List<PageData> unsignedList = confinedspaceSignMapper.checkUnsigned(sign);//当前步骤未签名人列表
        if ((unsignedList == null || unsignedList.size() == 0) && pd.getString("APPLY_STATUS").equals("1")) {//如果没有未签人 则跳转下一步
            confinedspaceMapper.editStep(work);
            PageData currentflow = getStep(work.get("TASK_ID"), work.get("STEP_ID"));

            //保存日志
            saveLog(work, work.getString("USER_ID"), "1");

            if ("99".equals(currentflow.getString("NEXT_STEP_ID"))) {
                eightworkvideomanagerMapper.editStatus(work);
                sendMessageForFinished(work.getString("CORPINFO_ID"), work.getString("CREATOR"), "EIGHTWORK_ACCEPT", work.getString("CHECK_NO"));

                return;
            }
            if (work.get("PREPARERS") != null && !work.get("PREPARERS").equals("")) { //如果是设置安全措施确认人步骤
                savePreparers(work, currentflow);
            }
            saveNextSigner(work, currentflow);
        } else if (pd.getString("APPLY_STATUS").equals("-1")) {
            //保存日志
            saveLog(work, work.getString("USER_ID"), "-1");
            eightworkvideomanagerMapper.editStatus(work);

            work.put("STEP_ID", -1);
            confinedspaceMapper.editStep(work);
            sendMessageForFinished(work.getString("CORPINFO_ID"), work.getString("CREATOR"), "EIGHTWORK_ACCEPT", work.getString("CHECK_NO"));

        }// 作业 监护人停止
        else if ("-3".equals(pd.getString("APPLY_STATUS"))) {
            //保存日志
            saveLog(work, work.getString("USER_ID"), "-3");
            eightworkvideomanagerMapper.editStatus(work);
            work.put("STEP_ID", -3);
            confinedspaceMapper.editStep(work);
            sendMessageForFinished(work.getString("CORPINFO_ID"), work.getString("CREATOR"), "EIGHTWORK_STOP", work.getString("CHECK_NO"));
        }
    }

    private void sendMessageForFinished(String corpinfo_id, String userId, String template, String number) throws Exception {
        PageData mes = new PageData();
        mes.put("RECEIVER_ID", userId);// 收信人userid
        mes.put("templateCode", template);// 短信模板编码
        mes.put("CORPINFO_ID", corpinfo_id);// 企业id

        // 参数集合
        List<PageData> paramsList = new ArrayList<PageData>();
        // 第1个参数
        PageData params1 = new PageData();
        params1.put("name", "number");// 存入短信模板中的参数名称
        params1.put("value", number);// 存入上面参数名称所传递的值
        paramsList.add(params1);

        PageData params2 = new PageData();
        params2.put("name", "type");// 存入短信模板中的参数名称
        params2.put("value", "受限作业");// 存入上面参数名称所传递的值
        paramsList.add(params2);

        try {
            sendMessageUtil.sendMessages(mes, paramsList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PageData findById(PageData pd) throws Exception {
        PageData pageData = confinedspaceMapper.findById(pd);
        return pageData;
    }

    @Override
    public PageData listSignFinished(PageData pd) throws Exception {
        Map<String, List<PageData>> rmap = new HashMap<>();
        List<PageData> varList = confinedspaceSignMapper.listAll(pd);
        if (varList != null && !varList.isEmpty()) {
            varList.stream().forEach(item -> {
                PageData sign = new PageData();
                sign.put("SIGN_PATH", item.getString("SIGN_PATH").split(","));
                sign.put("SIGN_TIME", item.getString("SIGN_TIME").split(","));
                if (item.getString("IMG_PATH") != null || "".equals(item.getString("IMG_PATH"))) {
                    sign.put("IMG_PATH", item.getString("IMG_PATH").split(","));
                }
                sign.put("DESCR", item.getString("DESCR") != null ? item.getString("DESCR") : "无");
                if (rmap.containsKey(item.getString("CODE"))) {
                    rmap.get(item.getString("CODE")).add(sign);
                } else {
                    List<PageData> signs = new ArrayList<>();
                    signs.add(sign);
                    rmap.put(item.getString("CODE"), signs);
                }
            });
        }
        PageData rpd = new PageData();
        if (rmap != null && !rmap.isEmpty()) {
            rpd.putAll(rmap);
        }
        return rpd;
    }

    @Override
    public PageData checkWorkCount(PageData pd) {
        PageData rpd = new PageData();
        List<PageData> varList = confinedspaceMapper.checkWorkCount(pd);

        if (varList != null && !varList.isEmpty()) {
            Map<String, String> newMap = varList.stream().collect(Collectors.toMap(map -> map.getString("CODE"), map -> map.getString("COUNT")));

            rpd.putAll(newMap);
        }
        return rpd;
    }

    @Override
    public List<PageData> listAllMeasures() throws Exception {
        return confinedspaceMapper.listAllMeasures();

    }

    @Override
    public List<PageData> listAllMeasuresForSign(PageData pd) throws Exception {
        return confinedspaceToMeasuresMapper.listAllMeasuresForSign(pd);

    }

    @Override
    public List<PageData> listSignFinishMeasures(PageData pd) throws Exception {
        return confinedspaceToMeasuresMapper.listSignFinishMeasures(pd);
    }

    @Override
    @Transactional
    public void saveGas(PageData pd, MultipartFile[] files) throws Exception {
        PageData work = confinedspaceMapper.findById(pd);
        work.putAll(pd);
        List<String> filePaths = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            //保存签名文件
            String ffile = DateUtil.getDays();
            String fileName = UuidUtil.get32UUID() + files[i].getOriginalFilename().substring(files[i].getOriginalFilename().lastIndexOf("."));
            smb.sshSftp(files[i], fileName, Const.FILEPATHFILE + work.getString("CORPINFO_ID") + "/" + ffile);
            filePaths.add(Const.FILEPATHFILE + work.getString("CORPINFO_ID") + "/" + ffile + "/" + fileName);
        }
        pd.put("CONFINEDSPACEGAS_ID", UuidUtil.get32UUID());    //主键
        pd.put("ISDELETE", "0");    //是否删除 1-是  0-否
        pd.put("SIGN_PATH", String.join(",", filePaths));
        confinedspacegasMapper.save(pd);
        confinedspaceMapper.editGasTime(pd);//修改最后一次气体检测时间

        PageData flow = getStep(work.get("TASK_ID"), work.get("STEP_ID"));
        if (pd.get("APPLY_STATUS").equals("1")) { //如果通过
            if (flow.get("NEXT_STEP_ID") != null && flow.getString("NEXT_STEP_ID").equals("2")) {//如果为气体检测步骤,则保存日志并跳转下一步
                PageData sign = new PageData();
                sign.put(primary_key, work.get(primary_key));
                sign.put("STEP_ID", 2);
                sign.put("SIGN_USER_ID", pd.get("USER_ID"));
                sign.put("SIGN_TIME", DateUtil.date2Str(new Date()));
                sign.put("SIGN_PATH", String.join(",", filePaths));
                sign.put("DESCR", pd.get("DESCR"));
                confinedspaceSignMapper.edit(sign);
                work.put("STEP_ID", flow.get("NEXT_STEP_ID"));
                confinedspaceMapper.editStep(work);

                //保存日志
                saveLog(work, work.getString("USER_ID"), "1");

                //预存下一步
                PageData currentflow = getStep(work.get("TASK_ID"), work.get("STEP_ID"));
                saveNextSigner(work, currentflow);
            }
        } else if (pd.getString("APPLY_STATUS").equals("-1")) {
            PageData sign = new PageData();
            sign.put(primary_key, work.get(primary_key));
            sign.put("STEP_ID", 2);
            sign.put("SIGN_USER_ID", pd.get("USER_ID"));
            sign.put("SIGN_TIME", DateUtil.date2Str(new Date()));
            sign.put("SIGN_PATH", String.join(",", filePaths));
            sign.put("DESCR", pd.get("DESCR"));
            confinedspaceSignMapper.edit(sign);
            //保存日志
            eightworkvideomanagerMapper.editStatus(work);

            work.put("STEP_ID", flow.get("NEXT_STEP_ID"));
            saveLog(work, pd.getString("USER_ID"), "-2");
            work.put("STEP_ID", -1);
            confinedspaceMapper.editStep(work);
            sendMessageForFinished(work.getString("CORPINFO_ID"), work.getString("CREATOR"), "EIGHTWORK_REJECT", work.getString("CHECK_NO"));
        }
    }

    @Override
    public List<PageData> getFlowList(PageData pd) throws Exception {
        pd = findById(pd);
        return confinedspaceMapper.getFlowList(pd);
    }

    @Override
    public ReturnMap getMapList() throws Exception {
        ReturnMap returnMap = new ReturnMap();
        PageData pd = new PageData();
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        returnMap.put("varList", confinedspaceMapper.getMapList(pd));
        return returnMap;
    }

    private void saveNextSigner(PageData pd, PageData flow) throws Exception {

        pd.put("STEP_ID", flow.get("NEXT_STEP_ID"));

        if (pd.get(flow.get("NEXT_ACTOR_FIELD")) == null || pd.get(flow.get("NEXT_ACTOR_FIELD")).equals("")) {
            return;
        }
        //提前保存下一步签字人
        List<PageData> signers = new ArrayList<>();
        PageData signer = new PageData();
        signer.put("CONFINEDSPACE_SIGN_ID", UuidUtil.get32UUID()); // 主键
        signer.put(primary_key, pd.get(primary_key));
        signer.put("CORPINFO_ID", pd.get("CORPINFO_ID"));
        signer.put("SIGN_USER_ID", pd.get(flow.get("NEXT_ACTOR_FIELD")));
        signer.put("STEP_ID", flow.get("NEXT_STEP_ID"));
        signers.add(signer);
        confinedspaceSignMapper.saveBatch(signers);
        sendMessageForNext(pd.getString("CORPINFO_ID"), pd.getString(flow.get("NEXT_ACTOR_FIELD")), pd.getString("CHECK_NO"), flow.getString("NEXT_STEP_NAME"));

    }

    private void sendMessageForNext(String corpinfo_id, String userId, String number, String flow_name) throws Exception {
        PageData mes = new PageData();
        mes.put("RECEIVER_ID", userId);// 收信人userid
        mes.put("templateCode", "EIGHTWORK_REMINDER");// 短信模板编码
        mes.put("CORPINFO_ID", corpinfo_id);// 企业id

        // 参数集合
        List<PageData> paramsList = new ArrayList<PageData>();
        // 第1个参数
        PageData params1 = new PageData();
        params1.put("name", "number");// 存入短信模板中的参数名称
        params1.put("value", number);// 存入上面参数名称所传递的值
        paramsList.add(params1);

        PageData params2 = new PageData();
        params2.put("name", "type");// 存入短信模板中的参数名称
        params2.put("value", "受限作业");// 存入上面参数名称所传递的值
        paramsList.add(params2);

        PageData params3 = new PageData();
        params3.put("name", "flow");// 存入短信模板中的参数名称
        params3.put("value", flow_name);// 存入上面参数名称所传递的值
        paramsList.add(params3);
        try {
            sendMessageUtil.sendMessages(mes, paramsList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void saveMeasures(PageData pd) {
        List<JSONObject> list = (List<JSONObject>) JSON.parse(pd.get("MEASURES").toString());
        for (JSONObject json : list) {
            PageData measure = new PageData();
            measure.put("CONFINEDSPACETOMEASURES_ID", json.get("CONFINEDSPACETOMEASURES_ID"));
            measure.put("STATUS", json.get("STATUS"));
            measure.put("ANSWER1", json.get("ANSWER1"));
            measure.put("ANSWER2", json.get("ANSWER2"));
            measure.put("ANSWER3", json.get("ANSWER3"));
            measure.put("SIGN_PATH", json.get("SIGN_PATH"));
            measure.put("SIGN_TIME", json.get("SIGN_TIME"));
            measure.put("IMG_PATH", json.get("IMG_PATH"));
            confinedspaceToMeasuresMapper.edit(measure);
        }
    }

    private void savePreparers(PageData pd, PageData flow) {
        List<PageData> signers = new ArrayList<>();
        List<JSONObject> list = (List<JSONObject>) JSON.parse(pd.get("PREPARERS").toString());
        for (JSONObject json : list) {
            PageData preparer = new PageData();
            preparer.put("CONFINEDSPACETOMEASURES_ID", UuidUtil.get32UUID()); // 主键
            preparer.put("CONFINEDSPACE_ID", pd.get("CONFINEDSPACE_ID"));
            preparer.put("BUS_CONFINEDSPACE_MEASURES_ID", json.get("BUS_CONFINEDSPACE_MEASURES_ID"));
            preparer.put("CONFIRM_ID", json.get("USER_ID"));
            signers.add(preparer);
        }
        if (signers.size() > 0) {
            confinedspaceToMeasuresMapper.saveBatch(signers);

            //获取所有需要签名人
            List<String> fieldList = signers.stream().map(map -> map.getString("CONFIRM_ID")).collect(Collectors.toList());
            Set<String> fieldSet = new HashSet<>(fieldList); //去重

            List<String> uniqueList = new ArrayList<>(fieldSet);
            List<PageData> nextSigners = new ArrayList<>();
            uniqueList.forEach(item -> { // 保存下一步需要签名的人
                PageData signer = new PageData();
                signer.put("CONFINEDSPACE_SIGN_ID", UuidUtil.get32UUID()); // 主键
                signer.put(primary_key, pd.get(primary_key));
                signer.put("CORPINFO_ID", pd.get("CORPINFO_ID"));
                signer.put("SIGN_USER_ID", item);
                signer.put("STEP_ID", flow.get("NEXT_STEP_ID"));
                nextSigners.add(signer);
                try {
                    sendMessageForNext(pd.getString("CORPINFO_ID"), item, pd.getString("CHECK_NO"), flow.getString("NEXT_STEP_NAME"));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });

            confinedspaceSignMapper.saveBatch(nextSigners);
        }
    }

    private PageData getStep(Object TASK_ID, Object STEP_ID) throws Exception {
        PageData flow = new PageData();
        flow.put("TASK_ID", TASK_ID);
        flow.put("STEP_ID", STEP_ID);
        flow = eightWorkTaskFlowMapper.getStep(flow);
        return flow;
    }

    private void saveLog(PageData pd, String act_user, String status) throws Exception {
        PageData log = new PageData();
        log.put("LOG_ID", UuidUtil.get32UUID());
        log.put("WORK_ID", pd.get(primary_key));
        log.put("TASK_ID", pd.get("TASK_ID"));
        log.put("STEP_ID", pd.get("STEP_ID"));
        log.put("CORPINFO_ID", pd.get("CORPINFO_ID"));
        log.put("CHECK_NO", pd.get("CHECK_NO"));
        log.put("ACT_USER", act_user);
        log.put("ACT_TIME", DateUtil.date2Str(new Date()));
        log.put("STATUS", status);
        log.put("WORK_TYPE", work_type);
        eightWorkFlowLogMapper.save(log);
    }

    private void setPosition(PageData pd) throws Exception {
        JSONObject body = PLSUtil.getRyRegionInfo(pd.getString("CORPINFO_ID"), Integer.parseInt(pd.getString("PLS_ID")));
        List pointList = (List) ((Map) body.get("data")).get("list");
        List<String> positions = PLSUtil.getRandomPointInPolygon(pointList);
        pd.put("WORK_POSITION", String.join(",", positions));
        confinedspaceMapper.setPosition(pd);
    }

}
