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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.yeejoin.amos.boot.module.common.api.entity.FireTeam;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.api.service.IFireTeamService;
import com.yeejoin.amos.boot.module.jcs.api.dto.CarStatusInfoDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.PowerTransferCompanyResourcesDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.jcs.api.entity.JcSituationDetail;
import com.yeejoin.amos.boot.module.jcs.api.entity.PowerTransferCompanyResources;
import com.yeejoin.amos.boot.module.jcs.api.entity.UserCar;
import com.yeejoin.amos.boot.module.jcs.api.enums.FireCarStatusEnum;
import com.yeejoin.amos.boot.module.jcs.api.mapper.JcSituationDetailMapper;
import com.yeejoin.amos.boot.module.jcs.api.mapper.PowerTransferCompanyResourcesMapper;
import com.yeejoin.amos.boot.module.jcs.api.service.IPowerTransferCompanyResourcesService;
import com.yeejoin.amos.boot.module.jcs.api.service.IUserCarService;
import com.yeejoin.amos.component.rule.config.RuleConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 调派单位资源 服务实现类
 *
 * @author tb
 * @date 2021-06-17
 */
@Service
public class PowerTransferCompanyResourcesServiceImpl extends BaseService<PowerTransferCompanyResourcesDto, PowerTransferCompanyResources, PowerTransferCompanyResourcesMapper> implements IPowerTransferCompanyResourcesService {
    @Resource
    PowerTransferCompanyResourcesMapper powerTransferCompanyResourcesMapper;
    @Autowired
    EquipFeignClient equipFeignClient;

    @Autowired
    JcSituationDetailMapper jcSituationDetailMapper;

    @Autowired
    private EmqKeeper emqKeeper;

    @Autowired
    private IUserCarService userCarService;

    @Autowired
    private IFireTeamService fireTeamService;

    @Value("${mqtt.topic.command.power.deployment}")
    private String topic;

    @Override
    public AlertCalled getByPowerTransferCompanyResourId(Long id) {


        QueryWrapper<PowerTransferCompanyResources> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", FireCarStatusEnum.执行中.getCode());
        queryWrapper.eq("resources_id", id.toString());
        PowerTransferCompanyResources alertFormValue = this.getOne(queryWrapper);
        if (alertFormValue != null) {
            return powerTransferCompanyResourcesMapper.getByPowerTransferCompanyResourId(alertFormValue.getPowerTransferCompanyId());
        }
        return null;
    }

    @Override
    public PowerTransferCompanyResources getByAlertCalledIdCarId(Long alertCalledId, Long carId) {
        return powerTransferCompanyResourcesMapper.getByAlertCalledIdCarId(alertCalledId, carId);
    }

    @Override
    public void updateByAlertCalledId(Long alertCalledId) {
        powerTransferCompanyResourcesMapper.updateByAlertCalledId(alertCalledId);
    }


    @Override
    @Transactional
    public void updatePowerTransferCompanyResourcesService(Long alertCalledId, Long carId, String code, int type, String remarks) {

        PowerTransferCompanyResources powerTransferCompanyResources = powerTransferCompanyResourcesMapper.getByAlertCalledIdCarId(alertCalledId, carId);
        UserCar userCar = userCarService.selectByCarId(carId);
        FireTeam fireTeam = fireTeamService.getFireTeamBySequenceNbr(Long.valueOf(userCar.getTeamId()));
        try {

            if (type == 2) {


                powerTransferCompanyResources.setStatus(code);
                powerTransferCompanyResources.setRemarks(remarks);
                powerTransferCompanyResourcesMapper.updateById(powerTransferCompanyResources);

                if("finished".equals(code)){
                    List<Object> carStatusInfoDtoList = new ArrayList();
                    //修改装备信息
                    CarStatusInfoDto carStatusInfo = new CarStatusInfoDto();
                    carStatusInfo.setSequenceNbr(carId + "");
                    carStatusInfo.setStatus(FireCarStatusEnum.执勤.getCode());
                    carStatusInfoDtoList.add(carStatusInfo);
                    // 更新所有车辆状态为执勤
                    equipFeignClient.updateCarStatus(carStatusInfoDtoList);
                }



            } else {
                if (FireCarStatusEnum.到场.getCode().equals(code)){
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    powerTransferCompanyResources.setArrivalTime(format.format(new Date()));
                }
                powerTransferCompanyResources.setCarStatus(code);
                powerTransferCompanyResources.setRemarks(remarks);
                powerTransferCompanyResourcesMapper.updateById(powerTransferCompanyResources);
            }
            String carInfo = "车辆信息（" + fireTeam.getName() + " + " + powerTransferCompanyResources.getResourcesName() + " + " + powerTransferCompanyResources.getResourcesNum() + "）：";
            String info = "";
            info = StrUtil.isNotBlank(remarks) ? carInfo + remarks + " + " + Objects.requireNonNull(FireCarStatusEnum.getEnum(code)).getName() : carInfo + Objects.requireNonNull(FireCarStatusEnum.getEnum(code)).getName();
            JcSituationDetail jcSituationDetail = new JcSituationDetail();
            jcSituationDetail.setAlertCalledId(alertCalledId);
            jcSituationDetail.setInfoType("车辆反馈");
            jcSituationDetail.setInfo(info);
            jcSituationDetailMapper.insert(jcSituationDetail);
            // 车辆状态更改消息推送
            // 定义指令信息消息推送 页面发送mqtt 默认发送 String 类型 0, 新警情 1 警情状态变化
            emqKeeper.getMqttClient().publish(topic, "0".getBytes(), RuleConfig.DEFAULT_QOS, false);
        } catch (Exception e) {
            throw new RuntimeException("修改失败！");
        }


    }

    @Override
    public PowerTransferCompanyResources getResourceById(String resourceId) {
        QueryWrapper<PowerTransferCompanyResources> powerTransferCompanyResourcesQueryWrapper = new QueryWrapper<>();
        powerTransferCompanyResourcesQueryWrapper.eq("resources_id", resourceId);
        return powerTransferCompanyResourcesMapper.selectOne(powerTransferCompanyResourcesQueryWrapper);
    }

    @Override
    public int getCarExecutingCountById(String resourceId, String status) {
        QueryWrapper<PowerTransferCompanyResources> powerTransferCompanyResourcesQueryWrapper = new QueryWrapper<>();
        powerTransferCompanyResourcesQueryWrapper.eq("resources_id", resourceId);
        powerTransferCompanyResourcesQueryWrapper.eq("status", status);
        powerTransferCompanyResourcesQueryWrapper.eq("is_delete", 0);
        return powerTransferCompanyResourcesMapper.selectCount(powerTransferCompanyResourcesQueryWrapper);
    }
}
