package com.cweb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.alipay.utils.AlipayRequest;
import com.hfkj.channel.lakala.LaKaLaLedgerService;
import com.hfkj.channel.lakala.LaKaLaTradeService;
import com.hfkj.channel.lakala.LaKaLaWalletService;
import com.hfkj.channel.lakala.config.LaKaLaConfig;
import com.hfkj.channel.saas.SaasActivityService;
import com.hfkj.channel.saas.SaasMerService;
import com.hfkj.channel.saas.utils.SaasCommon;
import com.hfkj.channel.saas.utils.SaasMerRequest;
import com.hfkj.channel.tianque.service.TianQueMerElecSignService;
import com.hfkj.channel.tianque.service.TianQueMerService;
import com.hfkj.channel.tianque.service.TianQueTradeService;
import com.hfkj.channel.weixin.WeiXinMerService;
import com.hfkj.channel.weixin.utils.WxUtils;
import com.hfkj.channel.weixin.utils.sdk.WXPayConstants;
import com.hfkj.common.Base64Util;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.common.utils.UnionUtils;
import com.hfkj.config.CommonSysConst;
import com.hfkj.config.device.SoundService;
import com.hfkj.config.mqtt.MqttProviderService;
import com.hfkj.entity.*;
import com.hfkj.model.MerBasisModel;
import com.hfkj.model.ResponseData;
import com.hfkj.service.*;
import com.hfkj.sysenum.MerStatusEnum;
import com.hfkj.sysenum.PlatformTypeEnum;
import com.hfkj.sysenum.StoreCreateTypeEnum;
import com.hfkj.sysenum.StoreStatusEnum;
import com.hfkj.tts.HWYunSisService;
import com.hfkj.unipush.UniPushService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping(value = "/test")
@Api(value = "测试")
public class TestController {

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

    @Resource
    private WeiXinMerService weiXinMerService;

    @Resource
    private MqttProviderService mqttProviderService;

    @Resource
    private SoundService soundService;

    @Resource
    private SaasCommon saasCommon;

    @Resource
    private SaasMerRequest saasMerRequest;

    @Resource
    private SaasMerService saasMerService;
    @Resource
    private BsTradeOrderService tradeOrderService;
    @Resource
    private BsMerService merService;

    @Resource
    private SaasActivityService saasActivityService;

    @Resource
    private BsMerPlatformNoService merPlatformNoService;
    @Resource
    private BsMerContractRecordMsgService merContractRecordMsgService;
    @Resource
    private BsMerContractRecordService merContractRecordService;
    @Resource
    private BsMerPlatformTermService merPlatformTermService;
    @Resource
    private BsStoreService storeService;
    @Resource
    private BsBankActivityRosterRateService bankActivityRosterRateService;

    @Resource
    private LaKaLaLedgerService laKaLaLedgerService;

    @Resource
    private BsMerContractService merContractService;

    @Resource
    private LaKaLaWalletService laKaLaWalletService;

    @Resource
    private LaKaLaTradeService laKaLaTradeService;

    @Resource
    private BsStoreCidService bsStoreCidService;

