package com.ym.mec.collectfee.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ym.mec.collectfee.common.web.BaseController;
import com.ym.mec.collectfee.entity.*;
import com.ym.mec.collectfee.service.*;
import com.ym.mec.collectfee.utils.GenerateNum;
import com.ym.mec.collectfee.utils.yqpay.Intfc;
import com.ym.mec.collectfee.utils.yqpay.Msg;
import com.ym.mec.collectfee.utils.yqpay.NotifyMsg;
import com.ym.mec.collectfee.utils.yqpay.YqPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

//@Api("支付")
@Slf4j
@RestController
@RequestMapping("yqpay")
@EnableScheduling   // 2.开启定时任务
public class YqPayController extends BaseController {

    @Autowired
    private YqPayService yqPayService;
    @Autowired
    private YqQueryService yqQueryService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private CourseGroupInfoService CourseGroupInfoService;

    @Autowired
    private ApplyInfoService applyInfoService;

    @Autowired
    private RenewalsService renewalsService;
    @Autowired
    private SchoolService schoolService;


    /**
     * 统一下单(乐团缴费)
     *
     * @return String
     * @throws Exception
     */
//    @ApiOperation(value = "提交支付", notes = "易乾支付统一下单")
    @PostMapping("/toPay")
    @Transactional
    public Object toPay(@ModelAttribute @Validated Order order) throws Exception {
        BigDecimal amount = new BigDecimal("0");
        //1、判断已报名人数
        CourseGroupInfo courseGroupInfo = CourseGroupInfoService.get(order.getCourseId());
        if (courseGroupInfo.getRegNum() >= courseGroupInfo.getPlanNum()) {
            return failed("乐团人数暂时已满，请稍后再试");
        }

        //课程组价格
        BigDecimal courseFee = courseGroupInfo.getFeeAmount();
        amount = amount.add(courseFee);

        ClassPathResource classPathResource = new ClassPathResource("instruments.json");

        BigDecimal instrumentPrice = new BigDecimal("0");//乐器价格
        String instrumentName = "";//乐器名称

        //获取乐器的价格
        String instrumentId = order.getInstrument();
        String jsonString = IOUtils.toString(new InputStreamReader(classPathResource.getInputStream(), "UTF-8"));
        Instrument instrument = JSONObject.parseObject(jsonString, Instrument.class);

        if (order.getInstrument() != null && !order.getInstrument().isEmpty()) {
            instrumentPrice = new BigDecimal(instrument.getInstruments().get(instrumentId).get("referencePrice"));
            instrumentName = (String) instrument.getInstruments().get(instrumentId).get("index") + "-" +
                    (String) instrument.getInstruments().get(instrumentId).get("name");
        }

        //2 版本为3.0（ 26），不收乐器费用，收押金800放乐器费用
        if (courseGroupInfo.getFeeType().equals(26)) {
            instrumentPrice = new BigDecimal("800");
        }
        amount = amount.add(instrumentPrice);

        //辅件价格
        String adjunctIds = order.getAdjunct();
        BigDecimal adjunctPrice = new BigDecimal("0");//辅件价格
        String adjunctName = "";//辅件名称
        if (adjunctIds != null && !adjunctIds.isEmpty()) {
            String[] adjunctIdArr = adjunctIds.split(",");
            for (String adjunctId : adjunctIdArr) {
                adjunctPrice = adjunctPrice.add(new BigDecimal(instrument.getAuxiliaries().get(adjunctId).get("referencePrice")));
                adjunctName += (String) instrument.getAuxiliaries().get(adjunctId).get("name") + "|";
            }
        }

        amount = amount.add(adjunctPrice);
        order.setGroupId(courseGroupInfo.getId());
        order.setAmount(amount);
        order.setRemark(instrumentName);
        order.setTuiFee(courseFee);
        order.setGoodsFee(instrumentPrice);
        order.setSdName(adjunctName + "教材|琴谱");
        order.setSdFee(adjunctPrice);


        School school = schoolService.get(order.getClassId());
        String notifyUrl = "http://47.99.212.176:9000/yqpay/notify"; //异步通知地址
        String returnUrl = "http://pay.dayaedu.com/#/login?schoolId=" + school.getSchoolId() + "&classId=" + order.getClassId() + "&cityId=" + school.getCityId();//支付后返回页面
        String payUrl = "https://qyfapi.95epay.com/api/api/hPay/toPayHtml";//支付跳转页
        String payChannels = "{\"weChatPay\":true,\"weChatPayMobile\":false,\"aliPay\":true,\"fastpayXy\":true,\"aliPayMobile\":false,\"balancePay\":false}";//支付方式配置

        String orderNo = GenerateNum.getInstance().GenerateOrderNo(); //自己系统订单号
        order.setOrderNo(orderNo);
        order.setCreateTime(new Date()); //订单提交时间
        order.setStatus(1); //订单状态

        //获取支付成功跟支付中的订单数
        int branchId = order.getBranchId();
        int payOrderNums = orderService.getPayOrderNums();
        //分佣账户（1、每10笔，前四笔收入私户 2、私户每个商户最多收款400万）
        if ((payOrderNums + 1) % 10 <= 4) { //私人账户
            branchId = 0;
        }

        //获取分佣账户
        Account account = accountService.getAccountByBranchId(branchId);
        if (account == null) {
            return failed("机构没有设置收款账户");
        }
        String routingMerNo = account.getSellerNo();
        BigDecimal HasRouting = account.getHasRouting().add(order.getAmount());
        account.setHasRouting(HasRouting);

        Map<String, Object> routingList = new LinkedHashMap<String, Object>();
        routingList.put("routingMerNo", routingMerNo);//分佣账户
        routingList.put("routingFee", order.getAmount()); //分佣金额
        List<Map> tempRoutingList = new ArrayList();
        tempRoutingList.add(routingList);

        order.setUAccount(account.getId().toString());
        order.setAccount(routingMerNo);

        //1、插入订单
        orderService.insert(order);
        //2、修改已报名人数
        courseGroupInfo.setRegNum(courseGroupInfo.getRegNum() + 1);
        CourseGroupInfoService.upByIdAndVersion(courseGroupInfo);
        //3、修改分佣账户已收金额
        accountService.upByIdAndVersion(account);


        /*订单信息*/
        String orderBody = "大雅乐盟培训课程";
        /*订单标题*/
        String orderSubject = "培训订单";


        order.setAmount(new BigDecimal("2")); //测试设置金额

        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        resultMap.put("sellerNo", "0021677"); //收款商户号
        resultMap.put("payChannels", payChannels); //支付方式
        resultMap.put("orderBody", orderBody); //订单信息
        resultMap.put("payAmount", order.getAmount()); //支付金额
        resultMap.put("apiPayType", "1"); //*API支付类型1-即时支付,2-担保支付,3-预授权支付*/
        resultMap.put("tradeType", "0"); //*交易类型1—充值，0—收款*
        resultMap.put("merMerOrderNo", orderNo); //商户订单号
        resultMap.put("orderSubject", orderSubject); //订单标题
        resultMap.put("returnUrl", returnUrl); //前台页面地址
        resultMap.put("tempRoutingList", JSON.toJSONString(tempRoutingList));//分账设置
        Map rqMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        rqMap.put("host", payUrl);

        return succeed(rqMap);
    }


