package com.jeequan.jeepay.db.entity;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;
import com.jeequan.jeepay.core.exception.BizException;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商户门店设备配置表
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2021-12-28
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName(value = "t_mch_store_device",autoResultMap = true)
public class MchStoreDevice extends com.jeequan.jeepay.core.entity.MchStoreDevice {
    //gw
    public static final LambdaQueryWrapper<MchStoreDevice> gw(){
        return new LambdaQueryWrapper<>();
    }

    private static final long serialVersionUID=1L;

    public static final byte DEVICE_TYPE_SPEAKER = 1; // 云喇叭
    public static final byte DEVICE_TYPE_PRINTER = 2; // 打印机
    public static final byte DEVICE_TYPE_POS = 3; // 扫码POS
    public static final byte DEVICE_TYPE_AUTO_POS = 4; // 智能POS
    public static final byte DEVICE_TYPE_PLUGIN = 5; // 收银插件
    public static final byte DEVICE_TYPE_FACE_APP = 6; // 刷脸设备
    public static final byte DEVICE_TYPE_RUYI = 7; // 如意Lite

    // 绑定类型
    public static final byte DEVICE_BIND_TYPE_STORE = 0; // 门店
    public static final byte DEVICE_BIND_TYPE_QRC = 1; // 码牌

    public static final byte NO_BIND = 0;

    public static final byte YES_BIND = 1;

    // 设备表类型 和 订单表类型转换关系
    public static Object covertDeviceType(Object deviceType) {
        if (deviceType instanceof Byte) {
            switch ((Byte) deviceType) {
                case DEVICE_TYPE_POS: return PayOrder.DEVICE_TYPE_SCAN_POS;
                case DEVICE_TYPE_AUTO_POS: return PayOrder.DEVICE_TYPE_AUTO_POS;
                case DEVICE_TYPE_PLUGIN: return PayOrder.DEVICE_TYPE_CASH_PLUGIN;
                case DEVICE_TYPE_FACE_APP: return PayOrder.DEVICE_TYPE_FACE_APP;
                case DEVICE_TYPE_RUYI: return PayOrder.DEVICE_TYPE_ALIPAY_RUYI_LITE;
                case DEVICE_TYPE_PRINTER: return PayOrder.DEVICE_TYPE_PRINTER;
            }
        }else {
            switch ((String) deviceType) {
                case PayOrder.DEVICE_TYPE_SCAN_POS: return DEVICE_TYPE_POS;
                case PayOrder.DEVICE_TYPE_AUTO_POS: return DEVICE_TYPE_AUTO_POS;
                case PayOrder.DEVICE_TYPE_CASH_PLUGIN: return DEVICE_TYPE_PLUGIN;
                case PayOrder.DEVICE_TYPE_FACE_APP: return DEVICE_TYPE_FACE_APP;
                case PayOrder.DEVICE_TYPE_ALIPAY_RUYI_LITE: return DEVICE_TYPE_RUYI;
                case PayOrder.DEVICE_TYPE_PRINTER: return DEVICE_TYPE_PRINTER;
            }
        }
        return null;
    }

    // 支付宝如意设备型号
    public static final Map<String, String> ALIPAY_IOT_DEVICE_MAP = new HashMap<>();
    static {
        ALIPAY_IOT_DEVICE_MAP.put("alipayRuYi", "201901111100635561");
        ALIPAY_IOT_DEVICE_MAP.put("alipayRuYiPro", "202109071403204809");
        ALIPAY_IOT_DEVICE_MAP.put("alipayRuYi2", "202008061702346558");
    }

    /**
     * 设备ID
     */
    @TableId(value = "device_id", type = IdType.AUTO)
    private Long deviceId;

    /**
     * 设备名称
     */
    private String deviceName;

    /**
     * 批次号
     */
    private String batchId;

    /**
     * 关联厂商配置ID
     */
    private Long configId;

    /**
     * 设备类型： 1-云喇叭, 2-云打印
     */
    private Byte deviceType;

