package com.bcxin.ins.coninsweb.order.controller.api.afr;

import com.bcxin.ins.third.gzx.huatai.HtPolicyService;
import com.bcxin.ins.service.order.InsInsuranceSlipAPIService;
import com.bcxin.ins.service.order.InsTransactionAPIService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.service.product.ProductService;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.entity.policy_core.InsInsuranceSlip;
import com.bcxin.ins.entity.policy_core.InsTransaction;
import com.bcxin.ins.util.Constant;
import com.bcxin.ins.util.DateUtil;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.util.MD5Util;
import com.bcxin.ins.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 交易流程处理
 */
@Controller
@RequestMapping("/api/afr/pay")
public class PolicyAFRTransactionController extends BaseController {

    @Autowired
    private HtPolicyService htPolicyService;

    @Autowired
    private PolicyService policyService;

    @Autowired
    private InsInsuranceSlipAPIService insInsuranceSlipService;

    @Autowired
    private ProductService productService;

    @Autowired
    private InsTransactionAPIService transactionService;

    @Autowired
    private InsInsuranceSlipAPIService insInsuranceSlipAPIService;


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


    /**
     * <b>保单支付失败的处理 </b>
     * tradeNumber  我们系统的 订单id
     * <b>
     */
    @RequestMapping("/payFaid")
    public ModelAndView payFaid(String tradeNumber) throws IOException {
        return getPayPage(tradeNumber);
    }

    /**
     * <b>保单支付成功的处理 </b>
     *  tradeNumber  我们系统的 订单id
     * <b>
     */
    @RequestMapping("/paySuccess")
    public ModelAndView paySuccess(String tradeNumber)  {
        ModelAndView view = new ModelAndView("/coninsweb/api/afr/transaction/pay_fail_noauto");
        view.addObject("tradeNumber",tradeNumber);
        try{
            return getPayPage(tradeNumber);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return view;
    }

    private ModelAndView getPayPage(String tradeNumber) {
        ModelAndView view = new ModelAndView("/coninsweb/api/afr/transaction/pay_fail_noauto");
        view.addObject("tradeNumber",tradeNumber);
        //支付失败
        InsInsuranceSlip insInsuranceSlip = insInsuranceSlipService.getInsOrderForm(Long.parseLong(tradeNumber));
        List<InsTransaction> insTransactionList = transactionService.selectInsTransactionByInsOrderForm(insInsuranceSlip.getIns_insurance_slip_id());
        InsTransaction transaction = null;
        if(insTransactionList.size()>0){
            transaction=insTransactionList.get(0);
        }
        // 判断是否已经支付
        if(transaction!=null){
            if (DictConst.PAY_STATUS_YZF.equals(transaction.getTransaction_status())) {
                view.setViewName("/coninsweb/api/afr/transaction/pay_success_noauto");
                OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(tradeNumber));
                view.addObject("tradeNumber",tradeNumber);
                view.addObject("payAmount", insInsuranceSlip.getPremium());
                view.addObject("orderNo", transaction.getPay_order_number());
                view.addObject("productName",dto.getProduct_name());
                view.addObject("policyURL", insInsuranceSlip.getInsure_path());
                view.addObject("policyNo", insInsuranceSlip.getIns_insurance_slip_id());
            } /*else {
//            InsurancePolicy policy = policyService.findPolicyByTransaction(transaction);
//            view.addObject("policy", policy);
//            view.addObject("product", policy.getInsuranceProduct());
            }*/
        }
        setTokenByApi(view);
        return view;
    }

    /**
     * <b>获取下载保单的URL </b>
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     * @author zhouzhipeng
     * @date 2017年1月10日 上午11:06:12
     * @注意事项 </b>
     * <b>
     */
    @RequestMapping("saveFileToPDF")
    public ResultDto saveFileToPDF(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String oid = request.getParameter("oid");
        // 订单详情
//        InsurancePolicy policy = policyService.findPolicyByOid(Long.valueOf(oid));
          return null;
        //return new ResultDto(policy.getPolicyURL(), "");
    }



