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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.DispatchPaperFormDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.DispatchTaskDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.RescueProcessDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.tzs.api.entity.DispatchPaper;
import com.yeejoin.amos.boot.module.tzs.api.entity.DispatchTask;
import com.yeejoin.amos.boot.module.tzs.api.entity.Elevator;
import com.yeejoin.amos.boot.module.tzs.api.entity.MaintenanceUnit;
import com.yeejoin.amos.boot.module.tzs.api.entity.RescueStation;
import com.yeejoin.amos.boot.module.tzs.api.entity.Template;
import com.yeejoin.amos.boot.module.tzs.api.entity.UseUnit;
import com.yeejoin.amos.boot.module.tzs.api.enums.AlertStageEnums;
import com.yeejoin.amos.boot.module.tzs.api.mapper.DispatchTaskMapper;
import com.yeejoin.amos.boot.module.tzs.api.service.IDispatchTaskService;
import com.yeejoin.amos.boot.module.tzs.api.service.IMaintenanceUnitService;
import com.yeejoin.amos.boot.module.tzs.api.service.IRescueStationService;
import com.yeejoin.amos.boot.module.tzs.api.service.IUseUnitService;
import com.yeejoin.amos.boot.module.tzs.biz.utils.BeanDtoVoUtils;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 派遣任务服务实现类
 *
 * @author system_generator
 * @date 2021-08-03
 */
@Service
public class DispatchTaskServiceImpl extends BaseService<DispatchTaskDto,DispatchTask,DispatchTaskMapper> implements IDispatchTaskService {


    @Autowired
    DispatchPaperServiceImpl dispatchPaperServiceImpl;

    @Autowired
    AlertCalledServiceImpl alertCalledServiceImpl;

    @Autowired
    ElevatorServiceImpl elevatorServiceImpl;

    @Autowired
    TemplateServiceImpl templateServiceImpl;

    @Autowired
    AlertFormValueServiceImpl iAlertFormValueService;

    @Autowired
    IUseUnitService iUseUnitService;

    @Autowired
    IMaintenanceUnitService iMaintenanceUnitService;

    @Autowired
    IRescueStationService iRescueStationService;

    /**
     * 分页查询
     */
    public Page<DispatchTaskDto> queryForDispatchTaskPage(Page<DispatchTaskDto> page)   {
        return this.queryForPage(page, null, false);
    }

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

