package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.MqttProviderConfig;
import com.hfkj.device.sanmisen.PrinterTemplate;
import com.hfkj.device.spyun.SpPrinterConfig;
import com.hfkj.device.spyun.SpPrinterTemplate;
import com.hfkj.entity.BsDevice;
import com.hfkj.entity.BsGasClassGroupTask;
import com.hfkj.model.GasClassGroupTaskDataCount;
import com.hfkj.model.ResponseData;
import com.hfkj.model.SecUserSessionObject;
import com.hfkj.service.BsDeviceService;
import com.hfkj.service.gas.BsGasClassGroupTaskService;
import com.hfkj.service.gas.BsGasStaffService;
import com.hfkj.sysenum.DeviceTypeEnum;
import com.hfkj.sysenum.SecUserObjectTypeEnum;
import com.hfkj.sysenum.gas.GasClassGroupTaskStatus;
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.HashMap;
import java.util.List;
import java.util.Map;

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

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

    @Resource
    private BsGasClassGroupTaskService gasClassGroupTaskService;
    @Resource
    private BsDeviceService deviceService;
    @Resource
    private BsGasStaffService gasStaffService;
    @Resource
    private UserCenter userCenter;
    @Resource
    private MqttProviderConfig mqttProviderConfig;

    @RequestMapping(value = "/startGroupTask", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "开启班组任务")
    public ResponseData startGroupTask(@RequestBody JSONObject body) {
        try {
            SecUserSessionObject userInfoModel = userCenter.getSessionModel(SecUserSessionObject.class);
            if (userInfoModel == null ||
                    (!userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type2.getCode())
                            && !userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type3.getCode()))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NOT_PERMISSIONS);
            }

            if (body == null || body.getLong("gasClassGroupId") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            Long gasId = null;
            if (userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type2.getCode())
                    || userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type3.getCode())) {
                gasId = userInfoModel.getMerchant().getId();
            }

            gasClassGroupTaskService.startGroupTask(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() {
        try {
            SecUserSessionObject userInfoModel = userCenter.getSessionModel(SecUserSessionObject.class);
            Long gasId = null;
            if (userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type2.getCode())
                    || userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type3.getCode())) {
                gasId = userInfoModel.getMerchant().getId();
            }

            gasClassGroupTaskService.endGroupTask(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("gasClassGroupId") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            SecUserSessionObject userInfoModel = userCenter.getSessionModel(SecUserSessionObject.class);
            Long gasId = null;
            if (userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type2.getCode())
                || userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type3.getCode())) {
                gasId = userInfoModel.getMerchant().getId();
            }

            gasClassGroupTaskService.swapGroupTask(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 = false) Long gasId) {
        try {
            SecUserSessionObject userInfoModel = userCenter.getSessionModel(SecUserSessionObject.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NOT_PERMISSIONS);
            }
            Map<String,Object> param = new HashMap<>();
            if (userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type2.getCode())
                || userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type3.getCode())) {
                gasId = userInfoModel.getMerchant().getId();
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NOT_PERMISSIONS, "");
            }
            GasClassGroupTaskDataCount dataCount;

            param.put("merId", gasId);
            param.put("status", GasClassGroupTaskStatus.status1.getStatus());
            List<BsGasClassGroupTask> list = gasClassGroupTaskService.getGroupTaskList(param);
            if (!list.isEmpty()) {
                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<>();

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

            if (userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type2.getCode())
                || userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type3.getCode())) {
                param.put("merId", userInfoModel.getMerchant().getId());
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NOT_PERMISSIONS, "");
            }
            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 {
            BsGasClassGroupTask groupTask = gasClassGroupTaskService.getDetailById(gasClassGroupTaskId);
            if (groupTask == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到班次");
            }
            GasClassGroupTaskDataCount dataCount = JSONObject.parseObject(groupTask.getDataCount(), GasClassGroupTaskDataCount.class);

            // 查询加油站打印机
            List<BsDevice> deviceList = deviceService.getDeviceByMer(groupTask.getMerId());
            for (BsDevice 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();
                } else if (device.getType().equals(DeviceTypeEnum.type2.getType())) {
                    new Thread(() -> {
                        try {
                            JSONObject param = new JSONObject();
                            param.put("id", System.currentTimeMillis());
                            param.put("type", 5);
                            param.put("vType", 0);
                            param.put("vMessage", "补打班结数据汇总，请注意查收");
                            param.put("contents", PrinterTemplate.classGroupCountTemp(dataCount ,true));

                            mqttProviderConfig.publish(1, false, device.getDeviceSn()+"/submsg", param.toJSONString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
            }

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

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


}