    /**
     * 设备厂商：参考配置表
     */
    private String provider;

    /**
     * 设备号
     */
    private String deviceNo;

    /**
     * 设备参数，json字符串
     */
    private String deviceParams;

    /**
     * 业务配置参数，json字符串
     */
    private String bizConfigParams;

    /**
     * 业务配置参数，json对象
     */
    @TableField(exist = false)
    private JSONObject jsonBizConfigParams;


    /**
     * 打印机模式  1：仅打印  2仅播报 3打印并播报
     */
    @TableField(exist = false)
    private Integer printMode;

    /**
     * 绑定码牌ID（批量添加云喇叭设备时绑定的码牌ID，与云喇叭设备一对一关系）
     */
    private Long bindQrcId;

    /**
     * 门店ID
     */
    private String storeId;

    /**
     * 商户号
     */
    private String mchNo;

    /**
     * 应用appId
     */
    private String appId;

    /**
     * 服务商号
     */
    private String agentNo;

    /**
     * 状态： 0-停用，1-启用
     */
    private Byte state;

    /**
     * 商户绑定状态： 0-未绑定，1-已绑定
     */
    private Byte bindState;

    /**
     * 绑定类型： 0-门店，1-码牌
     */
    private Byte bindType;

    /**
     * 绑定时间
     */
    private Date bindTime;

    /**
     * 解绑时间
     */
    private Date unbindTime;

    /**
     * 蚂蚁店铺Iot设备绑定状态： 0-未绑定，1-已绑定
     */
    private Byte alipayBindState;

    /**
     * 蚂蚁店铺ID
     */
    private String alipayShopId;

    /**
     * 是否固定支付金额: 1-是, 0-否
     */
    private Byte fixedFlag;

    /**
     * 固定支付金额,单位分
     */
    private Long fixedPayAmount;

    /**
     * 商户名称
     */
    private String MchApplyName;

    /**
     * 扩展商户号 现在的申请单编号 也是商户号
     */
    private String MchApplyId;

    /**
     * 创建时间
     */
    private Date createdAt;

    /**
     * 更新时间
     */
    private Date updatedAt;


    @TableField(typeHandler = FastjsonTypeHandler.class)
    private JSONObject marqueeInfo;

    /**
     * 轮播图
     */
    @TableField(typeHandler = FastjsonTypeHandler.class)
    private List<JSONObject> carouselPicInfo;

    /**
     * 付款区域背景图
     */
    @TableField(typeHandler = FastjsonTypeHandler.class)
    private JSONObject payPicInfo;

    /**
     * 绑定的应用名称
     */
    @TableField(exist = false)
    private String appName;

    /**
     * 绑定的门店名称
     */
    @TableField(exist = false)
    private String storeName;

    @TableField(exist = false)
    private List<Long> qrcIdList;

    /**
     * 马牌名称
     */
    @TableField(exist = false)
    private String bindQrcName;

    /**
     * 用户名称
     */
    @TableField(exist = false)
    private String mchUserName;

    /**
     * 用户电话
     */
    @TableField(exist = false)
    private String mchUserPhone;

    @TableField(exist = false)
    private String isvName;

    /**
     * 渠道简称
     */
    @TableField(exist = false)
    private String isvShortName;

    @TableField(exist = false)
    private String isvNo;

    @TableField(exist = false)
    private String mchServiceName;

    @TableField(exist = false)
    private String mchServicePhone;
    @TableField(exist = false)
    private Date firstDate;

    @TableField(exist = false)
    private Date lastDate;

    @TableField(exist = false)
    List<String> subAgentNoList;

    @TableField(exist = false)
    private String ifName;

    @TableField(exist = false)
    private String ifCode;

    @TableField(exist = false)
    List<String> storeIdList;

    @TableField(exist = false)
    private String appSearchData;


    public void preCheckMarket() {
        if(StringUtils.isEmpty(this.getDeviceNo())){
            throw new BizException("设备号不能为空");
        }
    }

