'use strict';

const Controller = require('egg').Controller;
const xml2js = require('xml2js').parseString;
class OrderController extends Controller {

    //订单支付详情页信息
    async getOrderPayInfo() {

        const { ctx } = this;
        const order_id = ctx.params.order_id;
        const result = await ctx.service.credit.order.getOrderPayInfo(order_id);

        ctx.success({ result });

    }

    //我的历史订单
    async getRecord() {

        const { ctx } = this;
        const type = ctx.params.type;

        const results = await ctx.service.credit.order.getHistoryOrders(type);

        ctx.success({ results });
    }

    //支付订单
    async payOrder() {

        const { ctx } = this;
        const input_params = ctx.request.body;
        const { method, order_id, reject_url } = input_params;
        let result = await ctx.service.credit.order.unifiedOrder(method, order_id);
        // result.reject_url = reject_url;
        result.url = `${result.url}&redirect_url=${reject_url}`;
        ctx.success({ result });
    }

    //微信支付异步通知
    async WexinPayNotice() {

        const { ctx } = this;
        let data = '';
        ctx.req.setEncoding('utf8');
        ctx.req.on('data', function (chunk) {
            data += chunk;
        });
        const getxml = await new Promise(function (resolve) {
            ctx.req.on('end', function () {
                resolve(data);
            });
        });
        ctx.logger.info(JSON.stringify({ wexin_pay_xml_params: getxml }));
        const ret_obj = await ctx.helper.xmlTojson(getxml);
        ctx.logger.info({ notice_params: ret_obj });
        const ret = await ctx.service.credit.common.WexinNotify(ret_obj);
        if (ret) {
            ctx.logger.info('1111111111111111111111111111111111111');
            ctx.response.body = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            return ;
        }
        ctx.response.body = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[UNKNOW]]></return_msg></xml>';
        return;
    }

    //查询支付是否完成
    async checkPay() {

        const { ctx } = this;
        const order_id = ctx.params.order_id;
        const is_pay = await ctx.service.credit.order.checkOrderPay(order_id);
        const order = await ctx.service.credit.order.getOrderInfo(order_id);
        let status = 0;
        if (is_pay) {
            status = 1;
        }
        ctx.success({ status, report_id: order.report_id });
    }


}

module.exports = OrderController;
