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.SpPrinterConfig;
import com.hai.entity.*;
import com.hai.enum_type.DeviceTypeEnum;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.BsCompanyService;
import com.hai.service.HighDeviceService;
import com.hai.service.HighMerchantService;
import com.hai.service.HighMerchantStoreService;
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.Map;

@Controller
@RequestMapping(value = "/device")
@Api(value = "卡卷接口")
public class HighDeviceController {

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

    @Resource
    private UserCenter userCenter;

    @Resource
    private HighDeviceService deviceService;

    @Resource
    private HighMerchantService merchantService;

    @Resource
    private HighMerchantStoreService merchantStoreService;

    @Resource
    private BsCompanyService companyService;

    @RequestMapping(value="/editDevice",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑设备")
    public ResponseData editDevice(@RequestBody HighDevice body) {
        try {

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

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

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

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

            HighDevice 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 HighDevice();
            }

            // 查询门店
            HighMerchantStore store = merchantStoreService.getDetailById(body.getMerStoreId());
            if (store == null) {
                log.error("HighDeviceController -> editDevice() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的门店");
            }

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

            // 查询分公司
            BsCompany company = companyService.getCompanyById(merchant.getCompanyId());
            if (company == 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(), store.getStoreName()));
                    if (!jsonObject.getInteger("errorcode").equals(0)) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, jsonObject.getString("errormsg"));
                    }
                }
            }

            device.setCompanyId(company.getId());
            device.setCompanyName(company.getName());
            device.setMerId(merchant.getId());
            device.setMerName(merchant.getMerchantName());
            device.setMerStoreId(store.getId());
            device.setMerStoreName(store.getStoreName());
            device.setType(body.getType());
            device.setDeviceName(store.getStoreName());
            device.setDeviceSn(body.getDeviceSn());
            device.setDeviceKey(body.getDeviceKey());
            device.setDeviceImei(body.getDeviceImei());
            device.setDeviceIccid(body.getDeviceIccid());
            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("HighDeviceController -> delDevice() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询设备
            HighDevice device = deviceService.getDetailById(body.getLong("deviceId"));
            if (device == null) {
                log.error("HighDeviceController -> 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("HighDeviceController -> 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 = "根据id查询设备详情")
    public ResponseData getDeviceList(@RequestParam(name = "companyId", required = false) Long companyId,
                                      @RequestParam(name = "merId", required = false) Long merId,
                                      @RequestParam(name = "storeId", required = false) Long storeId,
                                      @RequestParam(name = "deviceName", required = false) String deviceName,
                                      @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                      @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {

            UserInfoModel sessionModel = userCenter.getSessionModel(UserInfoModel.class);
            if (sessionModel == null) {
                log.error("HighDeviceController -> getDeviceList() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到");
            }

            Map<String, Object> param = new HashMap<>();
            param.put("deviceName", deviceName);

            if (sessionModel.getSecUser().getObjectType().equals(0)) {
                param.put("companyId", companyId);
                param.put("merId", merId);
                param.put("storeId", storeId);

            } else if (sessionModel.getSecUser().getObjectType().equals(1)) {
                param.put("companyId", sessionModel.getBsCompany().getId());
                param.put("merId", merId);
                param.put("storeId", storeId);

            } else if (sessionModel.getSecUser().getObjectType().equals(2)) {
                param.put("merId", sessionModel.getMerchant().getId());
                param.put("storeId", storeId);

            } else if (sessionModel.getSecUser().getObjectType().equals(3)) {
                param.put("storeId", sessionModel.getMerchantStore().getId());

            } else {
                log.error("HighDeviceController -> getDeviceList() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            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);
        }
    }

}