    /**
     * ----orderNo
     * 跳到华泰支付页面
     *
     * @param orderNo
     * @return
     */
    @RequestMapping("/ht/{orderNo}")
    public ModelAndView payHtPage(@PathVariable String orderNo, ModelMap model, HttpServletResponse response) {


        ModelAndView view = new ModelAndView("/coninsweb/api/afr/transaction/pay_zhifubao");
        try {
            //根据订单号查询 保险单据的信息
            OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(orderNo));
            InsInsuranceSlip insInsuranceSlip = insInsuranceSlipService.selectById(orderNo);
            PolicyTransactionVo pvo = new PolicyTransactionVo();
            pvo.setPay_amount(new BigDecimal(dto.getGross_premium()));
            pvo.setStart_time(new Date());
            pvo.setPayment_method(Constant.PAYMETHOND_ONE);//一次性缴费
            pvo.setPolicy_id(orderNo);
            pvo.setPay_type(DictConst.PAY_TYPE_ZFB);//
            pvo.setDeal_url(GlobalResources.WEB_PRO_URL + "/api/afr/pay/ht/" + orderNo);
            pvo.setUser_id(insInsuranceSlip.getRegister_user_id());
            policyService.saveTransaction(pvo);
            SpecialPublicDutyVo vo = policyService.accordingToOrderIDToGetSpecialPublicDutyVo(insInsuranceSlip.getIns_insurance_slip_id());
            String result = htPolicyService.htPay(response, insInsuranceSlip, vo.getRoleSubjectList().get(0));
            view.addObject("payinfo", result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        setTokenByApi(view);

        return view;
    }


    /**
     * 回调地址
     * @param request
     * @param model
     * @param response
     */
    @RequestMapping("/ht/callback/back")
    public void callbackBack(HttpServletRequest request, ModelMap model, HttpServletResponse response) {

        log.info("回调后台");
        String orderNo = request.getParameter("orderNo");
        String status = request.getParameter("payStatus");
//        String transSign = request.getParameter("transSign");
        String transactionNo = request.getParameter("transactionNo");
        log.info("华泰支付状态status" + status);
        //验证一下密钥是否正确
        String channel = GlobalResources.HT_CHANNELCODE;
        String sign = MD5Util.string2MD5(channel + DateUtil.getCurrentDate());

        if (status.equals("1")) {
            // 这边需要验证一下密钥是否正确
            policyService.HTTP_HT_GZX_HBCB(orderNo,transactionNo);
        }

    }

    @RequestMapping("/ht/callback/front")
    public ModelAndView callbackFront(HttpServletRequest request, ModelMap model, HttpServletResponse response) {
        //投保单里面  trade_serial_number   ==orderNo3   874828134044790784
        //交易表  trade_serial_number    2017061421001004300285766833
//http://localhost:8080/pay/ht/callback/front?payStatus=1&orderNo=874828134044790784&transactionNo=2017061421001004300285766833&transSign=9602df417147053892caeffdabdfce2c
        ModelAndView view = new ModelAndView("/coninsweb/api/afr/transaction/pay_fail");
//        view = new ModelAndView("/coninsweb/api/afr/transaction/pay_fail");pay_success
        log.info("回调前台");
        log.info("回调前台");
        String orderNo = request.getParameter("orderNo");
        String status = request.getParameter("payStatus");
//        String transSign = request.getParameter("transSign");
        String transactionNo = request.getParameter("transactionNo");
        log.info("华泰支付状态status" + status);
        log.info("华泰支付状态status" + status);
        //验证一下密钥是否正确
        String channel = GlobalResources.HT_CHANNELCODE;
        String sign = MD5Util.string2MD5(channel + DateUtil.getCurrentDate());
    // TODO: 2017/06/30 0030   这边对接的时候要注意 自己系统 返回iframe  别的系统只返回一些参数
        if (status.equals("1")) {
            view.setViewName("/coninsweb/api/afr/transaction/pay_success");
            // 这边需要验证一下密钥是否正确
            policyService.HTTP_HT_GZX_HBCB(orderNo,transactionNo);
            OrderFormVo dto = insInsuranceSlipService.getOrderFormVoByTradeSerialNumber(orderNo);
            view.addObject(ConstProp.DTO,dto);
        }
        setTokenByApi(view);
        return view;
    }

    /**
     * 公责险回调地址
     * @param oid 订单id
     * @param request
     * @return
     * @throws Exception
     */
    /*@RequestMapping("/syntony-service/{oid}")
    public ModelAndView syntonyService(@PathVariable("oid") String oid,HttpServletRequest request) {
        logger.info("公责险承保完成后页面展示-star");
        ClientUserVo userdetail = UserSupportUtil.getSessionUser();
        if (  userdetail == null ) {
            return new ModelAndView("redirect:/");
        }
        logger.info("公责险承保完成后页面展示-syntony-service：oid:"+oid);
        ModelAndView view = new ModelAndView("/coninsweb/api/lote/transaction/finishPay");
        if(com.bcxin.mybatisplus.toolkit.StringUtils.isNotEmpty(oid)){
            OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
            ProductVo pd = productService.getProduct(Long.parseLong(dto.getProduct_oid()));
            view.addObject(ConstProp.PD,pd);
            view.addObject(ConstProp.DTO,dto);
            logger.info("公责险承保完成后页面展示-OrderFormVo："+dto.toString());
        }
        view.addObject("oid",oid);
        logger.info("公责险承保完成后页面展示-end");
        return view;
    }*/

}