    /**
     * 续费支付
     *
     * @return String
     * @throws Exception
     */
//    @ApiOperation(value = "续费支付", notes = "续费支付")
    @PostMapping("/renewalsPay")

    public Object renewalsPay(@ModelAttribute @Validated Renewals renewals) throws Exception {
        MecUser mecUser = applyInfoService.findMecUser(renewals.getUserId());
        if (mecUser == null) {
            return failed("续费用户不存在");
        }
        renewals.setBranchId(mecUser.getBranchId());

        //课程组价格
        List<MecCourse> courses = applyInfoService.queryUserCourse(renewals.getUserId());//获取续费课程
        if (courses == null) {
            return failed("您没有续费的课程");
        }
        MecCourse mecCourse4json = JSON.parseObject(renewals.getCourses(), MecCourse.class);
        if (mecCourse4json == null) {
            return failed("请选择续费课程");
        }

        //classType 小课1 大课2
        Integer buyCount = mecCourse4json.getBuyCount();
        if (buyCount <= 0) {
            return failed("购买次数不能小于1");
        }
        BigDecimal amount = new BigDecimal("0"); //课程总价
        String remark = "";
        List<MecCourse> pickCourses = new ArrayList<>();
        for (int i = 0; i < courses.size(); i++) {
            MecCourse course = courses.get(i);
            if (mecCourse4json.getCourseId().equals(course.getCourseId().intValue())) {
                BigDecimal price = course.getClassType().equals(1) ? course.getPrice().multiply(BigDecimal.valueOf(buyCount)) : course.getPrice().multiply(BigDecimal.valueOf(course.getBuyCount()));
                amount = amount.add(price);
                remark += course.getClassName();
                if (course.getClassType().equals(1)) {
                    course.setBuyCount(buyCount);
                }
                pickCourses.add(course);
            }
        }
        if (pickCourses.size() == 0) {
            return failed("请选择续费课程");
        }

        School school = schoolService.get(pickCourses.get(0).getClassId());
        if (school == null) {
            return failed("报名学校不存在");
        }
        String notifyUrl = "http://47.99.212.176:9000/yqpay/notify"; //异步通知地址
        String returnUrl = "http://pay.dayaedu.com/#/login?schoolId=" + school.getId() + "&classId=" + pickCourses.get(0).getClassId() + "&cityId=" + school.getCityId();//支付后返回页面
        String payUrl = "https://qyfapi.95epay.com/api/api/hPay/toPayHtml";//支付跳转页
        String payChannels = "{\"weChatPay\":true,\"weChatPayMobile\":false,\"aliPay\":true,\"fastpayXy\":true,\"aliPayMobile\":false,\"balancePay\":false}";//支付方式配置

        String orderNo = GenerateNum.getInstance().GenerateOrderNo(); //自己系统订单号

        //获取支付成功跟支付中的订单数
        int branchId = renewals.getBranchId();
        int payOrderNums = orderService.getPayOrderNums();
        //分佣账户（1、每10笔，前四笔收入私户 2、私户每个商户最多收款400万）
        if ((payOrderNums + 1) % 10 <= 4) { //私人账户
            branchId = 0;
        }

        //获取分佣账户
        Account account = accountService.getAccountByBranchId(branchId);
        if (account == null) {
            return failed("机构没有设置收款账户");
        }
        String routingMerNo = account.getSellerNo();
        BigDecimal HasRouting = account.getHasRouting().add(amount);
        account.setHasRouting(HasRouting);

        Map<String, Object> routingList = new LinkedHashMap<String, Object>();
        routingList.put("routingMerNo", routingMerNo);//分佣账户
        routingList.put("routingFee", amount); //分佣金额
        List<Map> tempRoutingList = new ArrayList();
        tempRoutingList.add(routingList);

        renewalsService.addRenewalsOrder(renewals, amount, orderNo, pickCourses, routingMerNo, account.getId(), remark);

        /*订单信息*/
        String orderBody = "大雅乐盟培训课程";
        /*订单标题*/
        String orderSubject = "培训订单";

        //测试用
        amount = new BigDecimal("2");
        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        resultMap.put("sellerNo", "0021677"); //收款商户号
        resultMap.put("payChannels", payChannels); //支付方式
        resultMap.put("orderBody", orderBody); //订单信息
        resultMap.put("payAmount", amount); //支付金额
        resultMap.put("apiPayType", "1"); //*API支付类型1-即时支付,2-担保支付,3-预授权支付*/
        resultMap.put("tradeType", "0"); //*交易类型1—充值，0—收款*
        resultMap.put("merMerOrderNo", orderNo); //商户订单号
        resultMap.put("orderSubject", orderSubject); //订单标题
        resultMap.put("returnUrl", returnUrl); //前台页面地址
        resultMap.put("tempRoutingList", JSON.toJSONString(tempRoutingList));//分账设置
        Map rqMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        rqMap.put("host", payUrl);
        return succeed(rqMap);
    }

