package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.MqttProviderConfig;
import com.hai.config.SpPrinterConfig;
import com.hai.config.SpPrinterTemplate;
import com.hai.config.ZkcPrinterTemplate;
import com.hai.entity.HighDevice;
import com.hai.entity.HighGasClassGroupTask;
import com.hai.enum_type.DeviceTypeEnum;
import com.hai.enum_type.GasClassGroupTaskStatus;
import com.hai.enum_type.UserObjectTypeEnum;
import com.hai.model.GasClassGroupTaskDataCount;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.HighDeviceService;
import com.hai.service.HighGasClassGroupTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 加油站班组任务
 * @author hurui
 */
@Controller
@RequestMapping(value = "/gasClassGroupTask")
@Api(value = "加油站班组任务")
public class HighGasClassGroupTaskController {

    private static Logger log = LoggerFactory.getLogger(HighGasClassGroupTaskController.class);

    @Resource
    private HighGasClassGroupTaskService gasClassGroupTaskService;

    @Resource
    private HighDeviceService deviceService;

    @Resource
    private MqttProviderConfig mqttProviderConfig;

    @Resource
    private UserCenter userCenter;

    @RequestMapping(value = "/startGroupTask", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "开启班组任务")
    public ResponseData startGroupTask(@RequestBody JSONObject body) {
        try {
            if (body == null || body.getLong("gasId") == null || body.getLong("gasClassGroupId") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            gasClassGroupTaskService.startGroupTask(body.getLong("gasId"), body.getLong("gasClassGroupId"));

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("HighGasClassGroupTaskController --> startGroupTask() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/endGroupTask", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "结束班组任务")
    public ResponseData endGroupTask(@RequestBody JSONObject body) {
        try {
            if (body == null || body.getLong("gasId") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            gasClassGroupTaskService.endGroupTask(body.getLong("gasId"));

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("HighGasClassGroupTaskController --> endGroupTask() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/swapGroupTask", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "交换班组任务")
    public ResponseData swapGroupTask(@RequestBody JSONObject body) {
        try {
            if (body == null || body.getLong("gasId") == null || body.getLong("gasClassGroupId") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            gasClassGroupTaskService.swapGroupTask(body.getLong("gasId"), body.getLong("gasClassGroupId"));

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("HighGasClassGroupTaskController --> swapGroupTask() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getCurrentClassGroupTask", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询当前班次")
    public ResponseData getCurrentClassGroupTask(@RequestParam(name = "gasId", required = true) Long gasId) {
        try {
            GasClassGroupTaskDataCount dataCount;

            Map<String,Object> param = new HashMap<>();
            param.put("merchantStoreId", gasId);
            param.put("status", GasClassGroupTaskStatus.status1.getStatus());
            List<HighGasClassGroupTask> list = gasClassGroupTaskService.getGroupTaskList(param);
            if (list.size() > 0) {
                dataCount = gasClassGroupTaskService.countGroupTaskData(gasId,
                        list.get(0).getClassNum(),
                        list.get(0).getId(),
                        list.get(0).getStatus(),
                        list.get(0).getStartTime(),
                        null
                );
                return ResponseMsgUtil.success(dataCount);
            }
            dataCount = new GasClassGroupTaskDataCount();
            dataCount.setStatus(0);

            dataCount.setRefuelPrice(new BigDecimal("0"));
            dataCount.setRefuelNum(0);
            dataCount.setRefuelLiters(new BigDecimal("0"));

            dataCount.setRefundPrice(new BigDecimal("0"));
            dataCount.setRefundNum(0);
            dataCount.setRefundLiters(new BigDecimal("0"));
            return ResponseMsgUtil.success(dataCount);

        } catch (Exception e) {
            log.error("HighGasClassGroupTaskController --> getCurrentClassGroupTask() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getClassGroupTaskById", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询班组任务记录")
    public ResponseData getClassGroupTaskById(@RequestParam(name = "gasClassGroupTaskId", required = true) Long gasClassGroupTaskId) {
        try {

            return ResponseMsgUtil.success(gasClassGroupTaskService.getDetailById(gasClassGroupTaskId));

        } catch (Exception e) {
            log.error("HighGasClassGroupTaskController --> getClassGroupTaskById() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getClassGroupTaskList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询班组任务记录")
    public ResponseData getClassGroupTaskList(@RequestParam(name = "gasClassGroupId", required = false) Long gasClassGroupId,
                                              @RequestParam(name = "merchantStoreId", required = false) Long merchantStoreId,
                                              @RequestParam(name = "status", required = false) Integer status,
                                              @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                              @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String,Object> param = new HashMap<>();

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type3.getType())) {
                param.put("merchantStoreId", userInfoModel.getMerchantStore().getId());
            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type8.getType())) {
                param.put("merchantStoreId", userInfoModel.getMerchantStore().getId());
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            param.put("gasClassGroupId", gasClassGroupId);
            param.put("status", status);

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(gasClassGroupTaskService.getGroupTaskList(param)));

        } catch (Exception e) {
            log.error("HighGasClassGroupTaskController --> getClassGroupTaskList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/print", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "打印小票")
    public ResponseData print(@RequestParam(name = "gasClassGroupTaskId", required = true) Long gasClassGroupTaskId) {
        try {
            HighGasClassGroupTask groupTask = gasClassGroupTaskService.getDetailById(gasClassGroupTaskId);
            if (groupTask == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到班次");
            }
            GasClassGroupTaskDataCount dataCount = JSONObject.parseObject(groupTask.getDataCount(), GasClassGroupTaskDataCount.class);

            // 查询加油站打印机
            List<HighDevice> deviceList = deviceService.getDeviceListByStoreId(groupTask.getMerchantStoreId());
            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, true), 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,true));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
            }

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("HighGasClassGroupTaskController --> getClassGroupTaskById() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


}
