package com.cweb.notify;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.lakala.LaKaLaLedgerService;
import com.hfkj.channel.lakala.LaKaLaWalletService;
import com.hfkj.channel.tianque.service.TianQueMerElecSignService;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.*;
import com.hfkj.service.*;
import com.hfkj.sysenum.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 天阙业务通知
 * @author hurui
 */
@Controller
@Api(value = "天阙通知")
@RequestMapping(value = "/tianqueNotify")
public class TianQueController {

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

    @Resource
    private BsTradeOrderService tradeOrderService;
    @Resource
    private BsTradeOrderMsgService tradeOrderMsgService;
    @Resource
    private BsMerService merService;
    @Resource
    private BsMerPlatformNoService merPlatformNoService;
    @Resource
    private BsMerPlatformTermService merPlatformTermService;
    @Resource
    private BsStoreService storeService;
    @Resource
    private BsMerContractRecordService merContractRecordService;
    @Resource
    private BsMerContractRecordMsgService merContractRecordMsgService;
    @Resource
    private TianQueMerElecSignService tianQueMerElecSignService;

    @RequestMapping(value="/microPay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "交易【被扫】通知")
    public void microPay(@RequestBody String reqBody, HttpServletResponse response) {
        try {
            log.info("交易【被扫】通知", reqBody);
            System.out.println(reqBody);

            JSONObject body = JSONObject.parseObject(reqBody);
            // 请求记录
            BsTradeOrderMsg orderMsg = new BsTradeOrderMsg();
            orderMsg.setOutTradeNo(body.getString("ordNo"));
            orderMsg.setType(TradeOrderMsgTypeEnum.type2.getNumber());
            orderMsg.setResponseContent(reqBody);
            tradeOrderMsgService.editTradeOrderMsg(orderMsg);

            // 查询订单
            BsTradeOrder order = tradeOrderService.getOrderByOutTradeNo(body.getString("ordNo"));
            if (order != null) {
                Map<String,Object> other = new HashMap<>();
                other.put("acc_trade_no", body.getString("transactionId"));
                other.put("card_type", body.getString("drType"));

                if (body.getString("acc_settle_amount") != null) {
                    other.put("acc_settle_amount", body.getBigDecimal("amt"));
                }
                if (body.getString("pointAmount") != null) {
                    other.put("acc_discount_amount", body.getBigDecimal("pointAmount"));
                }
                if (body.getString("clearDt") != null) {
                    other.put("settleDate", DateUtil.format(body.getString("clearDt"), "yyyyMMdd").getTime());
                }
                if (body.getString("settleAmt") != null) {
                    other.put("settleAmount", body.getBigDecimal("settleAmt"));
                }

                tradeOrderService.paySuccess(
                        body.getString("ordNo"),
                        body.getString("uuid"),
                        PlatformTypeEnum.type5,
                        TradeOrderPayModeEnum.getNameByCode(body.getString("payType")),
                        body.getBigDecimal("totalOffstAmt"),
                        body.getString("mno"),
                        other
                );
            }

        } catch (Exception e) {
            log.error("login error!",e);
        } finally {
            try {
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
                JSONObject result = new JSONObject();
                result.put("code", "success");
                result.put("message", "成功");
                out.write(result.toJSONString().getBytes());
                out.flush();
                out.close();
            } catch (Exception e) {

            }

        }
    }

    @RequestMapping(value="/merInbound",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "商户进件通知")
    public void merInbound(@RequestBody String reqBody, HttpServletResponse response) {
        try {
            log.info("商户进件通知", reqBody);
            System.out.println(reqBody);

            JSONObject respData = JSONObject.parseObject(reqBody);

            BsMerContractRecord merContractRecord = merContractRecordService.getRecordByContractId(respData.getString("applicationId"));
            if (merContractRecord != null && merContractRecord.getStatus().equals(1)) {
                // 审核状态，枚举值 取值范围：1 入驻通过 2 入驻驳回 5 商户修改通过 6 商户修改驳回
                if (respData.getString("taskStatus").equals("1") || respData.getString("taskStatus").equals("5")) {
                    merContractRecord.setStatus(2);
                } else {
                    merContractRecord.setStatus(3);
                }
                merContractRecordService.updateRecord(merContractRecord);

                BsMerContractRecordMsg merContractRecordMsg = new BsMerContractRecordMsg();
                merContractRecordMsg.setOrderNo(merContractRecord.getOrderNo());
                merContractRecordMsg.setType(1);
                merContractRecordMsg.setResponseCode(merContractRecord.getStatus().equals(2)?"SUCCESS":"REJECT");
                merContractRecordMsg.setResponseContent(reqBody);
                merContractRecordMsg.setResponseMsg(respData.getString("suggestion"));
                merContractRecordMsgService.insertRecordMsg(merContractRecordMsg);

                // 查询商户
                BsMer mer = merService.getMer(merContractRecord.getMerId());
                if (mer != null) {
                    if (merContractRecord.getStatus().equals(2)) {
                        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);
                        }

                        BsMerPlatformNo merPlatformNo = merPlatformNoService.getPlatformNo(mer.getId(), PlatformTypeEnum.type5, MerPlatformNoStatusEnum.status2);
                        if (merPlatformNo != null) {
                            merPlatformNo.setStatus(MerPlatformNoStatusEnum.status1.getNumber());
                            merPlatformNoService.editMerPlatformNo(merPlatformNo);
                        }
                        JSONArray repoInfoArray = respData.getJSONArray("repoInfo");
                        for (Object obj : repoInfoArray) {
                            JSONObject repoInfo = (JSONObject) obj;
                            BsMerPlatformTerm merPlatformTerm = new BsMerPlatformTerm();
                            merPlatformTerm.setMerPlatformNoId(merPlatformNo.getId());
                            merPlatformTerm.setMerId(merPlatformNo.getMerId());
                            merPlatformTerm.setBusiTypeCode(repoInfo.getString("childNoType"));
                            merPlatformTerm.setBusiTypeName(repoInfo.getString("childNoType"));
                            merPlatformTerm.setShopId(repoInfo.getString("channelId"));
                            merPlatformTerm.setTermNo(repoInfo.getString("childNo"));
                            merPlatformTermService.editMerPlatformTerm(merPlatformTerm);
                        }

                        // 签署协议
                        tianQueMerElecSignService.openElecSignature(respData.getString("mno"));

                    } else {
                        if (mer.getMerStatus().intValue() != MerStatusEnum.status1.getNumber().intValue()) {
                            mer.setMerStatus(MerStatusEnum.status4.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.status4.getNumber());
                            storeService.editStore(store);
                        }

                        BsMerPlatformNo merPlatformNo = merPlatformNoService.getPlatformNo(mer.getId(), PlatformTypeEnum.type5,MerPlatformNoStatusEnum.status2);
                        if (merPlatformNo != null) {
                            merPlatformNo.setStatus(MerPlatformNoStatusEnum.status3.getNumber());
                            merPlatformNo.setSuggestionReject(respData.getString("suggestion"));
                            merPlatformNoService.editMerPlatformNo(merPlatformNo);
                        }
                   }
                }
            }

        } catch (Exception e) {

        } finally {
            try {
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
                JSONObject result = new JSONObject();
                result.put("code", "success");
                result.put("msg", "成功");
                out.write(result.toJSONString().getBytes());
                out.flush();
                out.close();
            } catch (Exception e) {

            }
        }

    }

}
