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.HighGasChannelConfig;
import com.hai.entity.HighMerchantTripartitePlatform;
import com.hai.enum_type.GasChannel;
import com.hai.enum_type.GasChannelPayPlatformType;
import com.hai.model.ResponseData;
import com.hai.model.WxSharingReceiversVO;
import com.hai.service.HighGasChannelConfigService;
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 = "/gasChannelConfig")
@Api(value = "加油站渠道商配置")
public class HighGasChannelConfigController {

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

    @Resource
    private HighGasChannelConfigService gasChannelConfigService;

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

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

            // 查询平台
            HighGasChannelConfig platform = gasChannelConfigService.getConfig(
                    GasChannel.getChannelByType(body.getInteger("channelId")),
                    GasChannelPayPlatformType.getPlatformByType(body.getInteger("payPlatformType")));

            if (platform == null) {
                platform = new HighGasChannelConfig();
            }
            platform.setChannelId(body.getInteger("channelId"));
            platform.setChannelName(GasChannel.getChannelByType(body.getInteger("channelId")).getName());
            platform.setPayPlatformType(body.getInteger("payPlatformType"));
            platform.setPayPlatformMerName(body.getString("payPlatformMerName"));
            platform.setPayPlatformMerNo(body.getString("payPlatformMerNo"));
            platform.setProfitSharingStatus(body.getBoolean("profitSharingStatus"));
            platform.setProfitSharingRatio(body.getBigDecimal("profitSharingRatio"));
            platform.setProfitSharingReceiversNo(body.getString("profitSharingReceiversNo"));
            platform.setProfitSharingReceiversName(body.getString("profitSharingReceiversName"));

            // 微信平台 增加分账关系
            if (platform.getPayPlatformType().equals(1) && platform.getProfitSharingStatus().equals(true)) {
                WxSharingReceiversVO receiversVO = new WxSharingReceiversVO();
                receiversVO.setAccount(platform.getProfitSharingReceiversNo());
                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.getPayPlatformMerNo());
                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"));
                }
            }

            gasChannelConfigService.editConfig(platform);

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

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

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

            return ResponseMsgUtil.success(gasChannelConfigService.getConfig(GasChannel.getChannelByType(channelId), GasChannelPayPlatformType.getPlatformByType(payPlatformType)));

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