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.device.spyun.SpPrinterConfig;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.model.SecUserSessionObject;
import com.hfkj.service.BsDeviceService;
import com.hfkj.service.merchant.BsMerchantService;
import com.hfkj.sysenum.DeviceReceiptOutContentEnum;
import com.hfkj.sysenum.DeviceTypeEnum;
import com.hfkj.sysenum.SecUserObjectTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
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.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/device")
@Api(value = "设备管理")
public class BsDeviceController {

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

    @Resource
    private UserCenter userCenter;
    @Resource
    private BsDeviceService deviceService;
    @Resource
    private BsMerchantService merchantService;
    @RequestMapping(value="/editDevice",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑设备")
    public ResponseData editDevice(@RequestBody BsDevice body) {
        try {

            if (StringUtils.isBlank(body.getMerNo()) || body.getType() == null) {
                log.error("BsDeviceController -> editDevice() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            if (DeviceTypeEnum.getNameByType(body.getType()) == null) {
                log.error("BsDeviceController -> editDevice() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的设备类型");
            }

            if ((body.getType().equals(DeviceTypeEnum.type1.getType()) || body.getType().equals(DeviceTypeEnum.type2.getType()))
                && (StringUtils.isBlank(body.getDeviceSn()) || StringUtils.isBlank(body.getDeviceKey()))) {
                log.error("BsDeviceController -> editDevice() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            BsDevice device;
            if (body.getId() != null) {
                // 查询设备
                device = deviceService.getDetailById(body.getId());
                if (device == null) {
                    log.error("HighDeviceController -> editDevice() error!","参数错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
            } else {
                device = new BsDevice();
            }

            // 查询商户
            BsMerchant merchant = merchantService.getMerchant(body.getMerNo());
            if (merchant == null) {
                log.error("HighDeviceController -> editDevice() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
            }


            if (body.getId() == null) {
                if (body.getType().equals(DeviceTypeEnum.type1.getType())) {
                    SpPrinterConfig sp = new SpPrinterConfig();
                    JSONObject jsonObject = JSONObject.parseObject(sp.addPrinter(body.getDeviceSn(), body.getDeviceKey(), merchant.getMerName()));
                    if (!jsonObject.getInteger("errorcode").equals(0)) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, jsonObject.getString("errormsg"));
                    }
                }
            }

            DeviceReceiptOutContentEnum receiptOutContent = null;
            Map<String,Object> param = new HashMap<>();
            param.put("type", DeviceTypeEnum.type1.getType());
            param.put("merNo", body.getMerNo());
            // 查询设备
            List<BsDevice> deviceList = deviceService.getDeviceList(param);
            if (!deviceList.isEmpty()) {
                // 查询设备的设置
                receiptOutContent = DeviceReceiptOutContentEnum.getDataByType(deviceList.get(0).getReceiptOutContent());
            }
            if (receiptOutContent == null) {
                receiptOutContent = DeviceReceiptOutContentEnum.content2;
            }

            device.setMerId(merchant.getId());
            device.setMerNo(merchant.getMerNo());
            device.setMerName(merchant.getMerName());
            device.setType(body.getType());
            device.setDeviceName(merchant.getMerName());
            device.setDeviceSn(body.getDeviceSn());
            device.setDeviceKey(body.getDeviceKey());
            device.setDeviceImei(body.getDeviceImei());
            device.setDeviceIccid(body.getDeviceIccid());
            device.setReceiptOutContent(receiptOutContent.getType());
            device.setReceiptTop(body.getReceiptTop());
            device.setReceiptSource(body.getReceiptSource());
            device.setReceiptBottom(body.getReceiptBottom());
            deviceService.editDevice(device);

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

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

    @RequestMapping(value="/delDevice",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除设备")
    public ResponseData delDevice(@RequestBody JSONObject body) {
        try {

            if (body.getLong("deviceId") == null) {
                log.error("BsDeviceController -> delDevice() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询设备
            BsDevice device = deviceService.getDetailById(body.getLong("deviceId"));
            if (device == null) {
                log.error("HighDeviceCBsDeviceControllerontroller -> delDevice() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            if (device.getType().equals(DeviceTypeEnum.type1.getType())) {
                SpPrinterConfig sp = new SpPrinterConfig();
                JSONObject jsonObject = JSONObject.parseObject(sp.deletePrinter(device.getDeviceSn()));
                if (!jsonObject.getInteger("errorcode").equals(0)) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, jsonObject.getString("errormsg"));
                }
            }

            device.setStatus(0);
            deviceService.editDevice(device);

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

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

    @RequestMapping(value="/getDetailById",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id查询设备详情")
    public ResponseData getDetailById(@RequestParam(name = "deviceId", required = true) Long deviceId) {
        try {

            return ResponseMsgUtil.success(deviceService.getDetailById(deviceId));

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

    @RequestMapping(value="/getDeviceList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询设备列表")
    public ResponseData getDeviceList(@RequestParam(name = "merNo", required = false) String merNo,
                                      @RequestParam(name = "merName", required = false) String merName,
                                      @RequestParam(name = "deviceName", required = false) String deviceName,
                                      @RequestParam(name = "deviceSn", required = false) String deviceSn,
                                      @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                      @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {

            SecUserSessionObject sessionModel = userCenter.getSessionModel(SecUserSessionObject.class);
            if (sessionModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
            }
            Map<String, Object> param = new HashMap<>();
            if (sessionModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type1.getCode())) {
                param.put("merNo", merNo);
            } else if (sessionModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type2.getCode())) {
                param.put("merNo", sessionModel.getMerchant().getMerNo());
            } else if (sessionModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type3.getCode())) {
                param.put("merNo", sessionModel.getMerchant().getMerNo());
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NOT_PERMISSIONS, "");
            }
            param.put("merName", merName);
            param.put("deviceSn", deviceSn);
            param.put("deviceName", deviceName);

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

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


    @RequestMapping(value="/getSettingReceipt",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询小票打印内容")
    public ResponseData getSettingReceipt(@RequestParam(name = "merNo", required = true) String merNo) {
        try {
            DeviceReceiptOutContentEnum receiptOutContent = null;
            Map<String,Object> param = new HashMap<>();
            param.put("type", DeviceTypeEnum.type1.getType());
            param.put("merNo", merNo);
            // 查询设备
            List<BsDevice> deviceList = deviceService.getDeviceList(param);
            if (!deviceList.isEmpty()) {
                // 查询设备的设置
                receiptOutContent = DeviceReceiptOutContentEnum.getDataByType(deviceList.get(0).getReceiptOutContent());
            }
            if (receiptOutContent == null) {
                receiptOutContent = DeviceReceiptOutContentEnum.content2;
            }
            return ResponseMsgUtil.success(receiptOutContent.getType());

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

    @RequestMapping(value="/settingReceipt",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "设置小票打印内容")
    public ResponseData settingReceipt(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || StringUtils.isBlank(body.getString("merNo"))
                    || body.getInteger("receiptOutContent") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            Map<String,Object> param = new HashMap<>();
            param.put("merNo", body.getString("merNo"));
            List<BsDevice> deviceList = deviceService.getDeviceList(param);
            for (BsDevice device : deviceList) {
                device.setReceiptOutContent(body.getInteger("receiptOutContent"));
                deviceService.editDevice(device);
            }
            return ResponseMsgUtil.success("操作成功");

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

}