    /**
     * 校验设备跑马灯参数
     */
    public void preCheckMarqueeInfo() {
        preCheckMarket();
        JSONObject marqueeInfo = this.getMarqueeInfo() == null ? this.getExt() : this.getMarqueeInfo();
        if(marqueeInfo == null){
            throw new BizException("跑马灯广告信息为空");
        }
        String inputText = marqueeInfo.getString("inputText");
        if(StringUtils.isEmpty(inputText)){
            throw new BizException("跑马灯文字内容不能为空");
        }
        String fontColor = marqueeInfo.getString("fontColor");
        if(StringUtils.isEmpty(fontColor)){
            throw new BizException("跑马灯内字体颜色不能为空");
        }
        String bgColor = marqueeInfo.getString("bgColor");
        if(StringUtils.isEmpty(bgColor)){
            throw new BizException("跑马灯背景颜色不能为空");
        }
        //文字大小写死
        marqueeInfo.put("fontSize",20);
        //跑马灯显示的X轴位置 写死
        marqueeInfo.put("displayAreX",0);
        //跑马灯显示的Y轴位置 写死
        marqueeInfo.put("displayAreY",300);
        //尺寸（分辨率）宽 写死
        marqueeInfo.put("picWidth",840);
        //尺寸（分辨率）高 写死
        marqueeInfo.put("picHeight",40);
        this.setMarqueeInfo(marqueeInfo);
    }

    public void preCheckMarketPic() {
        preCheckMarket();
        List<JSONObject> carouselPicInfo = this.getCarouselPicInfo();
        if(carouselPicInfo == null || carouselPicInfo.isEmpty()){
            throw new BizException("营销区轮播图片不能为空");
        }
        if(carouselPicInfo.size() > 5){
            throw new BizException("最多只能设置5张图片");
        }
        for (JSONObject item:carouselPicInfo) {
            Integer displayTime = item.getInteger("displayTime") == null ? 3 : item.getInteger("displayTime");
            item.put("displayTime",displayTime);
            item.put("enable",1);
            String url = item.getString("picName");
            byte[] bytes = HttpUtil.downloadBytes(url);
            BufferedImage bufferedImage = ImgUtil.toImage(bytes);
            // 获取图片的位深度
            int bitDepth = bufferedImage.getColorModel().getPixelSize();
            //只支持图片位深度为24的图片
            if(bitDepth != 24){
                throw new BizException("当前图片格式不支持");
            }
            if(bufferedImage.getWidth() != 800){

            }
            item.put("picWidth",bufferedImage.getWidth());
            item.put("picHeight",bufferedImage.getHeight());
            item.put("picBitDepth",bitDepth);
            item.put("picSize",bytes.length);
        }
    }

    public void preCheckPayCode() {
        preCheckMarket();
        JSONObject payPicInfo = this.getPayPicInfo();
        if(payPicInfo == null){
            throw new BizException("付款区域的图片信息不能为空");
        }
        String picUrl = payPicInfo.getString("picName");
        if(StringUtils.isEmpty(picUrl)){
            throw new BizException("付款区域的图片地址参数不能为空");
        }
        payPicInfo.put("displayTime",-1);
        payPicInfo.put("enable",1);
        payPicInfo.put("showQrCode",1);
        byte[] bytes = HttpUtil.downloadBytes(picUrl);
        BufferedImage bufferedImage = ImgUtil.toImage(bytes);
        // 获取图片的位深度
        int bitDepth = bufferedImage.getColorModel().getPixelSize();
        //只支持图片位深度为24的图片
        if(bitDepth != 24){
            throw new BizException("当前图片格式不支持");
        }
        payPicInfo.put("picWidth",bufferedImage.getWidth());
        payPicInfo.put("picHeight",bufferedImage.getHeight());
        payPicInfo.put("picBitDepth",bitDepth);
        payPicInfo.put("picSize",bytes.length);
    }
}
