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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
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.AlertCalled;
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.enums.DispatchPaperEnums;
import com.yeejoin.amos.boot.module.tzs.api.enums.TzsCommonParam;
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.springframework.transaction.annotation.Transactional;
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;

    @Autowired
    RepairConsultServiceImpl repairConsultServiceImpl;

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

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

    @Override
    public DispatchTaskDto getTaskInfo(String orgTypeCode, Long alertId) {
        DispatchTaskDto dispatchTaskDto = new DispatchTaskDto();
        // 获取警情信息 填充模板返回
        AlertCalledDto alertCalledDto = alertCalledServiceImpl.queryBySeq(alertId);
        dispatchTaskDto.setOrgType(DispatchPaperEnums.getEnumByCode(orgTypeCode).getValue());
        dispatchTaskDto.setOrgTypeCode(DispatchPaperEnums.getEnumByCode(orgTypeCode).getId());
        dispatchTaskDto.setAlertId(alertId);
        dispatchTaskDto.setAlertCode(alertCalledDto.getAlarmTypeCode());
        // 获取模板 拼接json
        LambdaQueryWrapper<Template> templateQueryWrapper = new LambdaQueryWrapper<>();
        String alertTypeCode =   AlertStageEnums.getEnumById(alertCalledDto.getAlarmTypeCode()).getCode()  ;
        templateQueryWrapper.eq(Template::getTypeCode,"TASK-" + alertTypeCode);
        Template template = templateServiceImpl.getOne(templateQueryWrapper);
        String content = template.getContent();
        // 替换模板内容
        // 通用替换字段 报修时间 地址 电梯识别码 使用单位分类
        String createTime = DateUtils.date2LongStr(alertCalledDto.getCallTime());
        String rescueCode = alertCalledDto.getDeviceId();

        String emergencyCall = alertCalledDto.getEmergencyCall()  == null ? "" : alertCalledDto.getEmergencyCall();
        String contactPhone = alertCalledDto.getContactPhone()  == null ? "" : alertCalledDto.getContactPhone();

        // 电梯数据
        Elevator elevator = elevatorServiceImpl.selectByAlertId(alertId);
        String address = elevator.getAddress()  == null ? "" : elevator.getAddress();
        String useSiteCategory = elevator.getUseSiteCategory()  == null ? "" : 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.getId();
        } else if(AlertStageEnums.GZWX.toString().equals(alertTypeCode)) {
            typeCode  = AlertStageEnums.GZWX.getId();
        } else if(AlertStageEnums.TSZX.toString().equals(alertTypeCode)) {
            typeCode  = AlertStageEnums.TSZX.getId();
        }
        // 警情信息动态数据
        LambdaQueryWrapper<AlertFormValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlertFormValue::getAlertCalledId, alertId).eq(AlertFormValue::getAlertTypeCode,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" : // 困人救援
                dispatchTaskDto.setIsSaveTask(true);
                String trappedNum = dynamicParms.get("trapped_num") == null ? "" : dynamicParms.get("trapped_num");
                String trappedFloorNum = dynamicParms.get("trapped_floor_num") == null ? "" : dynamicParms.get("trapped_floor_num");
                String isLight = dynamicParms.get("is_light") == null ? "" : dynamicParms.get("is_light");
                String trappedTime = dynamicParms.get("trapped_time") == null ? "" : 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" : // 故障维修
                dispatchTaskDto.setIsSaveTask(false);
                desc = dynamicParms.get("desc") == null ? "" : dynamicParms.get("desc");
                content = content.replace("$use_unit",useUnit).replace("$desc",desc);
                break;
            case "TSZX" : // 投诉咨询
                dispatchTaskDto.setIsSaveTask(false);
                desc = dynamicParms.get("desc") == null ? "" : 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;
    }

    @Override
    public String returnDistanceByTaskId(Long taskId, String longitude, String latitude) {
        return baseMapper.returnDistanceByTaskId(taskId, longitude, latitude);
    }

    @Transactional
    @Override
    public Boolean createDispatchTask(DispatchTaskDto dispatchTaskDto, AgencyUserModel sendUser) {
        if(sendUser == null) {
            throw  new BadRequest("派遣任务创建人不能为空");
        }
        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);
        if(AlertStageEnums.KRJY.getId().equals(dispatchTaskDto.getAlertCode())) {
            dispatchTask.setIsSaveTask(true);
        }
        dispatchTask.setPaperId(dispatchPaperDto.getDispatchPaper().getSequenceNbr());
        if(dispatchPaper.getRepairOrgTaskId() != null && (dispatchTask.getOrgTypeCode().equals(DispatchPaperEnums.levelOneUnit.getCode()) || dispatchTask.getOrgTypeCode().equals(DispatchPaperEnums.levelTwoUnit.getCode()))) {
            throw new BadRequest("已经派遣过其他力量调派");
        }
        if(dispatchPaper.getUseOrgTaskId() != null && dispatchTask.getOrgTypeCode().equals(DispatchPaperEnums.useUnit.getCode())) {
            throw new BadRequest("已经派遣过使用单位");
        }
        if(dispatchPaper.getRepairOrgTaskId() != null && dispatchTask.getOrgTypeCode().equals(DispatchPaperEnums.repairUnit.getCode()) ) {
            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(AlertStageEnums.getEnumById(dispatchPaper.getAlertCode()).getCode().equals(AlertStageEnums.KRJY.getCode())) {
                        dynamicFormAlert.stream().forEach(alertFormValue -> {
                            if(alertFormValue.getFieldCode().equals("dispatch_status")) {
                                alertFormValue.setFieldValue(DispatchPaperEnums.hasDispatched.getValue());
                                alertFormValue.setFieldValueCode(DispatchPaperEnums.hasDispatched.getId());
                            }
                        });
                    }
                    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(DispatchPaperEnums.hasDispatched.getValue());
                            alertFormValue.setFieldValueCode(DispatchPaperEnums.hasDispatched.getId());
                        } else if(alertFormValue.getFieldCode().equals("response_level")) {
                            alertFormValue.setFieldValue(DispatchPaperEnums.levelOneUnit.getValue());
                            alertFormValue.setFieldValueCode(DispatchPaperEnums.levelOneUnit.getId());
                            // 响应级别反馈给警情
                            LambdaUpdateWrapper<AlertCalled> updateWrapper = new LambdaUpdateWrapper<>();
                            updateWrapper.eq(AlertCalled::getSequenceNbr,dispatchTask.getAlertId());
                            updateWrapper.set(AlertCalled::getResponseLevel,DispatchPaperEnums.levelOneUnit.getValue());
                            alertCalledServiceImpl.update(updateWrapper);
                        } 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(DispatchPaperEnums.hasDispatched.getValue());
                            alertFormValue.setFieldValueCode(DispatchPaperEnums.hasDispatched.getId());
                        } else if(alertFormValue.getFieldCode().equals("response_level")) {
                            alertFormValue.setFieldValue(DispatchPaperEnums.levelTwoUnit.getValue());
                            alertFormValue.setFieldValueCode(DispatchPaperEnums.levelTwoUnit.getId());
                            // 响应级别反馈给警情
                            LambdaUpdateWrapper<AlertCalled> updateWrapper = new LambdaUpdateWrapper<>();
                            updateWrapper.eq(AlertCalled::getSequenceNbr,dispatchTask.getAlertId());
                            updateWrapper.set(AlertCalled::getResponseLevel,DispatchPaperEnums.levelTwoUnit.getValue());
                            alertCalledServiceImpl.update(updateWrapper);
                        }
                    });
                    break;
            }
            //  保存派遣单
            dispatchPaperServiceImpl.updateById(dispatchPaper);
            // 保存动态表单数据
            iAlertFormValueService.updateBatchById(dynamicFormAlert);
            // 记录日志
            repairConsultServiceImpl.saveRepairConsultByAlertIdType(dispatchTask.getAlertId(), TzsCommonParam.PQ, dispatchTask.getSequenceNbr(),sendUser);
            // 派遣后如果困人救援更新派遣过程表
            if(AlertStageEnums.KRJY.getId().equals(dispatchPaper.getAlertCode())) {
                RescueProcessDto rescueProcessDto = rescueProcessServiceImpl.getProcessByAlertId(dispatchTaskDto.getAlertId());
                if(rescueProcessDto.getDispatchStatus() == null && rescueProcessDto.getDispatchTime() == null) {
                    rescueProcessDto.setDispatchStatus(true);
                    rescueProcessDto.setDispatchTime(dispatchTask.getDispatchTime());
                    rescueProcessDto.setDispatchUserName(sendUser.getRealName());
                    rescueProcessDto.setDispatchUserId(dispatchTask.getRecUserId());
                    rescueProcessServiceImpl.updateByAlertId(rescueProcessDto);
                }
            }

        }
        return flag;
    }
}