package com.ym.mec.collectfee.service.impl;

import com.alibaba.fastjson.JSON;
import com.thoughtworks.xstream.XStream;
import com.ym.mec.collectfee.common.dao.BaseDAO;
import com.ym.mec.collectfee.common.page.PageInfo;
import com.ym.mec.collectfee.common.service.impl.BaseServiceImpl;
import com.ym.mec.collectfee.dao.OrderDao;
import com.ym.mec.collectfee.entity.*;
import com.ym.mec.collectfee.service.CourseGroupInfoService;
import com.ym.mec.collectfee.service.OrderService;
import com.ym.mec.collectfee.service.SchoolService;
import com.ym.mec.collectfee.service.YqPayService;
import com.ym.mec.collectfee.utils.HttpUtil;
import com.ym.mec.collectfee.utils.MapUtil;
import com.ym.mec.collectfee.utils.XStreamUtil;
import com.ym.mec.collectfee.utils.yqpay.YqPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.StringWriter;
import java.io.Writer;
import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderServiceImpl extends BaseServiceImpl<Integer, Order> implements OrderService {

    @Value("${yq-pay.notify-url}")
    private String notifyUrl;

    @Value("${yq-pay.return-host}")
    private String returnHost;

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private CourseGroupInfoService courseGroupInfoService;

    //公共密钥
    @Value("${common.properties.mec-publicKey}")
    private String publicKey;

    @Value("${common.properties.mec-url}")
    private String url;

    @Override
    public BaseDAO<Integer, Order> getDAO() {
        return orderDao;
    }

    @Override
    public List<Order> getOrderByUserId(Integer userId) {
        return orderDao.getOrderByUserId(userId);
    }

    @Override
    public String pushOrder(String batchNum) {
        try {
            RequestParamBean requestParamBean = new RequestParamBean();
            List<Order> orderList = orderDao.getOrderByBatch(batchNum);
            if (orderList == null || orderList.size() < 1) {
                return null;
            }
            XStream xs = new XStream();
            xs.autodetectAnnotations(true);
            Writer writer = new StringWriter();
            Orders orders = new Orders(orderList);
            xs.toXML(orders, writer);
            String body = writer.toString();
            body = body.substring(body.indexOf("<body>") + 6, body.indexOf("</body>"));

            body = Base64.getEncoder().encodeToString(body.getBytes());
            requestParamBean.setBody(body);
            requestParamBean.setHead(XStreamUtil.getOrdersHead(body, 121512, publicKey, null, null));

            xs.autodetectAnnotations(true);
            writer = new StringWriter();
            writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
            xs.toXML(requestParamBean, writer);
            return writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public int countOrder(String poName, String voicePort) {
        return orderDao.countOrder(poName, voicePort);
    }

    @Override
    public Object getSchoolDetail(Integer schoolId) {
        try {
            RequestParamBean requestParamBean = new RequestParamBean();
            String body = "<status>1</status><schoolId>" + schoolId + "</schoolId>";
            body = Base64.getEncoder().encodeToString(body.getBytes());
            requestParamBean.setBody(body);
            requestParamBean.setHead(XStreamUtil.getOrdersHead(body, 124005, publicKey, null, null));
            XStream xs = new XStream();
            xs.autodetectAnnotations(true);
            Writer writer = new StringWriter();
            writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
            xs.toXML(requestParamBean, writer);
            String parseBody = parseBody(HttpUtil.postXmlData(writer.toString(), url));
            ResponseCourseEntity xmlToObject = XStreamUtil.xmlToObject("body", ResponseCourseEntity.class, parseBody);
            courseGroupInfoService.upSetCourseGroup(xmlToObject);
            return schoolService.upsetSchool(xmlToObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Order getOrderByOrderNo(String orderNo) {
        return orderDao.getOrderByOrderNo(orderNo);
    }


    public String parseBody(String body) {
        body = body.substring(body.indexOf("<body>") + 6, body.indexOf("</body>"));
        return "<body><courses>" + new String(Base64.getDecoder().decode(body)) + "</courses></body>";
    }

    @Override
    public int getPayOrderNums() {
        return orderDao.getPayOrderNums();
    }

    @Override
    public List<Order> findPayingOrders() {
        return orderDao.findPayingOrders();
    }

    @Override
    public Map getPayMap(Account routingAccount, Order order, School school) throws Exception {
//    	order.setAmount(new BigDecimal(2));

        String notifyUrl = this.notifyUrl; //异步通知地址
        String returnUrl = this.returnHost + "/#/payment?userId=" + order.getUserId();//支付后返回页面

        if (school != null) {
            returnUrl = this.returnHost + "/#/login?schoolId=" + school.getSchoolId() + "&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}";//支付方式配置

        List<Map> tempRoutingList = new ArrayList();
        Map<String, Object> routingList = new HashMap<>();
        routingList.put("routingMerNo", routingAccount.getSellerNo());//分佣账户
//      routingList.put("routingFee", order.getAmount()); //分佣金额
        routingList.put("routingFee", order.getAmount().subtract((order.getAmount().multiply(new BigDecimal(0.28)).divide(new BigDecimal(100))).setScale(2, BigDecimal.ROUND_HALF_UP))); //分佣金额
        tempRoutingList.add(routingList);

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

        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", order.getOrderNo()); //商户订单号
        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 rqMap;
    }

    @Override
    public List<Order> getOrderByClassId(Integer classId, Integer type, String voicyPart, String startTime, String endTime, Integer branchId) {
        return orderDao.getOrderByClassId(classId, type, voicyPart, startTime, endTime, branchId);
    }

    public static void main(String[] args) {
        BigDecimal temp = new BigDecimal(1440);
        BigDecimal feelv = new BigDecimal(0.28);
        BigDecimal result = temp.subtract((temp.multiply(feelv).divide(new BigDecimal(100))).setScale(2, BigDecimal.ROUND_HALF_UP));
        System.out.println(result);
    }

    @Override
    public int updateByIdAndStatus(Map upMap) {
        return orderDao.updateByIdAndStatus(upMap);
    }

    @Override
    public List<Order> findPayingOrdersOver(Map<String, Object> map) {
        return orderDao.findPayingOrdersOver(map);
    }

    @Override
    public Integer getPayingOrderNums(int groupId) {
        return orderDao.getPayingOrderNums(groupId);
    }

    @Override
    public Order findOrderByStatus(Integer userId, Integer status) {
        return orderDao.findOrderByStatus(userId, status);
    }

    @Override
    public Order findRegOrderByStatus(Integer userId, Integer status) {
        return orderDao.findRegOrderByStatus(userId, status);
    }

    @Override
    public PageInfo<Order> queryOrderPage(OrderQueryInfo queryInfo) {
        PageInfo<Order> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);

        List<Order> dataList = null;
        int count = orderDao.queryOrderCount(params);
        if (count > 0) {
            int page = count % pageInfo.getLimit() > 0 ? 1 : 0;
            int totalPage = count / pageInfo.getLimit() + page;
            pageInfo.setTotal(count);
            pageInfo.setTotalPage(totalPage);
            params.put("offset", pageInfo.getOffset());
            dataList = orderDao.queryOrderPage(params);
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }


}