package com.hai.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.config.MqttProviderConfig;
import com.hai.config.SpPrinterConfig;
import com.hai.config.SpPrinterTemplate;
import com.hai.config.ZkcPrinterTemplate;
import com.hai.dao.HighGasClassGroupTaskMapper;
import com.hai.entity.*;
import com.hai.enum_type.DeviceTypeEnum;
import com.hai.enum_type.GasClassGroupTaskStatus;
import com.hai.model.GasClassGroupTaskDataCount;
import com.hai.model.GasClassGroupTaskOilCount;
import com.hai.service.HighDeviceService;
import com.hai.service.HighGasClassGroupService;
import com.hai.service.HighGasClassGroupTaskService;
import com.hai.service.HighMerchantStoreService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service("gasClassGroupTask")
public class HighGasClassGroupTaskServiceImpl implements HighGasClassGroupTaskService {

    @Resource
    private HighGasClassGroupTaskMapper gasClassGroupTaskMapper;

    @Resource
    private HighGasClassGroupService gasClassGroupService;

    @Resource
    private HighMerchantStoreService merchantStoreService;

    @Resource
    private HighDeviceService deviceService;

    @Resource
    private MqttProviderConfig mqttProviderConfig;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void startGroupTask(Long gasId, Long gasClassGroupId) {
        // 查询加油站
        HighMerchantStore merchantStore = merchantStoreService.getDetailById(gasId);
        if (merchantStore == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到加油站信息");
        }

        // 查询进行中的任务
        Map<String, Object> param = new HashMap<>();
        param.put("merchantStoreId", merchantStore.getId());
        param.put("status", GasClassGroupTaskStatus.status1.getStatus());
        List<HighGasClassGroupTask> list = getGroupTaskList(param);
        if (list.size() > 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "已有班组正在进行中，请结束班组或交换班组");
        }
        // 查询班组信息
        HighGasClassGroup group = gasClassGroupService.getDetailById(gasClassGroupId);
        if (group == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到班组信息");
        }

