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.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.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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

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

}
