package com.testor.module.emergency.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.common.constant.EvaluateEnum;
import com.testor.common.constant.RehearsalStatusEnum;
import com.testor.module.emergency.dao.TEmergencyRehearsalDao;
import com.testor.module.emergency.model.domain.TEmergencyRehearsal;
import com.testor.module.emergency.model.domain.TEmergencyRehearsalAccessory;
import com.testor.module.emergency.model.domain.TEmergencyRehearsalEvaluate;
import com.testor.module.emergency.model.dto.EvaluateDTO;
import com.testor.module.emergency.model.dto.TEmergencyRehearsalDTO;
import com.testor.module.emergency.model.dto.TEmergencyRehearsalParam;
import com.testor.module.emergency.model.vo.EvaluateVO;
import com.testor.module.emergency.model.vo.EvaluationDrill;
import com.testor.module.emergency.model.vo.TEmergencyRehearsalVO;
import com.testor.module.emergency.service.TEmergencyRehearsalAccessoryService;
import com.testor.module.emergency.service.TEmergencyRehearsalEvaluateService;
import com.testor.module.emergency.service.TEmergencyRehearsalService;
import com.testor.module.messageNotice.model.domain.TMsgNotice;
import com.testor.module.messageNotice.model.vo.MsgTemplateVO;
import com.testor.module.messageNotice.service.TMsgNoticeService;
import com.testor.module.sys.service.TOrgService;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperModel;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 应急预案演练Service业务层处理
 *
 * @author testor-framework
 * @date 2022-12-02 15:50:38
 */
@Service
public class TEmergencyRehearsalServiceImpl extends SuperServiceImpl<TEmergencyRehearsalDao, TEmergencyRehearsal> implements TEmergencyRehearsalService {

    @Autowired(required = false)
    private TEmergencyRehearsalDao tEmergencyRehearsalDao;

    @Autowired(required = false)
    private TEmergencyRehearsalEvaluateService tEmergencyRehearsalEvaluateService;

    @Autowired(required = false)
    private TEmergencyRehearsalAccessoryService tEmergencyRehearsalAccessoryService;

    @Autowired
    private TMsgNoticeService tMsgNoticeService;

    @Autowired
    private TOrgService tOrgService;

    @Override
    public boolean addAndUpdate(TEmergencyRehearsalDTO addRequest) {
        boolean isSuccess;

        if (ObjectUtil.isEmpty(addRequest.getId())) {
            //新增
            String orgId = ContextUtils.getLoginUser().getOrgId();
            addRequest.setOrgId(orgId);
            addRequest.setRehearsalStatus(RehearsalStatusEnum.NOT_START.getCode());
            addRequest.setSimulationEventType(JSONObject.toJSONString(addRequest.getSimulationEventTypeList()));
            addRequest.setSpecificObjectId(JSONObject.toJSONString(addRequest.getSpecificObjectIdList()));
            String id = IdHelper.getId32bit();
            addRequest.setId(id);
            isSuccess = this.save(addRequest);
            if (isSuccess) {
                // 创建成功进行消息发送
                String totalCommandId = addRequest.getTotalCommandId();
                String participantIds = addRequest.getParticipantIds();
                String rehearsalPlanName = addRequest.getRehearsalPlanName();
                Date startTime = addRequest.getStartTime();
                SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
                String format1 = format.format(startTime);
                List<String> userIdList = new ArrayList<>();
                if (ObjectUtil.isNotEmpty(participantIds)) {
                    String[] split = participantIds.split(",");
                    for (String s : split) {
                        userIdList.add(s);
                    }
                }
                for (int i = 0; i < userIdList.size(); i++) {
                    if (!userIdList.contains(totalCommandId)) {
                        userIdList.add(totalCommandId);
                    }
                }
                sendMsg(userIdList, id, rehearsalPlanName, format1);
            }
        } else {
            //修改
            if (ObjectUtil.isNotEmpty(addRequest.getSimulationEventTypeList())) {
                addRequest.setSimulationEventType(JSONObject.toJSONString(addRequest.getSimulationEventTypeList()));
            }
            isSuccess = this.updateById(addRequest);
        }
        return isSuccess;
    }

    /**
     * 发送消息
     *
     * @param userIdList        接收消息人员集合
     * @param id                业务id
     * @param rehearsalPlanName 计划名称
     * @param format1           开始时间
     */
    private void sendMsg(List<String> userIdList, String id, String rehearsalPlanName, String format1) {
        // XXX（演练计划名称）将于X年X月X日X时X分X秒开始，请您按时参加。
        String msg = rehearsalPlanName + "将于" + format1 + "开始，请您按时参加";
        MsgTemplateVO msgTemplateVO = new MsgTemplateVO();
        msgTemplateVO.setTemplateContent(msg);
        msgTemplateVO.setTemplateType("notice");
        msgTemplateVO.setTemplateTypeName("通知");
        String bizKey = "emergency_rehearsa";
        List<TMsgNotice> tMsgNotices = tMsgNoticeService.generateMsgNotice(bizKey, id, userIdList, msgTemplateVO);
        tMsgNoticeService.saveBatch(tMsgNotices);
    }

