package com.bweb.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.LaKaLaMerService;
import com.hfkj.channel.lakala.LaKaLaTradeSeparateService;
import com.hfkj.channel.lakala.LaKaLaTradeService;
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.weixin.WeiXinMerService;
import com.hfkj.channel.weixin.utils.WxUtils;
import com.hfkj.channel.weixin.utils.sdk.WXPayConstants;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.common.utils.ResponseMsgUtil;
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.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
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.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 SaasMerService saasMerService;

    @Resource
    private BsTradeOrderProfitSharingService tradeOrderProfitSharingService;
    @Resource
    private BsMerLedgerService merLedgerService;
    @Resource
    private BsMerService merService;

    @Resource
    private BsMerPlatformNoService merPlatformNoService;
    @Resource
    private BsMerContractRecordMsgService merContractRecordMsgService;
    @Resource
    private BsMerContractRecordService merContractRecordService;
    @Resource
    private BsMerPlatformTermService merPlatformTermService;
    @Resource
    private BsStoreService storeService;
    @Resource
    private LaKaLaLedgerService laKaLaLedgerService;
    @Resource
    private LaKaLaTradeSeparateService laKaLaTradeSeparateService;
    @Resource
    private BsTradeOrderService tradeOrderService;
    @Resource
    private LaKaLaTradeService laKaLaTradeService;

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

            return ResponseMsgUtil.success(laKaLaTradeService.preorder(tradeNo));

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

    @RequestMapping(value="/queryTrans",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "queryTrans")
    public ResponseData queryTrans(@RequestParam(value = "merId", required = true) Long merId,
                                   @RequestParam(value = "code", required = true) String code) {
        try {
            // 查询商户号
            BsMerPlatformNo platformNo = merPlatformNoService.getPlatformNo(merId, PlatformTypeEnum.type1);
            if (platformNo == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户号");
            }
            // 查询终端号
            BsMerPlatformTerm merPlatformTerm = merPlatformTermService.getMerPlatformTerm(platformNo.getId(), "WECHAT_PAY");
            if (merPlatformTerm == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户终端号");
            }
            Map<String, Object> commonParam = new HashMap<>();
            commonParam.put("req_time", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
            commonParam.put("version", "3.0");

            Map<String, Object> map = new HashMap<>();
            map.put("merchant_no", platformNo.getCupNo());
            map.put("term_no", merPlatformTerm.getTermNo());
            map.put("log_no", code);
            commonParam.put("req_data", map);

            Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV3(JSONObject.parseObject(JSONObject.toJSONString(commonParam)));

            // 头部参数
            Map<String, Object> heard = new HashMap<>();
            heard.put("Authorization", reqParam.get("Authorization"));

            // 请求记录
            // 请求拉卡拉接口
            JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v3/lams/merchant/query_trans", commonParam, heard);
            log.info("请求参数："+ JSONObject.toJSONString(commonParam));
            log.info("响应参数："+ JSONObject.toJSONString(responseBody));
            System.out.println("请求参数："+ JSONObject.toJSONString(commonParam));
            System.out.println("响应参数："+ JSONObject.toJSONString(responseBody));
            if (!responseBody.getString("code").equals("000000")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("msg"));
            }
            return ResponseMsgUtil.success(responseBody.getJSONObject("resp_data"));

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



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

            Map<String, Object> param = new HashMap<>();
            param.put("status", "3");
            List<BsTradeOrder> orderList = tradeOrderService.getTradeOrderList(param);
            for (BsTradeOrder order : orderList) {
                try {
                    JSONObject queryTrade = laKaLaTradeService.queryTrade(order.getOutTradeNo());
                    if (queryTrade != null) {
                        order.setTradeActualAmount(queryTrade.getBigDecimal("total_amount").divide(new BigDecimal("100")));
                        order.setAccSettleAmount(
                                StringUtils.isNotBlank(queryTrade.getString("acc_settle_amount"))
                                        ?queryTrade.getBigDecimal("acc_settle_amount").divide(new BigDecimal("100"))
                                        :new BigDecimal("0"));

                        order.setAccDiscountAmount(
                                StringUtils.isNotBlank(queryTrade.getString("acc_discount_amount"))
                                        ?queryTrade.getBigDecimal("acc_discount_amount").divide(new BigDecimal("100"))
                                        :new BigDecimal("0"));

                        order.setAccMdiscountAmount(
                                StringUtils.isNotBlank(queryTrade.getString("acc_mdiscount_amount"))
                                        ?queryTrade.getBigDecimal("acc_mdiscount_amount").divide(new BigDecimal("100"))
                                        :new BigDecimal("0"));
                        tradeOrderService.editOrder(order);
                    }
                } catch (Exception e) {

                }
            }
            return ResponseMsgUtil.success("");

        } 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.updateFee(merId));

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

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

            return ResponseMsgUtil.success(saasMerService.merchantInfo(customerNo));

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

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

            return ResponseMsgUtil.success(saasMerService.queryFee(merId));

        } 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="/separate",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "separate")
    public ResponseData separate(@RequestParam(value = "ProfitSharingOrderNo", required = true) String ProfitSharingOrderNo) {
        try {

            return ResponseMsgUtil.success(laKaLaTradeSeparateService.separate(ProfitSharingOrderNo));

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

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

            return ResponseMsgUtil.success(laKaLaTradeSeparateService.query(ProfitSharingOrderNo));

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

    @RequestMapping(value="/queryAmt",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "separateQuery")
    public ResponseData separateQueryAmt(@RequestParam(value = "ProfitSharingOrderNo", required = true) String ProfitSharingOrderNo) {
        try {

            return ResponseMsgUtil.success(laKaLaTradeSeparateService.queryAmt(ProfitSharingOrderNo));

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

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

            Map<String, Object> param = new HashMap<>();
            param.put("SAAS_TOKEN", saasCommon.getToken());
            param.put("SAAS_UPDATE_TOKEN", saasCommon.getUpdateToken());
            return ResponseMsgUtil.success(param);

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

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

            Map<String, Object> param = new HashMap<>();
            param.put("merStatus", MerStatusEnum.status1.getNumber());
            List<BsMer> merList = merService.getMerList(param);

            BsMerLedger merLedger;
            for (BsMer mer : merList) {
                try {
                    if (merLedgerService.getMerLedger(mer.getId(), PlatformTypeEnum.type1) == null) {
                        BsMerPlatformNo merPlatform = merPlatformNoService.getPlatformNo(mer.getId(), PlatformTypeEnum.type1);
                        merLedger = new BsMerLedger();
                        merLedger.setMerId(mer.getId());
                        merLedger.setMerName(mer.getMerName());
                        merLedger.setPlatformType(merPlatform.getPlatformType());
                        merLedger.setPlatformNo(merPlatform.getPlatformNo());
                        merLedger.setCupNo(merPlatform.getCupNo());
                        merLedger.setStatus(MerLedgerStatusEnum.status2.getNumber());
                        merLedger.setReceiverStatus(false);
                        merLedgerService.editMerLedger(merLedger);

                        laKaLaLedgerService.applyLedgerReceiver(merLedger.getMerId());
                    }
                } catch (Exception e) {

                }
            }
            return ResponseMsgUtil.success("");

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

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

}
