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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.google.common.base.Joiner;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
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.apache.commons.collections.CollectionUtils;
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 org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 调派单位资源 服务实现类
 *
 * @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;

    private static  String RESOURCES_ID ="resources_id";
    private static  String PHOTOS ="/photos:";


    @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,List<String> photos) {

        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 + " + " +"<span style=\"color: #fe0c0c \" >"+Objects.requireNonNull(FireCarStatusEnum.getEnum(code)).getName() +"</span>" : carInfo + "<span style=\"color: #fe0c0c \" >"+Objects.requireNonNull(FireCarStatusEnum.getEnum(code)).getName()+"</span>";
            JcSituationDetail jcSituationDetail = new JcSituationDetail();
            jcSituationDetail.setAlertCalledId(alertCalledId);
            jcSituationDetail.setInfoType("车辆反馈");

            jcSituationDetail.setInfo(info);
            if (CollectionUtils.isNotEmpty(photos)){
                jcSituationDetail.setInfo(info+PHOTOS+Joiner.on(",").join(photos));
            }

            jcSituationDetail.setPowerTransferCompanyResourcesId(powerTransferCompanyResources.getSequenceNbr());


            jcSituationDetailMapper.insert(jcSituationDetail);
            // 车辆状态更改消息推送
            // 定义指令信息消息推送 页面发送mqtt 默认发送 String 类型 0, 新警情 1 警情状态变化
            emqKeeper.getMqttClient().publish(topic, "0".getBytes(), RuleConfig.DEFAULT_QOS, false);
        } catch (Exception e) {
            throw new BadRequest("修改失败！");
        }
    }

    @Override
    public List<JcSituationDetail> getTaskFeedback(Long carid, Long alertCalledId) {

        PowerTransferCompanyResources powerTransferCompanyResources = powerTransferCompanyResourcesMapper.getByAlertCalledIdCarId(alertCalledId, carid);

        LambdaQueryWrapper<JcSituationDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JcSituationDetail::getAlertCalledId,alertCalledId);
        wrapper.like(JcSituationDetail::getInfo,powerTransferCompanyResources.getResourcesNum());
        wrapper.eq(JcSituationDetail::getInfoType,"车辆反馈");
        wrapper.eq(JcSituationDetail::getPowerTransferCompanyResourcesId,powerTransferCompanyResources.getSequenceNbr());
        wrapper.orderByDesc(BaseEntity::getRecDate);
        List<JcSituationDetail> list = jcSituationDetailMapper.selectList(wrapper);
        list.stream().forEach(e->{
            if (e.getInfo().contains(PHOTOS)){
                String[] content = e.getInfo().split(PHOTOS);
                String info = content[0];
                String photoUrls = content[1];
                List<String> photos = Arrays.asList(photoUrls);
                e.setInfo(info);
                e.setPhotos(photos);
            }
        });
        return list;
    }


    @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);
    }
}