        HighGasClassGroupTask groupTask = new HighGasClassGroupTask();
        groupTask.setGasClassGroupId(group.getId());
        groupTask.setGasClassGroupName(group.getName());
        groupTask.setMerchantStoreId(merchantStore.getId());
        groupTask.setMerchantStoreName(merchantStore.getStoreName());
        groupTask.setStartTime(new Date());
        groupTask.setClassNum(gasClassGroupTaskMapper.getLatestClassNum(merchantStore.getId()) + 1);
        editGroupTask(groupTask);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void endGroupTask(Long gasId) {
        // 查询进行中的任务
        Map<String, Object> param = new HashMap<>();
        param.put("merchantStoreId", gasId);
        param.put("status", GasClassGroupTaskStatus.status1.getStatus());
        List<HighGasClassGroupTask> list = getGroupTaskList(param);
        if (list.size() > 0) {
            HighGasClassGroupTask groupTask = list.get(0);
            groupTask.setEndTime(new Date());
            groupTask.setStatus(GasClassGroupTaskStatus.status2.getStatus());
            // 统计
            GasClassGroupTaskDataCount dataCount = countGroupTaskData(gasId, groupTask.getClassNum(), groupTask.getId(), groupTask.getStatus(), groupTask.getStartTime(), groupTask.getEndTime());
            groupTask.setDataCount(JSONObject.toJSONString(dataCount));
            editGroupTask(groupTask);

            // 查询加油站打印机
            List<HighDevice> deviceList = deviceService.getDeviceListByStoreId(gasId);
            for (HighDevice device : deviceList) {
                if (device.getType().equals(DeviceTypeEnum.type1.getType())) {
                    new Thread(() -> {
                        try {
                            // 推送打印机
                            SpPrinterConfig spPrinterConfig = new SpPrinterConfig();
                            spPrinterConfig.print(device.getDeviceSn(), SpPrinterTemplate.classGroupCountTemp(dataCount, false), 1);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
                if (device.getType().equals(DeviceTypeEnum.type2.getType())) {
                   new Thread(() -> {
                        try {
                            // 推送打印机
                            mqttProviderConfig.publish(2,false, device.getDeviceImei(), ZkcPrinterTemplate.classGroupCountTemp(dataCount, false));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                  }).start();
                }
            }
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void swapGroupTask(Long gasId, Long gasClassGroupId) {
        // 任务结束
        endGroupTask(gasId);

        // 开启新的任务
        startGroupTask(gasId, gasClassGroupId);
    }

    @Override
    public GasClassGroupTaskDataCount countGroupTaskData(Long gasId, Integer classNum, Long groupTaskId, Integer status, Date startTime, Date endTime) {
        GasClassGroupTaskDataCount dataCount = new GasClassGroupTaskDataCount();
        dataCount.setClassNum(classNum);
        dataCount.setStatus(status);
        dataCount.setStartTime(startTime);
        dataCount.setEndTime(endTime);

        // 加油汇总
        Map<String, Object> refuelData = gasClassGroupTaskMapper.countRefuelData(groupTaskId);
        dataCount.setRefuelPrice(new BigDecimal(MapUtils.getString(refuelData, "refuelPrice")));
        dataCount.setRefuelNum(MapUtils.getInteger(refuelData, "refuelNum"));
        dataCount.setRefuelLiters(new BigDecimal(MapUtils.getString(refuelData, "refuelLiters")));

        // 退款汇总
        Map<String, Object> refundData = gasClassGroupTaskMapper.countRefundData(groupTaskId);
        dataCount.setRefundPrice(new BigDecimal(MapUtils.getString(refundData, "refundPrice")));
        dataCount.setRefundNum(MapUtils.getInteger(refundData, "refundNum"));
        dataCount.setRefundLiters(new BigDecimal(MapUtils.getString(refundData, "refundLiters")));


        // 油品汇总
        List<Map<String, Object>> oilDataList = gasClassGroupTaskMapper.countOilData(gasId, groupTaskId);

        List<GasClassGroupTaskOilCount> oilCountList = new ArrayList<>();
        for (Map<String, Object> oilData : oilDataList) {
            GasClassGroupTaskOilCount oilCount = new GasClassGroupTaskOilCount();
            oilCount.setOilNo(MapUtils.getInteger(oilData, "oilNo"));
            oilCount.setRefuelPrice(new BigDecimal(MapUtils.getString(oilData, "refuelPrice")));
            oilCount.setRefuelNum(MapUtils.getInteger(oilData, "refuelNum"));
            oilCount.setRefuelLiters(new BigDecimal(MapUtils.getString(oilData, "refuelLiters")));
            oilCountList.add(oilCount);
        }
        dataCount.setGroupTaskOilCountList(oilCountList);

        return dataCount;
    }

    @Override
    public void editGroupTask(HighGasClassGroupTask gasClassGroupTask) {
        if (gasClassGroupTask.getId() == null) {
            gasClassGroupTask.setStatus(GasClassGroupTaskStatus.status1.getStatus());
            gasClassGroupTask.setCreateTime(new Date());
            gasClassGroupTask.setUpdateTime(new Date());
            gasClassGroupTaskMapper.insert(gasClassGroupTask);
        } else {
            gasClassGroupTask.setUpdateTime(new Date());
            gasClassGroupTaskMapper.updateByPrimaryKey(gasClassGroupTask);
        }
    }

    @Override
    public HighGasClassGroupTask getDetailById(Long groupTaskId) {
        return gasClassGroupTaskMapper.selectByPrimaryKey(groupTaskId);
    }

    @Override
    public List<HighGasClassGroupTask> getGroupTaskList(Map<String, Object> param) {
        HighGasClassGroupTaskExample example = new HighGasClassGroupTaskExample();
        HighGasClassGroupTaskExample.Criteria criteria = example.createCriteria()
                .andStatusNotEqualTo(GasClassGroupTaskStatus.status0.getStatus());

        if (MapUtils.getLong(param, "gasClassGroupId") != null) {
            criteria.andGasClassGroupIdEqualTo(MapUtils.getLong(param, "gasClassGroupId"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "gasClassGroupName"))) {
            criteria.andGasClassGroupNameLike("%" + MapUtils.getString(param, "gasClassGroupName") + "%");
        }

        if (MapUtils.getLong(param, "merchantStoreId") != null) {
            criteria.andMerchantStoreIdEqualTo(MapUtils.getLong(param, "merchantStoreId"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "gasClassGroupName"))) {
            criteria.andGasClassGroupNameLike("%" + MapUtils.getString(param, "gasClassGroupName") + "%");
        }

        if (MapUtils.getInteger(param, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(param, "status"));
        }

        example.setOrderByClause("create_time desc");
        return gasClassGroupTaskMapper.selectByExample(example);
    }
}
