package com.chinacreator.video.restful.service;

import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.mapper.CommConfDao;
import com.chinacreator.video.mapper.DictionaryDao;
import com.chinacreator.video.mapper.PayConverDao;
import com.chinacreator.video.service.CommonService;
import com.chinacreator.video.util.HttpUtils;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.TripleDES;
import com.chinacreator.video.validate.*;
import net.sf.json.JSONObject;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付转换服务类
 *
 * @author zhengrong.yan
 * @date 202105008
 */
@Component
public class PayConverService {

    @Autowired
    private ChannelValidate channelValidate;

    @Autowired
    private IpValidate ipValidate;

    @Autowired
    private MobValidate mobValidate;

    @Autowired
    private TimetampValidate timetampValidate;

    @Autowired
    private SignValidate signValidate;

    @Autowired
    private ParamValidate paramValidate;

    @Autowired
    private CommConfDao commConfDao;

    @Autowired
    private CommonService commonService;

    @Autowired
    private PayConverDao payConverDao;

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private ChannelDao channelDao;

    private static Logger logger = Logger.getLogger(PayConverService.class);

    private static Logger log = Logger.getLogger("payconver");

    public void busiCheck(OrderInfo orderInfo) throws Exception {
        //timetamp验证
        timetampValidate.validate(orderInfo.getTimestamp());
        //渠道验证
        channelValidate.validate(orderInfo.getChannel());
        //ip验证
        ipValidate.volidate(orderInfo);
        //签名验证
        signValidate(orderInfo);
        //手机号码验证
        mobValidate.validate(orderInfo);
        //并发访问控制
        vistVali(orderInfo);
    }

    /**
     * 拼接签名信息 orderid+channel+timestamp
     *
     * @param
     * @return
     */
    public String getSign(OrderInfo orderInfo) throws Exception {
        StringBuilder strb = new StringBuilder();
        String userid = orderInfo.getUserid();
        strb.append(userid);
        strb.append(orderInfo.getCpid());
        strb.append(orderInfo.getSpid());
        strb.append(orderInfo.getChannel());
        strb.append(orderInfo.getTimestamp());
        return strb.toString();
    }

    /**
     * 签名验证
     *
     * @param
     * @throws Exception
     */
    public void signValidate(OrderInfo orderInfo) throws Exception {
        String lcalsign = getSign(orderInfo);
        String channel = orderInfo.getChannel();
        lcalsign += channelDao.queryChannel(channel).getPassword();
        System.out.println("local-->" + lcalsign);
        lcalsign = MD5.MD5Encode(lcalsign);
        System.out.println("orderinfo==>" + orderInfo.getSignature());
        System.out.println("lcalsign===>" + lcalsign);
        if (!lcalsign.equals(orderInfo.getSignature())) {
            throw new BussinessException("10006", "签名校验失败");
        }
    }

    /**
     * 业务处理
     *
     * @param orderInfo
     */
    public String busiOper(OrderInfo orderInfo) throws Exception {
        String resultcode = "0";
        String resultinfo = "";
        String jsonParams = "";
        String retrunurl = "";
        HashMap map = new HashMap();
        try {
            String cpid ="";
            String spid = "";
            String password = dictionaryDao.getValue("payconverPwd");
            String userid = orderInfo.getUserid();
            Map parm = payConverDao.getConverParm(orderInfo.getSpid());
            if(parm!=null && parm.size()>0) {
                cpid = (String)parm.get("CONVERCPID");
                spid = (String)parm.get("CONVERSPID");
            }else{
                /*添加到表*/
                map.put("id", payConverDao.getNo());
                map.put("userid", userid);
                map.put("cpid", orderInfo.getCpid());
                map.put("spid", orderInfo.getSpid());
                map.put("request",jsonParams);
                payConverDao.addPayConverRec(map);
                /**end**/
                throw new BussinessException("8009", "该产品表支付转换表中未配置！");
            }

            String mobile = TripleDES.encrypt(userid,password);

            String timestamp = System.currentTimeMillis() + "";;
            String signature = MD5.MD5Encode(spid + cpid + mobile + timestamp+password);


            //调接口
            String url = dictionaryDao.getValue("payconverUrl");
            JSONObject json = new JSONObject();
            json.put("mobile", mobile);
            json.put("cpid", cpid);
            json.put("spid", spid);
            json.put("timestamp", timestamp);
            json.put("signature", signature);
            jsonParams = json.toString();
            System.out.println(jsonParams);

            /*添加到表*/
            map.put("id", payConverDao.getNo());
            map.put("userid", userid);
            map.put("cpid", orderInfo.getCpid());
            map.put("spid", orderInfo.getSpid());
            map.put("request",jsonParams);
            payConverDao.addPayConverRec(map);
            /**end**/

            String result = HttpUtils.post(url, json);
            log.info(url);
            log.info(jsonParams);
            log.info(result);
            if(!"".equals(result) && result!=null) {
                JSONObject resjson = JSONObject.fromObject(result);
                resultcode = resjson.get("code") == null ? "" : resjson.get("code").toString();
                resultinfo = resjson.get("message") == null ? "" : resjson.get("message").toString();
                if ("0".equals(resultcode)) {
                    JSONObject jsonObject = resjson.getJSONObject("data");
                    if(jsonObject!=null) {
                        retrunurl = jsonObject.get("url") == null ? "" : jsonObject.getString("url");
                    }
                } else {
                    throw new BussinessException(resultcode, resultinfo);
                }
            }else{
                throw new BussinessException("8000", "解析json出错");
            }
            return retrunurl;
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                resultinfo = ((BussinessException) e).getMessage();
            } else {
                resultcode = "8000";
                resultinfo = "出现异常，" + e.toString();
            }
            throw e;
        }finally {
            //更新表
            map.put("resultcode", resultcode);
            map.put("resultinfo", resultinfo.length()>4000?resultinfo.substring(0,2000):resultinfo);
            map.put("returnurl", retrunurl);
            payConverDao.upPayConverRec(map);
        }
    }


    /**
     * 验证访问限制，1分钟内同一业务只能办理一次
     *
     * @param orderInfo
     * @throws Exception
     */
    private void vistVali(OrderInfo orderInfo) throws Exception {
        String[] params = new String[3];
        params[0] = orderInfo.getChannel();
        params[1] = orderInfo.getUserid();
        params[2] = orderInfo.getSpid();
        if (commonService.vistVali2(params, "payconver")) {
            throw new BussinessException("8001", "指定时间内重复请求");
        }
    }
}
