package com.njzscloud.supervisory.device.service;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.common.mqtt.util.MqttUtil;
import com.njzscloud.supervisory.device.contant.DeviceCode;
import com.njzscloud.supervisory.device.mapper.DeviceInfoMapper;
import com.njzscloud.supervisory.device.pojo.entity.DeviceInfoEntity;
import com.njzscloud.supervisory.order.contant.CheckStatus;
import com.njzscloud.supervisory.order.contant.OrderStatus;
import com.njzscloud.supervisory.order.pojo.entity.OrderInfoEntity;
import com.njzscloud.supervisory.order.pojo.param.DeviceRecognitionParam;
import com.njzscloud.supervisory.order.pojo.param.TruckComingOrderParam;
import com.njzscloud.supervisory.order.pojo.param.TruckLeavingOrderParam;
import com.njzscloud.supervisory.order.pojo.result.OrderPagingResult;
import com.njzscloud.supervisory.order.service.OrderInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 设备信息表
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeviceInfoService extends ServiceImpl<DeviceInfoMapper, DeviceInfoEntity> implements IService<DeviceInfoEntity> {
    private final OrderInfoService orderInfoService;

    /**
     * 新增
     *
     * @param deviceInfoEntity 数据
     */
    public void add(DeviceInfoEntity deviceInfoEntity) {
        this.save(deviceInfoEntity);
    }

    /**
     * 修改
     *
     * @param deviceInfoEntity 数据
     */
    public void modify(DeviceInfoEntity deviceInfoEntity) {
        this.updateById(deviceInfoEntity);
    }

    /**
     * 删除
     *
     * @param ids Ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 详情
     *
     * @param id Id
     * @return DeviceInfoEntity 结果
     */
    public DeviceInfoEntity detail(Long id) {
        return this.getById(id);
    }

    /**
     * 分页查询
     *
     * @param deviceInfoEntity 筛选条件
     * @param pageParam        分页参数
     * @return PageResult&lt;DeviceInfoEntity&gt; 分页结果
     */
    public PageResult<DeviceInfoEntity> paging(PageParam pageParam, DeviceInfoEntity deviceInfoEntity) {
        return PageResult.of(this.page(pageParam.toPage(), Wrappers.<DeviceInfoEntity>query(deviceInfoEntity)));
    }

    public void recognition(DeviceRecognitionParam deviceRecognitionParam) {
        String sn = deviceRecognitionParam.getSn();
        DeviceInfoEntity deviceInfoEntity = this.getOne(Wrappers.<DeviceInfoEntity>lambdaQuery().eq(DeviceInfoEntity::getSn, sn));
        if (deviceInfoEntity == null) {
            log.error("设备不存在：{}", deviceRecognitionParam);
            return;
        }

        DeviceCode deviceCode = deviceInfoEntity.getDeviceCode();

        switch (deviceCode) {
            // TODO 进前置不启用
            case JinQianZhi: {
                OrderPagingResult orderInfoByLicensePlate = orderInfoService.pendingOrder(deviceRecognitionParam.getLicensePlate());
                if (orderInfoByLicensePlate == null) {
                    // 播语音
                    return;
                }
                // 播语音
                // 开门
                orderInfoService.updateById(new OrderInfoEntity().setId(orderInfoByLicensePlate.getId()).setOrderStatus(OrderStatus.DaiJinChang));
            }
            break;
            case Jin: {
                OrderPagingResult orderInfoByLicensePlate = orderInfoService.pendingOrder(deviceRecognitionParam.getLicensePlate());
                if (orderInfoByLicensePlate == null) {
                    // 播语音
                    return;
                }
                // 播语音
                // 获取磅重
                // 播语音
                // 拍照
                Integer weight = null;
                String frontPhoto = null;
                String bodyPhoto = null;
                orderInfoService.truckComing(new TruckComingOrderParam()
                        .setOrderId(orderInfoByLicensePlate.getId())
                        .setWeight(weight)
                        .setFrontPhoto(frontPhoto)
                        .setBodyPhoto(bodyPhoto)
                );
            }
            break;
            // TODO 出前置不启用
            case ChuQianZhi: {
                OrderPagingResult orderInfoByLicensePlate = orderInfoService.pendingOrder(deviceRecognitionParam.getLicensePlate());
                if (orderInfoByLicensePlate == null) {
                    // 播语音
                    return;
                }
                CheckStatus checkStatus = orderInfoByLicensePlate.getCheckStatus();
                if (checkStatus == CheckStatus.WeiKanLiao) {
                    // 播语音
                    return;
                }
            }
            break;
            case Chu: {
                OrderPagingResult orderInfoByLicensePlate = orderInfoService.pendingOrder(deviceRecognitionParam.getLicensePlate());
                if (orderInfoByLicensePlate == null) {
                    // 播语音
                    return;
                }
                // 播语音
                // 获取磅重
                // 播语音
                // 拍照
                Integer weight = null;
                String frontPhoto = null;
                String bodyPhoto = null;
                orderInfoService.truckLeaving(new TruckLeavingOrderParam()
                        .setOrderId(orderInfoByLicensePlate.getId())
                        .setWeight(weight)
                        .setFrontPhoto(frontPhoto)
                        .setBodyPhoto(bodyPhoto)
                );
            }
            break;
            default:
                break;
        }


    }

    public Map<String, Object> report1(JSONObject data) {
        MapBuilder<String, Object> resBuilder = MapUtil.<String, Object>builder()
                .put("code", 0)
                .put("msg", "success");
        MapBuilder<String, Object> dataBuilder = MapUtil.<String, Object>builder()
                .put("order_no", "")
                .put("type", 0);
        String sn = data.getString("carDiscernCode");
        String licensePlate = data.getString("carNumber");
        DeviceInfoEntity deviceInfoEntity = this.getOne(Wrappers.<DeviceInfoEntity>lambdaQuery().eq(DeviceInfoEntity::getSn, sn));
        if (deviceInfoEntity == null) {
            log.error("设备不存在：{}", data);
            return resBuilder
                    .put("data", dataBuilder.put("type", 0).build())
                    .build();
        }
        OrderPagingResult orderPagingResult = orderInfoService.pendingOrder(licensePlate);
        if (orderPagingResult == null) {
            // 播语音
            playVoice(sn, "{}无订单", licensePlate);
            return resBuilder
                    .put("data", dataBuilder.put("type", 0).build())
                    .build();
        }
        DeviceCode deviceCode = deviceInfoEntity.getDeviceCode();
        OrderStatus orderStatus = orderPagingResult.getOrderStatus();
        if (deviceCode == DeviceCode.JinQianZhi && orderStatus == OrderStatus.QingYunZhong) {
            // 开门
            open(sn);
            return resBuilder
                    .put("data", dataBuilder.put("type", 0).build())
                    .build();
        }

        if (deviceCode == DeviceCode.Jin && orderStatus == OrderStatus.QingYunZhong) {
            return resBuilder
                    .put("data", dataBuilder.put("type", 1)
                            .put("order_no", orderPagingResult.getId() + "")
                            .build())
                    .build();
        }

        if (deviceCode == DeviceCode.ChuQianZhi && orderStatus == OrderStatus.YiJinChang) {
            // 开门
            open(sn);
            return resBuilder
                    .put("data", dataBuilder.put("type", 0).build())
                    .build();
        }

        if (deviceCode == DeviceCode.Chu && orderStatus == OrderStatus.YiJinChang) {
            return resBuilder
                    .put("data", dataBuilder.put("type", 2)
                            .put("order_no", orderPagingResult.getId() + "")
                            .build())
                    .build();
        }

        return resBuilder
                .put("data", dataBuilder.put("type", 0).build())
                .build();
    }

    public Map<String, Object> report2(JSONObject data) {
        MapBuilder<String, Object> resBuilder = MapUtil.<String, Object>builder()
                .put("code", 0)
                .put("msg", "success");
        MapBuilder<String, Object> dataBuilder = MapUtil.<String, Object>builder()
                .put("car_number", "")
                .put("order_no", "")
                .put("lane_code", "");
        String sn = data.getString("carDiscernCode");
        String licensePlate = data.getString("carNumber");
        Long orderId = data.getLong("orderNo");
        DeviceInfoEntity deviceInfoEntity = this.getOne(Wrappers.<DeviceInfoEntity>lambdaQuery().eq(DeviceInfoEntity::getSn, sn));
        if (deviceInfoEntity == null) {
            log.error("设备不存在：{}", data);
            return resBuilder
                    .put("data", dataBuilder.build())
                    .build();
        }

        DeviceCode deviceCode = deviceInfoEntity.getDeviceCode();
        OrderInfoEntity orderInfo = orderInfoService.getById(orderId);
        if (orderInfo == null) {
            // 播语音
            playVoice(sn, "{}无订单", orderId);
            return resBuilder
                    .put("data", dataBuilder.build())
                    .build();
        }
        Integer weight = data.getInteger("weight");
        String frontPhoto = data.getString("photoFront");
        String bodyPhoto = data.getString("photoBody");
        if (weight == null || weight <= 200) {
            // 播语音
            playVoice(sn, "{}磅重异常，请重新称重", licensePlate);
            return resBuilder
                    .put("data", dataBuilder.build())
                    .build();
        }
        if (deviceCode == DeviceCode.Jin) {
            // 播语音
            playVoice(sn, "{}称重完成，磅重{}吨", licensePlate, weight / 1000);
            // 开门
            open(sn);
            orderInfoService.truckComing(new TruckComingOrderParam()
                    .setOrderId(orderId)
                    .setWeight(weight)
                    .setFrontPhoto(frontPhoto)
                    .setBodyPhoto(bodyPhoto)
            );
        }

        if (deviceCode == DeviceCode.Chu) {
            // 播语音
            playVoice(sn, "{}称重完成，磅重{}吨", licensePlate, weight / 1000);
            // 开门
            open(sn);
            orderInfoService.truckLeaving(new TruckLeavingOrderParam()
                    .setOrderId(orderId)
                    .setWeight(weight)
                    .setFrontPhoto(frontPhoto)
                    .setBodyPhoto(bodyPhoto)
            );
        }

        return resBuilder
                .put("data", dataBuilder.build())
                .build();
    }

    private void open(String sn) {
        MqttUtil.publish("zsy/1/barrier", MapUtil.builder()
                .put("deviceNo", sn)
                .build());
    }

    private void playVoice(String sn, String content, Object... params) {
        MqttUtil.publish("zsy/1/voice", MapUtil.builder()
                .put("deviceNo", sn)
                .put("text", StrUtil.format(content, params))
                .build());
    }
}
