package com.yihu.wlyy.web.wx;

import com.yihu.wlyy.entity.charge.WlyyCharge;
import com.yihu.wlyy.service.weixin.wxpay.model.BindCard;
import com.yihu.wlyy.service.weixin.wxpay.model.Charge;
import com.yihu.wlyy.service.weixin.wxpay.service.OnePayService;
import com.yihu.wlyy.web.WeixinBaseController;
import com.ylzinfo.onepay.sdk.OnepayDefaultClient;
import com.ylzinfo.onepay.sdk.exception.PayException;
import com.ylzinfo.onepay.sdk.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hzp on 2017/05/23.
 */
@Controller
@RequestMapping(value = "/onepay", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "统一支付服务")
public class OnePayController extends WeixinBaseController {

    @Autowired
    private OnePayService pay;


    @RequestMapping(value = "bindCard", method = RequestMethod.POST)
    @ApiOperation("查询绑卡信息")
    @ResponseBody
    public String bindCard() throws Exception {
        try {
            BindCard bindCard = pay.bindCard("915cc456-5b1d-11e6-8344-fa163e8aee56","o4Ma2t5665rS7uNfA9EF-VnOJx30");         //ohNH9sh4uwuJCxIwcLJtGTX-BaSk  //o4Ma2t5665rS7uNfA9EF-VnOJx30      getUID()getOpenid()
            return write(200, "查询绑卡信息成功！","data",bindCard);
        }
        catch (Exception e)
        {
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "charge", method = RequestMethod.POST)
    @ApiOperation("家庭医生签约支付")
    @ResponseBody
    public String charge(
                         @ApiParam(name="orgCode",value="医疗机构编号",defaultValue = "3502050300")
                         @RequestParam String orgCode,
                         @ApiParam(name="chargeType",value="支付类型",defaultValue = "1")
                         @RequestParam String chargeType,
                         @ApiParam(name="chargeRelation",value="支付关联代码",defaultValue = "044701ea5b2311e68344fa163e8aee56")
                         @RequestParam String chargeRelation,
                         @ApiParam(name="totalAmount",value="交易总金额（分）",defaultValue = "1")
                         @RequestParam Integer totalAmount,
                         @ApiParam(name="selfpayAmount",value="自费金额（分）",defaultValue = "0")
                         @RequestParam Integer selfpayAmount,
                         @ApiParam(name="insuranceAmount",value="医保支付金额（分）",defaultValue = "1")
                         @RequestParam Integer insuranceAmount,
                         @ApiParam(name="feeDetail",value="费用明细",defaultValue = "[{\"itemName\":\"家庭医生签约支付\",\"itemDesc\":\"家庭医生签约支付\",\"itemOrigPrice\":\"1\",\"itemNowPrice\":\"1\",\"itemNum\":\"1\",\"itemTotalAmt\":\"1\"}]")
                         @RequestParam String feeDetail) throws Exception {
        try {
            String settleNo = pay.charge(orgCode,chargeType,chargeRelation,totalAmount, selfpayAmount, insuranceAmount, feeDetail,"915cc456-5b1d-11e6-8344-fa163e8aee56","o4Ma2t5665rS7uNfA9EF-VnOJx30");  //ohNH9sh4uwuJCxIwcLJtGTX-BaSk    getUID(),getOpenid()
            return write(200, "家庭医生签约支付成功！","data",settleNo);
        }
        catch (Exception e)
        {
            return error(-1, e.getMessage());
        }
    }


    @RequestMapping(value = "chargeQuery", method = RequestMethod.POST)
    @ApiOperation("家庭医生签约支付查询")
    @ResponseBody
    public String chargeQuery(@ApiParam(name="code",value="支付流水号",defaultValue = "")
                               @RequestParam String code) throws Exception {
        try {
            Charge charge = pay.chargeQuery(code);
            return write(200, "家庭医生签约支付查询成功！","data",charge);
        }
        catch (Exception e)
        {
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "createSicard", method = RequestMethod.POST)
    @ApiOperation("生成电子社保卡")
    @ResponseBody
    public String createSicard() throws Exception {
        try {
            String sicardUrl = pay.createSicard("915cc456-5b1d-11e6-8344-fa163e8aee56","o4Ma2t5665rS7uNfA9EF-VnOJx30");         //ohNH9sh4uwuJCxIwcLJtGTX-BaSk  //o4Ma2t5665rS7uNfA9EF-VnOJx30  getUID(),getOpenid()
            return write(200, "生成电子社保卡成功！","data",sicardUrl);
        }
        catch (Exception e)
        {
            return error(-1, e.getMessage());
        }
    }


    @RequestMapping(value = "chargeList", method = RequestMethod.POST)
    @ApiOperation("获取某次签约的支付记录")
    @ResponseBody
    public String chargeList(@ApiParam(name="chargeType",value="支付类型",defaultValue = "1")
                                  @RequestParam String chargeType,
                                  @ApiParam(name="chargeRelation",value="支付关联代码",defaultValue = "044701ea5b2311e68344fa163e8aee56")
                                  @RequestParam String chargeRelation) throws Exception {
        try {
            List<WlyyCharge> charge = pay.chargeList(chargeType,chargeRelation);
            return write(200, "获取某次签约的支付记录成功！","data",charge);
        }
        catch (Exception e)
        {
            return error(-1, e.getMessage());
        }
    }



    @RequestMapping(value = "chargeListByPatient", method = RequestMethod.POST)
    @ApiOperation("获取患者的支付记录")
    @ResponseBody
    public String chargeListByPatient(@ApiParam(name="patient",value="患者代码",defaultValue = "")
                             @RequestParam String patient,
                             @ApiParam(name="page",value="第几页,从1开始",defaultValue = "1")
                             @RequestParam Integer page,
                             @ApiParam(name="size",value="每页几行",defaultValue = "10")
                             @RequestParam Integer size) throws Exception {
        try {
            List<WlyyCharge> charge = pay.chargeListByPatient(patient,page,size);
            return write(200, "获取患者的支付记录成功！","data",charge);
        }
        catch (Exception e)
        {
            return error(-1, e.getMessage());
        }
    }










    /**
     * 解析URL参数串
     * @param formContext
     * @param wordFirstsplitRegex
     * @param wordSecondsplitRegex
     * @return
     */
    private static Map<String, String> resolveFormContext(String formContext, String wordFirstsplitRegex, String wordSecondsplitRegex) {
        if (StringUtil.isEmpty(formContext)) {
            return null;
        }
        Map<String, String> targetMap = new HashMap<String, String>();
        String[] wordSeconds = formContext.split(wordSecondsplitRegex);
        for (String wordSecond : wordSeconds) {
            if (StringUtil.isEmpty(wordSecond)) {
                continue;
            }

            int idx = wordSecond.indexOf(wordFirstsplitRegex);
            targetMap.put(wordSecond.substring(0, idx), wordSecond.substring(idx + 1, wordSecond.length()));
        }
        return targetMap;
    }

    /**
     * 转换URL参数中为Map
     * @param reqQueryString
     * @return
     * @throws PayException
     */
    private Map<String, String> getRequestMap(String reqQueryString) throws PayException {
        if (StringUtil.isEmpty(reqQueryString)) {
            throw new PayException("跳转参数为空");
        }

        Map<String, String> targetMap = null;

        try {
            reqQueryString = URLDecoder.decode(reqQueryString, "utf-8");
            targetMap = resolveFormContext(reqQueryString, "=", "&");
        } catch (Exception e) {
            throw new PayException("跳转参数处理异常," + reqQueryString);
        }
        return targetMap;
    }

    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    @ApiOperation("商户页面跳转(模拟测试)")
    public void testReturnUrl(HttpServletRequest request, HttpServletResponse response) throws IOException, PayException {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("返回结果:\n" + request.getQueryString() +"\n");

        String onepayUrl = request.getParameter("onepayUrl");
        String appId = "1BHEOI11C00J7B2CA8C0000071FA53E1";
        String appSecret = "1BHEOH8HB0006E0A0A0A00002DB28BC5";
        String signType = "MD5";
        String encryptType = "DES";

        try {
            OnepayDefaultClient client = new OnepayDefaultClient(onepayUrl, appId, appSecret, signType, encryptType);
            Map<String, String> returnParams = getRequestMap(request.getQueryString());
            /*boolean isVerify = client.verifyReturnSign(returnParams, returnParams.get("sign"));
            if (isVerify) {
                response.getWriter().write("签名结果:\nSIGN SUCCESS.\n");
                // TODO 继续处理业务
                //		如：查询显示订单信息
            } else {
                response.getWriter().write("签名结果:\nSIGN ERROR !!!\n");
            }*/
        } catch (Exception e) {
            response.getWriter().write(e.getMessage());
        }
    }
}