    /**
     * 交易查询
     *
     * @param merOrderNoList 用户订单号
     * @return
     * @throws Exception
     */
    //@PostMapping("/query")
    //@Scheduled(cron = "0/3 40 11 * * ?")
    public Object query(String merOrderNoList) throws Exception {
        String notifyUrl = ""; //回调地址
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("merOrderNoList", merOrderNoList);
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        return yqQueryService.orderQuery(requestMap);
    }

    /**
     * 用户信息(商户)查询
     *
     * @param sonMerNo 子商户号
     * @return
     * @throws Exception
     */
    @PostMapping("/queryaccount")
    public String queryAccount(String sonMerNo) throws Exception {
        String notifyUrl = ""; //回调地址
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("merOrderNoList", sonMerNo);
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        return yqQueryService.queryAccount(requestMap);
    }

    /**
     * 对账查询(定时任务每天对账)
     *
     * @return
     */
    public String queryBill() throws Exception {
        String notifyUrl = ""; //回调地址
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("tradeDate", ""); //交易日期
        resultMap.put("payState", ""); //订单状态
        resultMap.put("tradeType", ""); //交易类型,不填为全部
        resultMap.put("channelType", ""); //通道类型,不填为全部
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        return yqQueryService.billQuery(requestMap);
    }


    /**
     * 平台转账
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/platformtransferacc")
    public String platformTransferAcc() throws Exception {
        String notifyUrl = ""; //回调地址
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("payeeNo", ""); //收款方商户号
        resultMap.put("payeeName", ""); //收款方姓名
        resultMap.put("amount", ""); //金额
        resultMap.put("merOrderNo", ""); //商户订单号
        resultMap.put("remarks", ""); //备注
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        return yqPayService.platformTransferAcc(requestMap);
    }

    /**
     * 提现短信
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/sendsms")
    public Msg sendSms(@ModelAttribute Intfc intfc) throws Exception {
        String notifyUrl = ""; //回调地址
        String merMerOrderNo = GenerateNum.getInstance().GenerateOrderNo();
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("wdMerNo", intfc.getWdMerNo()); //提现商户号
        resultMap.put("merMerOrderNo", merMerOrderNo); //商户订单号
        resultMap.put("amount", intfc.getAmount()); //提现金额
        resultMap.put("cardNo", intfc.getCardNo()); //提现银行卡号
//        resultMap.put("phone", intfc.getPhone()); //预留手机号(选填)
//        resultMap.put("cardType", intfc.getCardType()); //卡类型 0-个人银行卡，1-企业银行卡。(选填)
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        return yqPayService.intfc(requestMap);
    }

    /**
     * 提现
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/intfc")
    public Msg intfc(@ModelAttribute Intfc intfc) throws Exception {
        String notifyUrl = "http://47.99.212.176:9000/yqpay/notify"; //回调地址
        String merMerOrderNo = GenerateNum.getInstance().GenerateOrderNo();
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("wdMerNo", intfc.getWdMerNo()); //提现商户号
        resultMap.put("merMerOrderNo", merMerOrderNo); //商户订单号
        resultMap.put("amount", intfc.getAmount()); //提现金额
        resultMap.put("cardNo", intfc.getCardNo()); //提现银行卡号
//        resultMap.put("phone", intfc.getPhone()); //预留手机号(选填)
//        resultMap.put("cardType", intfc.getCardType()); //卡类型 0-个人银行卡，1-企业银行卡。(选填)
        resultMap.put("seqNo", ""); //流水号(选填)
        resultMap.put("smsCode", ""); //验证码(选填)
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        return yqPayService.intfc(requestMap);
    }


    /**
     * 易乾异步通知接口
     *
     * @param msg
     * @return String
     * @throws Exception
     */
    @PostMapping("/notify")
    public Msg notify(@ModelAttribute Msg msg) throws Exception {
//        log.info(msg.toString());K
        Map<String, Object> rqMap = new LinkedHashMap<String, Object>();
        rqMap.put("code", msg.getCode());
        rqMap.put("msg", msg.getMsg());
        rqMap.put("responseType", msg.getResponseType());
        rqMap.put("responseParameters", msg.getResponseParameters());
        rqMap.put("sign", msg.getSign());
        boolean rs = YqPayUtil.verify(rqMap);
        msg.setCode("");
        msg.setMsg("fail");
        Order order = null;
        NotifyMsg notifyMsg = null;
        if (rs) {
            notifyMsg = JSON.parseObject(msg.getResponseParameters(), NotifyMsg.class);
            String merMerOrderNo = notifyMsg.getMerMerOrderNo(); //自己系统订单号
            order = orderService.getOrderByOrderNo(merMerOrderNo);
        }
        //支付中订单存在，更新状态
        if (order != null && msg.getResponseType().equals("1")) {
            //更新订单状态
            int status = msg.getCode().equals("88") ? 2 : 0;
            order.setStatus(status);
            if (order.getOrderNo().isEmpty()) {
                order.setPayId(notifyMsg.getOrderNo()); //更新易乾付订单号
            }
            if (status == 2) {
                order.setPay(notifyMsg.getPayAmount());
                order.setPayTime(new Date());
            }
            orderService.update(order);
            ApplyInfo applyInfo = applyInfoService.get(order.getUserId());
            applyInfoService.userRegister(applyInfo.getPatriarchPhone(), order.getId()); //推送mec

            msg.setCode("000000");
            msg.setMsg("success");
        }
        return msg;
    }