    @RequestMapping(value="/refreshMerStatus",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "refreshMerStatus")
    public ResponseData refreshMerStatus(@RequestParam(value = "orderNo", required = true) String orderNo) {
        try {

            BsMerContractRecord contractRecord = merContractRecordService.getRecordByOrderNo(orderNo);

            BsMer mer = merService.getMer(contractRecord.getMerId());
            if (mer != null && mer.getMerStatus().equals(MerStatusEnum.status3.getNumber())) {
                BsMerPlatformNo platform = merPlatformNoService.getPlatformNo(mer.getId(), PlatformTypeEnum.type1);
                if (platform != null) {
                    JSONObject merchantInfo = saasMerService.merchantInfo(platform.getPlatformNo());
                    // 查询申请记录
                    BsMerContractRecordMsg msg = new BsMerContractRecordMsg();
                    msg.setOrderNo(contractRecord.getOrderNo());
                    msg.setType(1);
                    msg.setResponseContent(merchantInfo.toJSONString());
                    merContractRecordMsgService.insertRecordMsg(msg);

                    JSONObject customer = merchantInfo.getJSONObject("customer");
                    // 商户状态 OPEN:开通，CLOSE:关闭，LOSS:流失, REJECT：拒绝。可用值:OPEN,ACTIVITY,WAIT_COMMIT,WAIT_AUDI,REJECT, CLOSE,INIT
                    if (customer.getString("customerStatus").equals("OPEN")) {
                        contractRecord.setStatus(2);
                        merContractRecordService.updateRecord(contractRecord);

                        mer.setMerStatus(MerStatusEnum.status1.getNumber());
                        merService.editMer(mer);

                        List<BsStore> storeList = storeService.getStoreByMerId(mer.getId(), StoreCreateTypeEnum.type1);
                        if (storeList.size() > 0) {
                            BsStore store = storeList.get(0);
                            store.setStatus(StoreStatusEnum.status2.getNumber());
                            storeService.editStore(store);
                        }
                        platform.setCupNo(customer.getString("externalCustomerNo"));
                        merPlatformNoService.editMerPlatformNo(platform);

                        // 终端信息
                        BsMerPlatformTerm term = new BsMerPlatformTerm();
                        term.setMerPlatformNoId(platform.getId());
                        term.setMerId(platform.getMerId());
                        term.setActiveNo(customer.getString("activeNo"));
                        term.setBusiTypeCode(customer.getString("bzPos"));
                        term.setBusiTypeName("码牌");
                        term.setProductCode(customer.getString("bzPos"));
                        term.setProductName("码牌");
                        term.setTermNo(customer.getString("termNo"));
                        merPlatformTermService.editMerPlatformTerm(term);

                        JSONArray terminalList = merchantInfo.getJSONArray("terminalInfo");
                        for (Object terminalObj : terminalList) {
                            JSONObject terminal = (JSONObject) terminalObj;
                            // 终端编号
                            JSONArray termNoList = terminal.getJSONArray("termNoList");
                            for (Object termNo : termNoList) {
                                term = new BsMerPlatformTerm();
                                term.setMerPlatformNoId(platform.getId());
                                term.setMerId(platform.getMerId());
                                term.setActiveNo(customer.getString("activeNo"));
                                term.setBusiTypeCode(terminal.getString("termTypeCode"));
                                term.setBusiTypeName(terminal.getString("termTypeName"));
                                term.setProductCode(terminal.getString("termTypeCode"));
                                term.setProductName(terminal.getString("termTypeName"));
                                term.setTermId(terminal.getString("coreTermId"));
                                term.setTermNo(termNo.toString());
                                merPlatformTermService.editMerPlatformTerm(term);
                            }
                        }

                    } else if (customer.getString("customerStatus").equals("REJECT")) {
                        contractRecord.setStatus(3);
                        merContractRecordService.updateRecord(contractRecord);

                        mer.setMerStatus(MerStatusEnum.status4.getNumber());
                        merService.editMer(mer);

                        BsMerContractRecordMsg merContractRecordMsg = new BsMerContractRecordMsg();
                        merContractRecordMsg.setOrderNo(contractRecord.getOrderNo());
                        merContractRecordMsg.setType(1);
                        merContractRecordMsg.setResponseCode(customer.getString("customerStatus"));
                        merContractRecordMsg.setResponseMsg(customer.getString("auditRemark"));
                        merContractRecordMsg.setResponseMsg(customer.getString("auditRemark"));
                        merContractRecordMsgService.insertRecordMsg(merContractRecordMsg);
                    }
                }
            }

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

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/lklWithdraw",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "lklWithdraw")
    public ResponseData lklWithdraw(@RequestParam(value = "cupNo", required = true) String cupNo) {
        try {

            // return ResponseMsgUtil.success(laKaLaWalletService.ewalletBalanceQuery("8226900581219V0", null,"01"));
            // return ResponseMsgUtil.success(laKaLaWalletService.ewalletWithdrawD1("8226900581219V0", new BigDecimal("30193.35"),"提现"));
            return ResponseMsgUtil.success(laKaLaWalletService.ewalletSettleProfile(
                    1,
                    cupNo,
                    "02",
                    "06",
                    CommonSysConst.getSysConfig().getDomainName()+"/crest/merWithdrawal/notify?cupNo="+cupNo));
            // return ResponseMsgUtil.success(laKaLaWalletService.ewalletWithdrawQuery("8226900581219V0", "230602150213408367448221"));
            // return ResponseMsgUtil.success(laKaLaWalletService.ewalletSettleQuery("8226900591200TC"));
            // return ResponseMsgUtil.success(laKaLaWalletService.activeSettleApply("8226900581219V0"));

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/saasGetToken",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "saasGetToken")
    public ResponseData saasGetToken() {
        try {

            return ResponseMsgUtil.success(LaKaLaConfig.queryCardBin("3100020709200056842"));
/*            // 转换成bas64
            String imageUrl = "https://gratia-pay-test.obs.cn-east-3.myhuaweicloud.com/merchant/57/1682405639861.jpeg";
            String base64ImgUrl = ImageUtils.getBase64ByImgUrl(imageUrl);
            String fileType = imageUrl.substring(imageUrl.lastIndexOf(".")  1);
            return ResponseMsgUtil.success(LaKaLaConfig.uploadFile("COOPERATION_QUALIFICATION_PROOF", fileType, base64ImgUrl));*/

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @Resource
    private TianQueMerService tianQueMerService;
    @Resource
    private TianQueTradeService tianQueTradeService;
    @Resource
    private TianQueMerElecSignService tianQueMerElecSignService;
    @RequestMapping(value="/tianQueTest",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "tianQueTest")
    public ResponseData tianQueTest(@RequestParam(value = "code", required = true) String code) {
        try {
            // tianQueMerService.addMer(Long.parseLong(code));
            return ResponseMsgUtil.success(tianQueMerService.queryMerchantInfo(code));
            // return ResponseMsgUtil.success(tianQueTradeService.preorder(code));
            // return ResponseMsgUtil.success(tianQueTradeService.queryTrade(code));
            // return ResponseMsgUtil.success(tianQueTradeService.poundageQuery("399200427027644",code));
            // return ResponseMsgUtil.success(tianQueTradeService.refund(code, new BigDecimal("0.01")));
            // return ResponseMsgUtil.success(tianQueTradeService.refundQuery(code));
            // return ResponseMsgUtil.success("");
            // 1200
            // return ResponseMsgUtil.success(saasCommon.fileUpload(new HashMap<>()));
           /* AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
            request.setGrantType("authorization_code");
            request.setCode(code);
            AlipaySystemOauthTokenResponse response = AlipayUtils.initClient().certificateExecute(request);
            if(response.isSuccess()){
                System.out.println("调用成功");
                return ResponseMsgUtil.success(response);
            } else {
                System.out.println("调用失败");
                return ResponseMsgUtil.success("调用失败");
            }*/
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/saasTest",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "saasTest")
    public ResponseData saasTest(@RequestParam(value = "code", required = true) String code) {
        try {
            // return ResponseMsgUtil.success(saasCommon.fileUpload(new File("D:/home/project/gratia-pay/filesystem/share/1680164428924.png"), "OTHERS", "0"));
            // 996900  6900 6905
            // return ResponseMsgUtil.success(saasCommon.getArea("1"));
            //return ResponseMsgUtil.success(saasCommon.getBank("6530", "恒丰银行重庆渝北支行"));

            // tradeOrderProfitSharingService.createProfitSharing(tradeOrderService.getOrderByOutTradeNo("ZF1130202304261043149211335400"));
            // laKaLaLedgerService.queryLedgerMer("8226900481608NL");
            //laKaLaTradeSeparateService.separate("1530202304261049572195600000");
            // tradeOrderProfitSharingService.createProfitSharing(tradeOrderService.getOrderByOutTradeNo("ZF1130202304261734049211335408"));
            // return ResponseMsgUtil.success(saasCommon.getUpdateToken());
/*            return ResponseMsgUtil.success(saasMerService.reconsiderSubmit("123364703"));*/
            //return ResponseMsgUtil.success(saasMerService.merchantInfo("123364703"));
            // return ResponseMsgUtil.success(saasCommon.getCategory(null));
            // return ResponseMsgUtil.success(laKaLaLedgerService.queryLedgerMer(code));
            return ResponseMsgUtil.success(laKaLaTradeService.queryTradeOrderTrans(code));
            //  return ResponseMsgUtil.success(laKaLaTradeService.queryTrade(code));
            // return ResponseMsgUtil.success("");
            // 1200
            // return ResponseMsgUtil.success(saasCommon.fileUpload(new HashMap<>()));
           /* AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
            request.setGrantType("authorization_code");
            request.setCode(code);
            AlipaySystemOauthTokenResponse response = AlipayUtils.initClient().certificateExecute(request);
            if(response.isSuccess()){
                System.out.println("调用成功");
                return ResponseMsgUtil.success(response);
            } else {
                System.out.println("调用失败");
                return ResponseMsgUtil.success("调用失败");
            }*/
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/pushToSingleByCid",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "pushToSingleByCid")
    public ResponseData pushToSingleByCid(@RequestParam(value = "code", required = true) String code) {
        try {

            JSONObject object = new JSONObject();
            object.put("cid", code);
            object.put("price", "0.01");

            // 获取语音播报地址
            String auditPath = HWYunSisService.ttsCustomDemo(object);
            String taskNo = Base64Util.generateOrderNo();
            String msg = CommonSysConst.getSysConfig().getDomainName() + auditPath + "!@#PUSH#@!" + taskNo + "!@#PUSH#@!" + "惠支付收款：" + object.getBigDecimal("price");
            object.put("body", msg);

            return ResponseMsgUtil.success(UniPushService.pushToSingleByCid(object));

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/saasUpdateFee",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "saasUpdateFee")
    public ResponseData saasUpdateFee(@RequestParam(value = "merId", required = true) Long merId) {
        try {

            // return ResponseMsgUtil.success(saasMerService.updateReview(reviewRelatedId);
          /*  int[] idArray = {74,75,76,77,78,79,81,82,85,89,90,92,95,97,98,100,100,101,101,102,104,105};
            for (int i = 0; i < idArray.length; i) {
                int id = idArray[i];
                // saasMerService.updateFee(Long.parseLong(id""));
            }*/
            // return ResponseMsgUtil.success("");
            return ResponseMsgUtil.success(saasMerService.updateFee(merId));
            // return ResponseMsgUtil.success(saasMerService.queryFee(85L));
            //return ResponseMsgUtil.success(saasMerService.updateReview(merId.toString()));

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/updateReview",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "updateReview")
    public ResponseData updateReview(@RequestParam(value = "reviewRelatedId", required = true) String reviewRelatedId) {
        try {

            return ResponseMsgUtil.success(saasMerService.updateReview(reviewRelatedId));

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/soundSendMsg",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "音响发送消息")
    public ResponseData soundSendMsg() {
        try {

/*            AlipayClient alipayClient = AlipayUtils.initClient();

            AntMerchantExpandIndirectZftConsultRequest request = new AntMerchantExpandIndirectZftConsultRequest();
            request.setBizContent("");
            AntMerchantExpandIndirectZftConsultResponse execute = alipayClient.certificateExecute(request);*/


            // soundService.sendPayMsg("898604A2192181729951", new BigDecimal("12.99"));
            // soundService.geSoundInfo("898604A2192181729951");
            return ResponseMsgUtil.success(tradeOrderService.getOrderByOutTradeNoOrPlatformTradeNo("ZF1130202304261716539211335407"));
            // soundService.geSoundDetail("898604A2192181729951");
            // return ResponseMsgUtil.success(AlipayRequest.imageUpload("C:/Users/hurui/Desktop/default_oil_station.jpg"));

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @Resource
    private BsBankActivityService bankActivityService;

    @RequestMapping(value="/refreshActivityList",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取活动列表")
    public ResponseData refreshActivityList() {
        try {

            JSONArray jsonArray = saasActivityService.queryAgentActivityList();
            for (Object obj : jsonArray) {
                JSONObject activity = (JSONObject) obj;

                BsBankActivity bankActivity = bankActivityService.getBankActivityByNo(activity.getLong("activityId"));
                if (bankActivity == null) {
                    bankActivity = new BsBankActivity();
                }
                bankActivity.setRegions(activity.getString("regions"));
                bankActivity.setActivityNo(activity.getLong("activityId"));
                bankActivity.setActivityName(activity.getString("activityName"));
                bankActivity.setEffectiveStart(activity.getDate("effectiveStart"));
                bankActivity.setEffectiveEnd(activity.getDate("effectiveEnd"));
                bankActivity.setRegistrationStart(activity.getDate("registrationStart"));
                bankActivity.setRegistrationEnd(activity.getDate("registrationEnd"));
                bankActivity.setDetails(activity.getString("details"));
                bankActivity.setComments(activity.getString("comments"));
                bankActivity.setStatus(1);
                bankActivityService.editData(bankActivity);
            }
            return ResponseMsgUtil.success(null);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/merchantIndirectConsult",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "图片上传")
    public ResponseData merchantIndirectConsult() {
        try {

            Map<String,Object> body = new HashMap<>();
            body.put("external_id", System.currentTimeMillis());
            body.put("name", "");
            body.put("alias_name", "");
            body.put("merchant_type", "");
            body.put("mcc", "");
            body.put("cert_no", "");
            body.put("cert_type", "");
            body.put("cert_image", "");
            body.put("cert_name", "");
            body.put("cert_image_back", "");
            body.put("legal_name", "");
            body.put("legal_cert_no", "");
            body.put("legal_cert_front_image", "");
            body.put("legal_cert_back_image", "");
            body.put("service_phone", "");

            Map<String,Object> businessAddress = new HashMap<>();
            businessAddress.put("city_code", "");
            businessAddress.put("district_code", "");
            businessAddress.put("address", "");
            businessAddress.put("province_code", "");
            body.put("business_address", businessAddress);


            Map<String,Object> contactInfos = new HashMap<>();
            contactInfos.put("name", "");
            contactInfos.put("phone", "");
            contactInfos.put("mobile", "");
            contactInfos.put("email", "");
            contactInfos.put("id_card_no", "");
            body.put("contact_infos", contactInfos);

            Map<String,Object> bizCards = new HashMap<>();
            bizCards.put("account_holder_name", "");
            bizCards.put("account_no", "");
            bizCards.put("account_inst_province", "");
            bizCards.put("account_inst_city", "");
            bizCards.put("account_branch_name", "");
            bizCards.put("usage_type", "");
            bizCards.put("account_type", "");
            bizCards.put("account_inst_name", "");
            bizCards.put("account_inst_id", "");
            bizCards.put("bank_code", "");
            body.put("biz_cards", bizCards);

            Map<String,Object> qualifications = new HashMap<>();
            qualifications.put("industry_qualification_type", "");
            qualifications.put("industry_qualification_image", "");
            body.put("qualifications", qualifications);

            body.put("out_door_images", "");
            // body.put("service", ['当面付', 'app支付', 'wap支付', '电脑支付']);
            body.put("sign_time_with_isv", DateUtil.date2String(new Date(), "yyyy-MM-dd"));

            Map<String,Object> sites = new HashMap<>();
            body.put("sites", sites);

            Map<String,Object> invoiceInfo = new HashMap<>();
            body.put("invoice_info", invoiceInfo);


            AlipayRequest.merchantIndirectConsult(JSONObject.toJSONString(body));

            return ResponseMsgUtil.success("");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/saasActivity",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "saasActivity")
    public ResponseData saasActivity(@RequestParam(value = "code", required = false) String code) {
        try {
            // return ResponseMsgUtil.success(saasActivityService.queryAgentActivityStatus("73"));
            // return ResponseMsgUtil.success(saasActivityService.agentRegisterActivity("73"));
            // return ResponseMsgUtil.success(saasActivityService.queryAgentActivityList());
            // return ResponseMsgUtil.success(saasActivityService.queryCustomerActivityStatus("73", "8226900445800HB"));

            /*********** 活动报名 *************/
            List<String> externalCustomerNos = new ArrayList<>();
            externalCustomerNos.add(code);
            // externalCustomerNos.add("8226900566100K0");
            // externalCustomerNos.add("82269005714051G");
            // externalCustomerNos.add("8226900899900CW");
            // externalCustomerNos.add("822690058121BAY");
            // externalCustomerNos.add("8226900899900CY");
            // externalCustomerNos.add("822690058121BDR");
            // externalCustomerNos.add("8226900729808JR");
            // externalCustomerNos.add("8226900566100JV");
            // externalCustomerNos.add("8226900566100JY");
            // externalCustomerNos.add("8226900899900DF");

            // 冉家坝支行
           /* externalCustomerNos.add("8226900445800HS");
            externalCustomerNos.add("82269005072004T");
            externalCustomerNos.add("8226900421500NJ");
            externalCustomerNos.add("822690053310F23");*/

            // 合川支行
            // externalCustomerNos.add("82269005399025K");
            // externalCustomerNos.add("822690058121C65");
            // externalCustomerNos.add("8226900899900DB");
            // externalCustomerNos.add("822690053310F6C");

            // return ResponseMsgUtil.success(saasActivityService.customerRegisterActivity("73", "315653020019", "0",externalCustomerNos));
            // return ResponseMsgUtil.success(saasActivityService.referee(code));
            /******* 配置活动费率 *******/
            String activityId = "73";
            String externalCustomerNo = code;
            JSONArray jsonArray = saasActivityService.queryCustomerRates(activityId, externalCustomerNo);
            return ResponseMsgUtil.success(jsonArray);
/*            Map<String, Object> rate;
            List<Map<String,Object>> rates = new ArrayList<>();

            for (Object obj : jsonArray) {
                JSONObject jsonObject = (JSONObject) obj;
                rate = new HashMap<>();
                rate.put("welfareRatesId", jsonObject.getLong("welfareRatesId"));
                rate.put("discountedRates", "0.0025");
                rates.add(rate);
            }
            return ResponseMsgUtil.success(saasActivityService.customerRatesUpdate(activityId,externalCustomerNo, rates));*/
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/saasActivity1",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "saasActivity1")
    public ResponseData saasActivity1(@RequestParam(value = "code", required = false) String code) {
        try {

            String str = "[{\"ratesStatus\":\"NOT\",\"rates\":[0.0025],\"start\":\"2023-05-15 00:00:00\",\"preferentialTypes\":[\"WXPAY\",\"ALIPAY\"],\"configModel\":\"SPECIFIED\",\"type\":24,\"quotaLimit\":100000.0,\"timeBundleNo\":93985,\"current\":true,\"preferentialModel\":\"QUOTA\",\"welfareRatesId\":884,\"ratesModel\":\"DISCOUNTED\",\"end\":\"2023-05-31 23:59:59\",\"order\":1},{\"ratesStatus\":\"NOT\",\"rates\":[0.0025],\"start\":\"2023-06-01 00:00:00\",\"preferentialTypes\":[\"WXPAY\",\"ALIPAY\"],\"configModel\":\"SPECIFIED\",\"type\":24,\"quotaLimit\":100000.0,\"timeBundleNo\":93986,\"current\":false,\"preferentialModel\":\"QUOTA\",\"welfareRatesId\":885,\"ratesModel\":\"DISCOUNTED\",\"end\":\"2023-06-30 23:59:59\",\"order\":2},{\"ratesStatus\":\"NOT\",\"rates\":[0.0025],\"start\":\"2023-07-01 00:00:00\",\"preferentialTypes\":[\"WXPAY\",\"ALIPAY\"],\"configModel\":\"SPECIFIED\",\"type\":24,\"quotaLimit\":100000.0,\"timeBundleNo\":93987,\"current\":false,\"preferentialModel\":\"QUOTA\",\"welfareRatesId\":886,\"ratesModel\":\"DISCOUNTED\",\"end\":\"2023-07-31 23:59:59\",\"order\":3},{\"ratesStatus\":\"NOT\",\"rates\":[0.0025],\"start\":\"2023-08-01 00:00:00\",\"preferentialTypes\":[\"WXPAY\",\"ALIPAY\"],\"configModel\":\"SPECIFIED\",\"type\":24,\"quotaLimit\":100000.0,\"timeBundleNo\":93988,\"current\":false,\"preferentialModel\":\"QUOTA\",\"welfareRatesId\":887,\"ratesModel\":\"DISCOUNTED\",\"end\":\"2023-08-31 23:59:59\",\"order\":4},{\"ratesStatus\":\"NOT\",\"rates\":[0.0025],\"start\":\"2023-09-01 00:00:00\",\"preferentialTypes\":[\"WXPAY\",\"ALIPAY\"],\"configModel\":\"SPECIFIED\",\"type\":24,\"quotaLimit\":100000.0,\"timeBundleNo\":93989,\"current\":false,\"preferentialModel\":\"QUOTA\",\"welfareRatesId\":888,\"ratesModel\":\"DISCOUNTED\",\"end\":\"2023-09-30 23:59:59\",\"order\":5},{\"ratesStatus\":\"NOT\",\"rates\":[0.0025],\"start\":\"2023-10-01 00:00:00\",\"preferentialTypes\":[\"WXPAY\",\"ALIPAY\"],\"configModel\":\"SPECIFIED\",\"type\":24,\"quotaLimit\":100000.0,\"timeBundleNo\":93990,\"current\":false,\"preferentialModel\":\"QUOTA\",\"welfareRatesId\":889,\"ratesModel\":\"DISCOUNTED\",\"end\":\"2023-10-31 23:59:59\",\"order\":6},{\"ratesStatus\":\"NOT\",\"rates\":[0.0025],\"start\":\"2023-11-01 00:00:00\",\"preferentialTypes\":[\"WXPAY\",\"ALIPAY\"],\"configModel\":\"SPECIFIED\",\"type\":24,\"quotaLimit\":100000.0,\"timeBundleNo\":93991,\"current\":false,\"preferentialModel\":\"QUOTA\",\"welfareRatesId\":890,\"ratesModel\":\"DISCOUNTED\",\"end\":\"2023-11-30 23:59:59\",\"order\":7},{\"ratesStatus\":\"NOT\",\"rates\":[0.0025],\"start\":\"2023-12-01 00:00:00\",\"preferentialTypes\":[\"WXPAY\",\"ALIPAY\"],\"configModel\":\"SPECIFIED\",\"type\":24,\"quotaLimit\":100000.0,\"timeBundleNo\":93992,\"current\":false,\"preferentialModel\":\"QUOTA\",\"welfareRatesId\":891,\"ratesModel\":\"DISCOUNTED\",\"end\":\"2023-12-31 23:59:59\",\"order\":8},{\"ratesStatus\":\"NOT\",\"rates\":[0.0025],\"start\":\"2024-01-01 00:00:00\",\"preferentialTypes\":[\"WXPAY\",\"ALIPAY\"],\"configModel\":\"SPECIFIED\",\"type\":24,\"quotaLimit\":100000.0,\"timeBundleNo\":93993,\"current\":false,\"preferentialModel\":\"QUOTA\",\"welfareRatesId\":892,\"ratesModel\":\"DISCOUNTED\",\"end\":\"2024-01-31 23:59:59\",\"order\":9},{\"ratesStatus\":\"NOT\",\"rates\":[0.0025],\"start\":\"2024-02-01 00:00:00\",\"preferentialTypes\":[\"WXPAY\",\"ALIPAY\"],\"configModel\":\"SPECIFIED\",\"type\":24,\"quotaLimit\":100000.0,\"timeBundleNo\":93994,\"current\":false,\"preferentialModel\":\"QUOTA\",\"welfareRatesId\":893,\"ratesModel\":\"DISCOUNTED\",\"end\":\"2024-02-29 23:59:59\",\"order\":10},{\"ratesStatus\":\"NOT\",\"rates\":[0.0025],\"start\":\"2024-03-01 00:00:00\",\"preferentialTypes\":[\"WXPAY\",\"ALIPAY\"],\"configModel\":\"SPECIFIED\",\"type\":24,\"quotaLimit\":100000.0,\"timeBundleNo\":93995,\"current\":false,\"preferentialModel\":\"QUOTA\",\"welfareRatesId\":894,\"ratesModel\":\"DISCOUNTED\",\"end\":\"2024-03-31 23:59:59\",\"order\":11}]";
            JSONArray array = JSONArray.parseArray(str);

            for (Object obj : array) {
                JSONObject rate = (JSONObject) obj;
                BsBankActivityRosterRate rosterRate = new BsBankActivityRosterRate();
                rosterRate.setBankActivityId(57L);
                rosterRate.setBankActivityRosterId(0L);
                rosterRate.setMerId(57L);
                rosterRate.setPlatformNo("100112200");
                rosterRate.setCupNo("822290058120KK2");
                rosterRate.setWelfareRatesId(rate.getLong("welfareRatesId"));
                rosterRate.setStartTime(rate.getDate("start"));
                rosterRate.setEndTime(rate.getDate("end"));
                rosterRate.setRates(rate.getString("rates"));
                rosterRate.setStatus(2);
                bankActivityRosterRateService.editData(rosterRate);
            }
            return ResponseMsgUtil.success(null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/generate",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "图片上传")
    public ResponseData generate() {
        try {


            MerBasisModel merDetail = merService.getMerDetail(57L);
/*
            Configuration cfg = new Configuration();
            cfg.setDirectoryForTemplateLoading(new File("D:/home"));
            Template template = cfg.getTemplate("indexHTKWECHAT_PAY.html");

            Map<String,Object> param = new HashMap<>();
            param.put("width", "100%");
            param.put("tbTitleWidth", "120px");
            param.put("tbConWidth", "100px");

            Map<String,Object> fee = new HashMap<>();
            fee.put("customerName", merDetail.getBlisName());
            param.put("fee", fee);

            // 执照信息
            if (merDetail.getMerType().equals(MerTypeEnum.status3.getNumber())) {
                param.put("licenseNo", "");
                param.put("legalName", "");
                param.put("licenseName", "");
                param.put("identityNo", "");
                param.put("address", "") ;
                param.put("identityNoExpire", "");
                param.put("receiveDetail", "");

            } else {
                param.put("licenseNo", merDetail.getBlisNo());
                param.put("legalName", merDetail.getLarName());
                param.put("licenseName", merDetail.getBlisName());
                param.put("identityNo", merDetail.getLarIdCard());
                param.put("address", merDetail.getMerRegion().getProvinceName()merDetail.getMerRegion().getCityName()merDetail.getMerRegion().getAreaName()) ;
                param.put("identityNoExpire", merDetail.getLarIdCardPeriodStart()  " —— "  merDetail.getLarIdCardPeriodEnd());
                param.put("receiveDetail", merDetail.getMerRegion().getAddress());
            }

            // 结算信息
            param.put("accountName", merDetail.getMerSettleAcct().getBankName());
            param.put("accountIdCard", merDetail.getMerSettleAcct().getSettleIdCardNo());
            param.put("accountNo", merDetail.getMerSettleAcct().getBankCardNo());
            param.put("accountIdDtEnd", merDetail.getMerSettleAcct().getSettleIdCardPeriodStart()  " —— "  merDetail.getMerSettleAcct().getSettleIdCardPeriodEnd());
            param.put("bankName", merDetail.getMerSettleAcct().getOpenningBankName());

            // 商户信息
            param.put("licenseName", merDetail.getBlisName());
            param.put("mail", merDetail.getRegEmail());
            param.put("contactManName", merDetail.getRegName());
            param.put("phone", merDetail.getRegPhone());
            param.put("channelType", merDetail.getMerIndustry().getChildName());
            param.put("receiveDetail", merDetail.getStoreModel().getStoreRegion().getAddress());
            param.put("agencyName", "重庆惠付科技有限公司");
            GenerateAgreementUtil.createAgreementPicture(merDetail.getId(),GenerateAgreementUtil.writeHtml(merDetail.getId(),template, param));
*/

            return ResponseMsgUtil.success(saasCommon.fileUpload(new File(CommonSysConst.getSysConfig().getFile_url() + "/" + SaasMerService.generateAddContract(merDetail)), "OPENING_PERMIT", "0").getString("url"));

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/rebate", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "返利")
    public ResponseData rebate(@RequestParam(name = "orderNo", required = true) String orderNo,
                                            @RequestParam(name = "orderId", required = true) Long orderId,
                                            @RequestParam(name = "price", required = true) BigDecimal price) {
        try {

            Map<String , Object> mapPost = new HashMap<>();
            mapPost.put("apiKey" , "0C7897EA3BD96156A5881618FF2FF645");
            mapPost.put("merchId" , "20230258302");
            mapPost.put("productType" , 102); // 101 普通支付  102 商家活动差价返利
            mapPost.put("orderNo" , orderNo);
            mapPost.put("phone" , 366);
            mapPost.put("orderId" , orderId);
            mapPost.put("price" , price);
            mapPost.put("title" , "南充大饭店");
            mapPost.put("createTime" , new Date());
            mapPost.put("sign" , WxUtils.generateSignApi(mapPost, MapUtils.getString(mapPost, "apiKey"), WXPayConstants.SignType.MD5));
            return ResponseMsgUtil.success(HttpsUtils.doPost("http://localhost:9902/v1/orderRebate/rebate" , mapPost , new HashMap<>()));
        } catch (Exception e) {
            log.error("HighOrderController --> getBackendToken() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/ttsCustomDemo",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "ttsCustomDemo")
    public ResponseData ttsCustomDemo() {
        try {

            JSONObject object = new JSONObject();
            object.put("price" , "374.87");

            return ResponseMsgUtil.success(HWYunSisService.ttsCustomDemo(object));

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/uniPush",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "uniPush")
    public ResponseData uniPush(@RequestParam(name = "storeId", required = true) Long storeId,@RequestParam(name = "price", required = true) BigDecimal price) {
        try {

            // merContractService.addMerContract(storeId, null);
            // tianQueMerService.queryMerchantInfo("75a7161a441f49568b55bca14c03e743");
            JSONObject object = new JSONObject();
/*
            object.put("price", price);
            object.put("storeId", storeId);
            bsStoreCidService.storePush(object);*/


            return ResponseMsgUtil.success("成功");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
