var system = require("../../../system")
const settings = require("../../../../config/settings")
const CtlBase = require("../../ctlms.base");

class OrderCtl extends CtlBase {
    constructor() {
        super();
        this.userSve = system.getObject("service.uc.userSve");
        this.orderSve = system.getObject("service.order.orderSve");
        this.merchantaccountSve = system.getObject("service.merchant.merchantaccountSve");
        this.merchanttradeSve = system.getObject("service.merchant.merchanttradeSve");
        // this.redisClient = system.getObject("util.redisClient");
        this.productSve = system.getObject("service.product.productSve");
        this.ordersignlogSve = system.getObject("service.order.ordersignlogSve");
        this.orderauthlogSve = system.getObject("service.order.orderauthlogSve");
    }

    /**
     * fn:保存订单
     * 如果是单价商品 product_type=1  product_id =xxx  product_ids =[] product_unit_price=1
     * 如果是组合产品 product_type=2 product_id=xxx   product_ids=['xxx','xxxx'] product_unit_price=-1
     * ps:需要对金额单位进行转化
     * @param pobj
     * @param pobj2
     * @param req
     * @param res
     * @returns {Promise<void>}
     */
    async saveEorder(pobj, pobj2, req, res) {
        try{
            if(!pobj.merchant_id){
                return system.getResult(null,`参数错误 商户ID不能为空`)
            }
            if(!pobj.merchant_name){
                return system.getResult(null,`参数错误 商户名称不能为空`)
            }
            //TODO:可能需要商户的合同ID和合同名称

            if(!pobj.contract_url){
                return system.getResult(null, `参数错误 业务合同不能为空`);
            }
            if(!pobj.live_start){
                return system.getResult(null, `参数错误 生效时间不能为空`);
            }
            if(!pobj.live_end){
                return system.getResult(null, `参数错误 结束时间不能为空`);
            }
            if(!pobj.hasOwnProperty('price')){
                return system.getResult(null, `参数错误 订单金额不能为空`);
            }
            pobj.price=system.y2f(pobj.price);
            if(pobj.product_type=='2'){//组合产品 需要 规格设成pricee
                pobj.product_specifications=pobj.price;
            }
            if(pobj.product_type=='1'){  //如果是单个产品 需要转化单价
                pobj.product_unit_price = system.y2f(pobj.product_unit_price);
            }
            // TODO:需要去调用商户钱包 扣钱
            if(pobj.id){
                let reduceAccountBalanceRes = await this.merchantaccountSve.addordelavailable({merchant_id: this.trim(pobj.merchant_id),amount:pobj.price*(-1)});
                if(reduceAccountBalanceRes.status!=0){
                    return system.getResult(null, `扣款失败`);
                }
            }
            //保存
            let res = await this.orderSve.saveEorder(pobj);
            if(res.status==0 && res.data && res.data.price && res.data.product_type){
                res.data.price = system.f2y(res.data.price) || 0;
                if(res.data.product_type=='2'){ //如果是组合产品
                    res.data.product_specifications = system.f2y(res.data.product_specifications) || 0;
                }
            }
            return system.getResult(res);
        }catch (e) {
            console.log(e);
            return system.getResult(null, `系统错误`);
        }
    }

    /**
     * fn:审核订单
     * @param pobj
     * @param pobj2
     * @param req
     * @param res
     * @returns {Promise<{msg: string, data: (*|null), bizmsg: string, status: number}>}
     */
    async auditEorder(pobj, pobj2, req, res) {
        try{
            if(!pobj.id){
                return system.getResult(null, `订单【${pobj.id}】不存在`);
            }
            if(!pobj.audit_status){
                return system.getResult(null, `参数错误 审核状态不能为空`);
            }
            pobj.audit_user_id=req.loginUser.id; //获取审核人
            let res = await this.orderSve.auditEorder(pobj);
            //TODO:审核订单成功之后
            if(res.status==0){
                this.pushMerchantTrade(pobj);
            }
            return res;
        }catch (e) {
            console.log(e);
            return system.getResult(null, `系统错误`);
        }
    }