    @Scheduled(cron = "0/5 * * * * ?")
    //@RequestMapping("/getOrderStatus")
    public void getOrderStatus() throws Exception {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());

        List<Order> payingOrders = orderService.findPayingOrders();

        String merOrderNos = ""; //

        for (int i = 0; i < payingOrders.size(); i++) {
            merOrderNos += payingOrders.get(i).getOrderNo() + ",";
        }
        if (merOrderNos.isEmpty()) {
            return;
        }
        merOrderNos = merOrderNos.substring(0, merOrderNos.length() - 1);

        String notifyUrl = ""; //回调地址
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("merOrderNoList", merOrderNos);
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        Msg queryRs = yqQueryService.orderQuery(requestMap);
        if (queryRs.getCode().equals("88")) {
            //更新订单状态
            String[] statusArr = {"0", "1", "7"};
            String responseParameters = queryRs.getResponseParameters();
            List<Map<String, String>> responseList = JSON.parseObject(responseParameters, List.class);
            for (int i = 0; i < responseList.size(); i++) {
                Map<String, String> rpMap = responseList.get(i);
                if (Arrays.asList(statusArr).contains(rpMap.get("tradeState"))) {
                    this.updateOrder(rpMap);
                }
            }


        }
    }

    @Transactional
    public void updateOrder(Map<String, String> rpMap) {
        int status = rpMap.get("tradeState").equals("1") ? 2 : 0;
        Order order = orderService.getOrderByOrderNo(rpMap.get("merOrderNo"));
        order.setStatus(status);
        order.setBank(rpMap.get("channelType"));

        if (order.getPayId() == null) {
            order.setPayId(rpMap.get("orderNo")); //更新易乾付订单号
        }
        if (status == 2) {
            order.setPay(order.getAmount());
            order.setPayTime(new Date());
            //推送mec
            if (order.getTuiFee() != null) { //乐团报名
                ApplyInfo applyInfo = applyInfoService.get(order.getUserId());
                applyInfo.setStatus(1);
                applyInfoService.update(applyInfo);
                applyInfoService.userRegister(applyInfo.getPatriarchPhone(), order.getId()); //推送mec
            } else {
                Renewals renewals = renewalsService.getRenewalsByOrderId(order.getId());
                RenewBean renewBean = new RenewBean();
                renewBean.setUserId(renewals.getUserId());
                renewBean.setClassId(renewals.getClassId());
                renewBean.setWay(renewals.getWay());
                renewBean.setPay(renewals.getPay());
                renewBean.setChargeMode(renewals.getChangeMode());
                renewBean.setBuy(new BigDecimal(renewals.getBuy()));
                renewBean.setPrice(renewals.getPrice());
                applyInfoService.pushRenew(renewBean);
            }
        }
        //失败减去已收款金额，减去报名人数
        if (status == 0 && order.getTuiFee() != null) {
            CourseGroupInfo courseGroupInfo = CourseGroupInfoService.get(order.getGroupId());
            courseGroupInfo.setRegNum(courseGroupInfo.getRegNum() - 1);
            CourseGroupInfoService.upByIdAndVersion(courseGroupInfo);
        }
        orderService.update(order);
    }

}