    @Override
    public Boolean createDispatchTask(DispatchTaskDto dispatchTaskDto, AgencyUserModel sendUser) {
        boolean flag = false;
        // 判断派遣单是否存在 如果不存在先创建派遣单
        DispatchPaperFormDto dispatchPaperDto = dispatchPaperServiceImpl.selectDispatchPaperDtoByAlertId(dispatchTaskDto.getAlertId());
        if(dispatchPaperDto == null || dispatchPaperDto.getDispatchPaper() == null) {
            dispatchPaperDto = dispatchPaperServiceImpl.createDispatchPaper(dispatchTaskDto.getAlertId(), dispatchTaskDto.getAlertCode(), sendUser);
        }
        DispatchPaper dispatchPaper = dispatchPaperDto.getDispatchPaper();
        List<AlertFormValue> dynamicFormAlert = dispatchPaperDto.getDynamicFormAlert();
        // 创建派遣单
        dispatchTaskDto.setDispatchTime(new Date());
        DispatchTask dispatchTask = BeanDtoVoUtils.convert(dispatchTaskDto, DispatchTask.class);
        dispatchTask.setPaperId(dispatchPaperDto.getDispatchPaper().getSequenceNbr());
        if(dispatchPaper.getRepairOrgTaskId() != null && (dispatchTask.getOrgTypeCode().equals("levelOneUnit") || dispatchTask.getOrgTypeCode().equals("levelTwoUnit"))) {
            throw new BadRequest("已经派遣过其他力量调派");
        }
        if(dispatchPaper.getUseOrgTaskId() != null && dispatchTask.getOrgTypeCode().equals("useUnit")) {
            throw new BadRequest("已经派遣过使用单位");
        }
        if(dispatchPaper.getRepairOrgTaskId() != null && dispatchTask.getOrgTypeCode().equals("repairUnit") ) {
            throw new BadRequest("已经派遣过维修单位调派");
        }

        flag = this.save(dispatchTask);
        if(flag) { // 创建好派遣任务单以后根据任务单类型修改派遣单信息
            // 社会信用代码 根据类型查找放入
            MaintenanceUnit maintenanceUnit = null;
            switch (dispatchTask.getOrgTypeCode()) {
                case "useUnit": // 使用单位
                    UseUnit useUnit = iUseUnitService.getById(dispatchTask.getResponseOrgId());
                    dispatchPaper.setUseOrgId(useUnit.getSequenceNbr());
                    dispatchPaper.setUseOrgTaskId(dispatchTask.getSequenceNbr());
                    if(dispatchPaper.getAlertCode().equals("KRJY")) {
                        dynamicFormAlert.stream().forEach(alertFormValue -> {
                            if(alertFormValue.getFieldCode().equals("dispatch_status")) {
                                alertFormValue.setFieldValue("已派遣");
                                alertFormValue.setFieldValueCode("hasDispatched");
                            }
                        });
                    }
                    break;
                case "repairUnit":
                    maintenanceUnit  = iMaintenanceUnitService.getById(dispatchTask.getResponseOrgId());
                    dispatchPaper.setRepairOrgId(maintenanceUnit.getSequenceNbr());
                    dispatchPaper.setRepairOrgTaskId(dispatchTask.getSequenceNbr());
                    break;
                case "levelOneUnit":
                    maintenanceUnit  = iMaintenanceUnitService.getById(dispatchTask.getResponseOrgId());
                    String socialCreditCode = maintenanceUnit.getSocialCreditCode();
                    dispatchPaper.setRepairOrgId(maintenanceUnit.getSequenceNbr());
                    dispatchPaper.setRepairOrgTaskId(dispatchTask.getSequenceNbr());
                    // 修改动态字段
                    dynamicFormAlert.stream().forEach(alertFormValue -> {
                        if(alertFormValue.getFieldCode().equals("dispatch_status")) {
                            alertFormValue.setFieldValue("已派遣");
                            alertFormValue.setFieldValueCode("hasDispatched");
                        } else if(alertFormValue.getFieldCode().equals("response_level")) {
                            alertFormValue.setFieldValue("一级响应");
                            alertFormValue.setFieldValueCode("levelOneUnit");
                        } else if(alertFormValue.getFieldCode().equals("save_credit_code")) {
                            alertFormValue.setFieldValue(socialCreditCode);
                        }
                    });
                    break;
                case "levelTwoUnit":
                    RescueStation rescueStation = iRescueStationService.getById(dispatchTask.getResponseOrgId());
                    dispatchPaper.setRepairOrgId(rescueStation.getSequenceNbr());
                    dispatchPaper.setRepairOrgTaskId(dispatchTask.getSequenceNbr());
                    // 修改动态字段
                    dynamicFormAlert.stream().forEach(alertFormValue -> {
                        if(alertFormValue.getFieldCode().equals("dispatch_status")) {
                            alertFormValue.setFieldValue("已派遣");
                            alertFormValue.setFieldValueCode("hasDispatched");
                        } else if(alertFormValue.getFieldCode().equals("response_level")) {
                            alertFormValue.setFieldValue("二级响应");
                            alertFormValue.setFieldValueCode("levelTwoUnit");
                        }
                    });
                    break;
            }
            //  保存派遣单
            dispatchPaperServiceImpl.updateById(dispatchPaper);
            // 保存动态表单数据
            iAlertFormValueService.updateBatchById(dynamicFormAlert);
        }
        return flag;
    }

