package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.pay.util.XmlUtil;
import com.hai.common.pay.util.sdk.WXPayConstants;
import com.hai.common.utils.HttpsUtils;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.common.utils.WxUtils;
import com.hai.entity.HighMerchantTripartitePlatform;
import com.hai.model.ResponseData;
import com.hai.model.WxSharingReceiversVO;
import com.hai.service.HighMerchantTripartitePlatformService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;

@Controller
@RequestMapping(value = "/merchantTripartitePlatform")
@Api(value = "商户第三方平台")
public class HighMerchantTripartitePlatformController {

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

    @Resource
    private HighMerchantTripartitePlatformService tripartitePlatformService;

    @RequestMapping(value="/editTripartitePlatform",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑第三方平台")
    public ResponseData editTripartitePlatform(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || body.getLong("merId") == null
                    || body.getInteger("platformType") == null
                    || StringUtils.isBlank(body.getString("platformMerName"))
                    || StringUtils.isBlank(body.getString("platformMerNumber"))
                    || body.getBoolean("profitSharingStatus") == null
            ) {
                log.error("HighMerchantController -> insertMerchantStore() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            if (body.getBoolean("profitSharingStatus") == true &&
                    (body.getBigDecimal("profitSharingRatio") == null ||
                            StringUtils.isBlank(body.getString("profitSharingReceiversNumber")) ||
                            StringUtils.isBlank(body.getString("profitSharingReceiversName")))) {
                log.error("HighMerchantController -> insertMerchantStore() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            HighMerchantTripartitePlatform platform = tripartitePlatformService.getDetail(body.getLong("merId"), body.getInteger("platformType"));
            if (platform == null) {
                platform = new HighMerchantTripartitePlatform();
            }
            platform.setMerId(body.getLong("merId"));
            platform.setPlatformType(body.getInteger("platformType"));
            platform.setPlatformMerName(body.getString("platformMerName"));
            platform.setPlatformMerNumber(body.getString("platformMerNumber"));
            platform.setProfitSharingStatus(body.getBoolean("profitSharingStatus"));
            platform.setProfitSharingRatio(body.getBigDecimal("profitSharingRatio"));
            platform.setProfitSharingReceiversNumber(body.getString("profitSharingReceiversNumber"));
            platform.setProfitSharingReceiversName(body.getString("profitSharingReceiversName"));

            // 微信平台 增加分账关系
            if (platform.getPlatformType().equals(1) && platform.getProfitSharingStatus().equals(true)) {
                WxSharingReceiversVO receiversVO = new WxSharingReceiversVO();
                receiversVO.setAccount(platform.getProfitSharingReceiversNumber());
                receiversVO.setType("MERCHANT_ID");
                receiversVO.setName(platform.getProfitSharingReceiversName());
                receiversVO.setRelation_type("SERVICE_PROVIDER");

                Map<String , String> map = new HashMap<>();
                map.put("mch_id" , "1289663601");     // 服务商
                map.put("sub_mch_id" , platform.getPlatformMerNumber());
                map.put("appid" , "wxa075e8509802f826");
                map.put("nonce_str" , WxUtils.makeNonStr());
                map.put("sign_type" , "HMAC-SHA256");
                map.put("receiver" , JSONObject.toJSONString(receiversVO));
                String sign = WxUtils.generateSignature(map, "Skufk5oi85wDFGl888i6wsRSTkdd5df5" , WXPayConstants.SignType.HMACSHA256);
                map.put("sign" , sign);
                String notifyXml = HttpsUtils.postData("https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver", WxUtils.mapToXml(map));
                SortedMap<String, String> postData = XmlUtil.parseXmlToTreeMap(notifyXml, "UTF-8");
                if (!postData.get("result_code").equals("SUCCESS")) {
                    log.error("HighMerchantController -> editTripartitePlatform() error!", postData.get("err_code_des"));
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, postData.get("err_code_des"));
                }
            }
            tripartitePlatformService.editDate(platform);

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

        } catch (Exception e) {
            log.error("HighMerchantTripartitePlatformController -> editTripartitePlatform() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询详情")
    public ResponseData getDetail(@RequestParam(value = "merId" , required = true) Long merId,
                                  @RequestParam(value = "platformType" , required = true) Integer platformType,
                                  HttpServletRequest request) {
        try {

            return ResponseMsgUtil.success(tripartitePlatformService.getDetail(merId, platformType));

        } catch (Exception e) {
            log.error("HighMerchantTripartitePlatformController -> getDetail() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }
}
