package com.jeequan.jeepay.thirdparty.device.printer.zwPrinter;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.device.IPrinterService;
import com.jeequan.jeepay.core.model.device.PayOrderInfo4Device;
import com.jeequan.jeepay.core.model.device.ZwParams;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.service.impl.SysConfigService;
import com.jeequan.jeepay.thirdparty.service.zw.model.request.PrintContextRequest;
import com.jeequan.jeepay.thirdparty.service.zw.model.request.PrintRequest;
import com.jeequan.jeepay.thirdparty.service.zw.model.request.UpdatePayParamRequest;
import com.jeequan.jeepay.thirdparty.service.zw.model.response.BaseResponse;
import com.jeequan.jeepay.thirdparty.service.zw.uils.SmartLinkUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 云打印厂商： 智网
 *
 * @author xiaoyu
 * @date 2023/4/11 16:36
 */
@Slf4j
@Service
public class ZwPrinterService implements IPrinterService {

    @Autowired private SysConfigService sysConfigService;

    @Override
    public void send(JSONObject deviceParams, PayOrderInfo4Device payOrderInfo) throws BizException {
        ZwParams zwParams = getZwParams(deviceParams);
        PrintRequest request = new PrintRequest();
        request.setIndex(IdUtil.fastSimpleUUID());
        request.setSn(zwParams.getDeviceParams().getDeviceNo());
        request.setToken(zwParams.getProviderParams().getToken());

        // 打印联数
        int printNum = zwParams.getBizConfigParams().getPrintNum() != null ? zwParams.getBizConfigParams().getPrintNum() : 1;

        PrintContextRequest contextRequest = new PrintContextRequest();
        // 音箱播报内容
        if (PayOrderInfo4Device.BOARD_TYPE_MEMBER.equals(payOrderInfo.getWayCodeType())) {
            contextRequest.setSc("会员余额支付" + AmountUtil.convertCent2Dollar(payOrderInfo.getAmount()) + "元");
        }else if (StringUtils.isNotBlank(zwParams.getProviderParams().getCustomContent())){
            contextRequest.setSc(zwParams.getProviderParams().getCustomContent() + AmountUtil.convertCent2Dollar(payOrderInfo.getAmount())+ "元");
        }

        // 打印内容
        contextRequest.setPd(SmartLinkUtil.getPrintPd(payOrderInfo));
        // 打印联数
        contextRequest.setCn(printNum + "");
        request.setContext(contextRequest);

        BaseResponse response = SmartLinkUtil.cloudPrint(request);
        if (!response.isSuccess()) {
            throw new BizException(response.getErrmsg());
        }
    }

    @Override
    public void sendCustomMsg(JSONObject deviceParams, PayOrderInfo4Device payOrderInfo) throws BizException {

        ZwParams zwParams = getZwParams(deviceParams);

        PrintRequest request = new PrintRequest();
        request.setIndex(IdUtil.fastSimpleUUID());
        request.setSn(zwParams.getDeviceParams().getDeviceNo());
        request.setToken(zwParams.getProviderParams().getToken());

        PrintContextRequest contextRequest = new PrintContextRequest();
        // 音箱播报内容
        contextRequest.setCn(zwParams.getProviderParams().getCustomContent() + AmountUtil.convertCent2Dollar(payOrderInfo.getAmount())+ "元");
        // 打印内容
        contextRequest.setPd(SmartLinkUtil.getPrintPd(payOrderInfo));
        request.setContext(contextRequest);

        BaseResponse response = SmartLinkUtil.cloudPrint(request);
        if (!response.isSuccess()) {
            throw new BizException(response.getErrmsg());
        }
    }