    /**
     * fn:推送商户流水
     * @param params
     */
    async pushMerchantTrade(params){
        let orderBean = await this.orderSve.getEorderById({id: this.trim(params.id)});
        if(orderBean.status!=0){
            console.log(`推送流水失败 订单信息获取异常 订单信息：` + JSON.stringify(orderBean));
        }
        orderBean = orderBean.data;
        if(params.audit_status=='20'){ //订单审核成功
            //TODO:推送给赵大哥
            let res =await this.merchantaccountSve.reduceAccountBalance({merchant_id:orderBean.merchant_id,amount:orderBean.price});
            if(res.status==0){
                console.log("扣除余额成功 返回结果：" + JSON.stringify(res));
                let res = await this.merchanttradeSve.valetorder({merchant_id:orderBean.merchant_id,amount:orderBean.price,trade_data_id:orderBean.id});
                if(res.status==0 && res.data && res.data.id){
                    console.log('交易流水创建完成 结果：' + JSON.stringify(res));
                    let r = await this.orderSve.updOrderSimple({id: orderBean.id, trade_id: res.data.id});
                    console.log("更新交易流水ID完成 结果："+JSON.stringify(r));
                }
            }
        }
        if(params.audit_status=='30'){ //订单审核失败
            //TODO:推送给赵大哥
            let reduceAccountBalanceRes = await this.merchantaccountSve.addordelavailable({merchant_id: this.trim(orderBean.merchant_id),amount:orderBean.price});
            console.log("订单审核失败 余额退回 "+JSON.stringify(reduceAccountBalanceRes));
        }
    }


    /**
     * fn:查看订单(根据ID查询)
     * @param pobj
     * @param pobj2
     * @param req
     * @param res
     * @returns {Promise<{msg: string, data: (*|null), bizmsg: string, status: number}>}
     */
    async getEorderById(pobj, pobj2, req, res) {
        try{
            if(!pobj.id){
                return system.getResult(null, `订单【${pobj.id}】不存在`);
            }
            let res = await this.orderSve.getEorderById(pobj);
            return res;
        }catch (e) {
            console.log(e);
            return system.getResult(null, `系统错误`);
        }
    }

    /**
     * fn:查看订单列表(分页)
     * @param pobj
     * @param pobj2
     * @param req
     * @param res
     * @returns {Promise<{msg: string, data: (*|null), bizmsg: string, status: number}>}
     */
    async pageEorder(pobj, pobj2, req, res) {
        try{
            let res = await this.orderSve.pageEorder(pobj);
            if(res.status!=0 || res.data.count==0){
                return res;
            }
            //格式化产品信息
            let ids = [],productMap={};
            for (let item of res.data.rows) {
                item.price = system.f2y(item.price);
                if(item.product_type=='1'){
                    item.product_unit_price = system.f2y(item.product_unit_price);
                }
                if(item.product_type=='2'){
                    item.product_specifications = system.f2y(item.product_specifications);
                }
                ids.push(item.product_id);
            }
            let p_listRes = await this.productSve.getByIds({ids:ids});
            if(p_listRes.status!=0){
                return system.getResul(`获取订单产品失败`);
            }
            //将产品列表映射成Map结构
            for (let ele of p_listRes.data) {
                productMap[ele.id]=ele;
            }
            for (let item of res.data.rows) {
                item.product_info = productMap[item.product_id];
            }
            return res;
        }catch (e) {
            console.log(e);
            return system.getResult(null, `系统错误`);
        }
    }

    /**
     * fn:更改订单状态
     * ps:可以修改的订单的状态 支付状态 审核状态 生效状态  状态code 依次 10 20 30 待xx 完成 失败
     *    每次只能修改一个状态 （这里只能修改状态没有 状态标记注释 如果修改订单审核状态为失败请调用 “auditEorder” 接口）
     *    TODO:可能考虑修改生效状态需要加到 延迟消息队列中 用来处理过期失效的订单
     * @param pobj
     * @param pobj2
     * @param req
     * @param res
     * @returns {Promise<void>}
     */
    async updEorderStatus(pobj, pobj2, req, res){
        if(!pobj.id){
            return system.getResult(null, `参数错误 订单ID不能为空`);
        }
        try{
            return await this.orderSve.updEorderStatus(pobj);
        }catch (e) {
            console.log(e);
            return system.getResult(null, `系统错误`);
        }
    }

    /**
     * fn:查看日志
     * @param pobj
     * @param pobj2
     * @param req
     * @param res
     * @returns {Promise<void>}
     */
    async pageEorderLog(pobj, pobj2, req, res){
        if(pobj.product_property=='1'){
            return await this.orderauthlogCtl.pageEorderAuthLog(pobj);
        }else if(pobj.product_property=='2'){
            return await this.ordersignlogSve.pageEorderSignLog(pobj);
        }else{
            return system.getResult(null, `参数错误 产品类型属性不存在`);
        }
    }
}

module.exports = OrderCtl;