    @Override
    public DispatchTaskDto getTaskInfo(String orgTypeCode, Long alertId) {
        DispatchTaskDto dispatchTaskDto = new DispatchTaskDto();
        // 获取警情信息 填充模板返回
        AlertCalledDto alertCalledDto = alertCalledServiceImpl.queryBySeq(alertId);
        dispatchTaskDto.setOrgTypeCode(orgTypeCode);
        dispatchTaskDto.setAlertId(alertId);
        dispatchTaskDto.setAlertCode(alertCalledDto.getAlarmTypeCode());
        // 获取模板 拼接json
        QueryWrapper<Template> templateQueryWrapper = new QueryWrapper<>();
        String alertTypeCode = alertCalledDto.getAlarmTypeCode();
        templateQueryWrapper.eq("type_code","TASK-" + alertTypeCode);
        Template template = templateServiceImpl.getOne(templateQueryWrapper);
        String content = template.getContent();
        // 替换模板内容
        // 通用替换字段 报修时间 地址 电梯识别码 使用单位分类
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        String createTime = sdf.format(alertCalledDto.getCallTime());
        String rescueCode = alertCalledDto.getDeviceId();

        String emergencyCall = alertCalledDto.getEmergencyCall();
        String contactPhone = alertCalledDto.getContactPhone();
        // 电梯数据
        Elevator elevator = elevatorServiceImpl.selectByAlertId(alertId);
        String address = elevator.getAddress();
        String useSiteCategory = elevator.getUseSiteCategory();
        String useUnit = elevator.getUseUnit();
        content = content.replace("$call_time",createTime).replace("$address",address).replace("$rescue_code",rescueCode).replace("$use_site_category",useSiteCategory);
        String typeCode = "";
        if(AlertStageEnums.KRJY.toString().equals(alertTypeCode)) {
            typeCode  = AlertStageEnums.KRJY.getCode();
        } else if(AlertStageEnums.GZWX.toString().equals(alertTypeCode)) {
            typeCode  = AlertStageEnums.GZWX.getCode();
        } else if(AlertStageEnums.TSZX.toString().equals(alertTypeCode)) {
            typeCode  = AlertStageEnums.TSZX.getCode();
        }
        // 警情信息动态数据
        QueryWrapper<AlertFormValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("alert_called_id", alertId).eq("alert_type_code",typeCode);
        // 派遣单动态表单数据
        List<AlertFormValue> list = iAlertFormValueService.list(queryWrapper);
        // map 存取数据
        Map<String,String> dynamicParms = new HashMap<String,String> ();
        list.stream().forEach(paperFormValue -> {
            dynamicParms.put(paperFormValue.getFieldCode(),paperFormValue.getFieldValue());
        });
        String desc = "";
        switch(alertTypeCode) {
            case "KRJY" : // 困人救援
                String trappedNum = dynamicParms.get("trapped_num");
                String trappedFloorNum = dynamicParms.get("trapped_floor_num");
                String isLight = dynamicParms.get("is_light");
                String trappedTime = dynamicParms.get("trapped_time");
                content = content.replace("$trapped_num",trappedNum).replace("$trapped_floor_num",trappedFloorNum);
                content = content.replace("$emergency_call",emergencyCall).replace("$contact_phone",contactPhone);
                content = content.replace("$is_light",isLight).replace("$trapped_time",trappedTime);
                break;
            case "GZWX" : // 故障维修
                desc = dynamicParms.get("desc");
                content = content.replace("$use_unit",useUnit).replace("$desc",desc);
                break;
            case "TSZX" : // 投诉咨询
                desc = dynamicParms.get("desc");
                content = content.replace("$emergency_call",emergencyCall).replace("$contact_phone",contactPhone);
                content = content.replace("$use_unit",useUnit).replace("$desc",desc);
                break;
        }
        dispatchTaskDto.setDispatchContext(content);
        return dispatchTaskDto;
    }
}