    @Override
    public Page<TEmergencyRehearsalVO> listPage(Page<TEmergencyRehearsalVO> resultPage, TEmergencyRehearsalParam param) {
        if (ObjectUtil.isEmpty(param.getOrgIds())) {
            param.setOrgIds(null);
        }
        if (ObjectUtil.isNotEmpty(param.getOrgIds())) {
            String[] split = param.getOrgIds().split(",");
            List<String> strings = Arrays.asList(split);
            param.setOrgIdList(strings);
        }
        Page<TEmergencyRehearsalVO> tEmergencyRehearsalVOPage = tEmergencyRehearsalDao.listPage(resultPage, param);
        List<TEmergencyRehearsalVO> records = tEmergencyRehearsalVOPage.getRecords();
        for (TEmergencyRehearsalVO record : records) {
            SysOrg regionalCompany = tOrgService.getRegionalCompany(record.getOrgId());
            if (regionalCompany != null) {
                record.setBusinessOrgName(regionalCompany.getOrgName());
            }
        }
        return tEmergencyRehearsalVOPage;
    }

    @Override
    public boolean addEvaluate(EvaluateDTO evaluateDTO) {
        String id = evaluateDTO.getId();
        if (ObjectUtil.isEmpty(id)) {
            tEmergencyRehearsalAccessoryService.saveBatch(evaluateDTO.getTEmergencyRehearsalAccessoryList());
            TEmergencyRehearsalEvaluate tEmergencyRehearsalEvaluate = evaluateDTO.getTEmergencyRehearsalEvaluate();
            String toJSONString = JSONObject.toJSONString(evaluateDTO.getMapList());
            tEmergencyRehearsalEvaluate.setEvaluate(toJSONString);
            tEmergencyRehearsalEvaluateService.save(tEmergencyRehearsalEvaluate);
        } else {
            tEmergencyRehearsalAccessoryService.update(
                    new LambdaUpdateWrapper<TEmergencyRehearsalAccessory>()
                            .eq(TEmergencyRehearsalAccessory::getRehearsalId, id).set(SuperModel::getStatus, "1"));
            tEmergencyRehearsalEvaluateService.update(new LambdaUpdateWrapper<TEmergencyRehearsalEvaluate>()
                    .eq(TEmergencyRehearsalEvaluate::getRehearsalId, id).set(SuperModel::getStatus, "1"));

            tEmergencyRehearsalAccessoryService.saveBatch(evaluateDTO.getTEmergencyRehearsalAccessoryList());
            TEmergencyRehearsalEvaluate tEmergencyRehearsalEvaluate = evaluateDTO.getTEmergencyRehearsalEvaluate();
            String toJSONString = JSONObject.toJSONString(evaluateDTO.getMapList());
            tEmergencyRehearsalEvaluate.setEvaluate(toJSONString);
            tEmergencyRehearsalEvaluateService.save(tEmergencyRehearsalEvaluate);

        }

        return true;
    }

    @Override
    public EvaluateVO getEvaluate(String id) {
        EvaluateVO evaluateVO = new EvaluateVO();
        TEmergencyRehearsalEvaluate tEmergencyRehearsalEvaluate = tEmergencyRehearsalEvaluateService.getOne(new LambdaQueryWrapper<TEmergencyRehearsalEvaluate>()
                .eq(SuperModel::getStatus, "0").eq(TEmergencyRehearsalEvaluate::getRehearsalId, id)
        );
        if (ObjectUtil.isEmpty(tEmergencyRehearsalEvaluate)) {
            tEmergencyRehearsalEvaluate = new TEmergencyRehearsalEvaluate();
        }
        List<EvaluationDrill> mapList = null;

        if (ObjectUtil.isNotEmpty(tEmergencyRehearsalEvaluate.getEvaluate())) {
            mapList = JSONObject.parseArray(tEmergencyRehearsalEvaluate.getEvaluate(), EvaluationDrill.class);
        } else {
            ArrayList<EvaluationDrill> maps = new ArrayList<>();
            for (int i = 1; i <= 5; i++) {
                EvaluationDrill evaluationDrill = new EvaluationDrill();
                evaluationDrill.setCount(EvaluateEnum.getEvaluateEnumByCode(i).getMsg());
                maps.add(evaluationDrill);
            }
            mapList = maps;
        }
        List<TEmergencyRehearsalAccessory> accessoriesList = tEmergencyRehearsalAccessoryService.list(new LambdaQueryWrapper<TEmergencyRehearsalAccessory>()
                .eq(SuperModel::getStatus, "0").eq(TEmergencyRehearsalAccessory::getRehearsalId, id)
        );
        evaluateVO.setMapList(mapList);
        evaluateVO.setTEmergencyRehearsalAccessoryList(accessoriesList);
        evaluateVO.setTEmergencyRehearsalEvaluate(tEmergencyRehearsalEvaluate);
        return evaluateVO;
    }
}