    @Override
    public String addPrinter(JSONObject deviceParams) {

        ZwParams zwParams = getZwParams(deviceParams);

        ZwParams.DeviceParams printConfig = zwParams.getDeviceParams();
        // 参数校验
        checkConfigInfo(printConfig);

        UpdatePayParamRequest request = new UpdatePayParamRequest();
        request.setIndex(IdUtil.fastSimpleUUID());
        request.setSn(zwParams.getDeviceParams().getDeviceNo());
        request.setToken(zwParams.getProviderParams().getToken());
        request.setShopid("1");
        request.setTermid("zw");

        request.setBill_cap(printConfig.getBillCap());
        request.setBill_print(printConfig.getBillPrint());
        request.setUrl(sysConfigService.getDBApplicationConfig().getPaySiteUrl() + "/api/zw/pay");
        request.setUrl_query(sysConfigService.getDBApplicationConfig().getPaySiteUrl() + "/api/zw/query");
        request.setBill_timeout(printConfig.getBillTimeout());
        request.setQuery_interval(printConfig.getQueryInterval());
        request.setQuery_num(printConfig.getQueryNum());
        request.setMd5key(zwParams.getProviderParams().getMd5Key());

        if ("-1".equals(printConfig.getProviderCode())) {
            request.setKeyword_cap(printConfig.getKeywordCap());
            request.setKeyword_skip(printConfig.getKeywordSkip());
            request.setOrder_prefix(printConfig.getOrderPrefix());
            request.setOrder_skip(printConfig.getOrderSkip());
        }else  {
            request.setPreset_prefix(printConfig.getPresetPrefix());
            request.setPreset_data(printConfig.getPresetData());
            request.setPreset_timestamp(printConfig.getTimestamp());
        }
        request.setAuthcode(printConfig.getAuthCode());
        request.setErrinfo_print(printConfig.getErrInfoPrint());
        request.setRefundcode_print(printConfig.getRefundCodePrint());

        // 支付方式 1-被扫 2-主扫 （默认为被扫）
        request.setPay_mode(1);

//        request.setKeyword_cap("实收,应收,总价,总计,合计,订单总额");
//        request.setKeyword_skip("店名,销售商品报表");

        BaseResponse response = SmartLinkUtil.updatePayParam(request);
        if (!response.isSuccess()) {
            log.error(response.getErrmsg());
            throw new BizException(response.getErrmsg());
        }
        return "success";
    }

    @Override
    public String editPrinter(JSONObject deviceParams) {
        return null;
    }

    @Override
    public String clearPrinter(JSONObject deviceParams) {
        return null;
    }


    private ZwParams getZwParams(JSONObject deviceParams) {
        JSONObject zwJSON = new JSONObject();
        zwJSON.put("providerParams", JSON.parseObject(deviceParams.getString("providerParams")));
        zwJSON.put("deviceParams", JSON.parseObject(deviceParams.getString("deviceParams")));
        zwJSON.put("bizConfigParams", JSON.parseObject(deviceParams.getString("bizConfigParams")));
        return JSON.parseObject(zwJSON.toJSONString(), ZwParams.class);
    }

    /** 设备参数校验 **/
    public void checkConfigInfo(ZwParams.DeviceParams printConfig) {
        if (printConfig == null) {
            throw new BizException("打印机参数配置不能为空");
        }

        if (StringUtils.isEmpty(printConfig.getAuthCode())) {
            throw new BizException("16字节唯一验证码不能为空");
        }

        if (StringUtils.isEmpty(printConfig.getProviderCode())) {
            throw new BizException("厂商编码不能为空");
        }

        if ("-1".equals(printConfig.getProviderCode())) {

            if (StringUtils.isEmpty(printConfig.getKeywordCap())) {
                throw new BizException("获取收银小票支付金额关键字不能为空");
            }
            if (StringUtils.isEmpty(printConfig.getKeywordSkip())) {
                throw new BizException("小票放行关键字不能为空");
            }
            if (printConfig.getOrderSkip() == null) {
                throw new BizException("是否跳过重复的订单编号配置不能为空");
            }
        }else {
            if (StringUtils.isEmpty(printConfig.getPresetPrefix())) {
                throw new BizException("收银小票金额拦截关键字不能为空");
            }
            if (StringUtils.isEmpty(printConfig.getSoftCode())) {
                throw new BizException("软件编号不能为空");
            }
            if (StringUtils.isEmpty(printConfig.getSoftName())) {
                throw new BizException("软件名称不能为空");
            }
            if (StringUtils.isEmpty(printConfig.getTimestamp())) {
                throw new BizException("时间戳不能为空");
            }
            if (StringUtils.isEmpty(printConfig.getPresetData())) {
                throw new BizException("支付预配置参数不能为空");
            }

        }

    }

}
