const ServiceBase = require("../../sve.base");
const system = require("../../../system");
const moment = require('moment');

class MerchanttradeService extends ServiceBase {
    constructor() {
        super("merchant", ServiceBase.getDaoName(MerchanttradeService));
        this.merchantaccountSve = system.getObject("service.merchant.merchantaccountSve");
        this.merchantDao = system.getObject("db.merchant.merchantDao")
    }

    async addMerchanttrades(params) {
        try {
            if (!params.merchant_id) {
                return system.getResultFail(-1, "请选择商户");
            }
            if (!params.trade_time) {
                return system.getResultFail(-1, "请选择交易时间");
            }
            if (!params.amount) {
                return system.getResultFail(-1, "请提供交易金额");
            } else if (0 > params.amount) {
                return system.getResultFail(-1, "交易金额错误");
            }
            if (!params.trade_voucher) {
                return system.getResultFail(-1, "请上传交易凭证");
            }
            params.trade_type = 1;  //线下充值
            params.pay_type = 2;    //线下支付
            params.amount_type = 1;//后入
            params.trade_data_id = moment().format("YYYYMMDDHHmmss");
            params.amount = params.amount;

            var accountamount = await this.merchantaccountSve.findOne({merchant_id: params.merchant_id})
            params.available_amount = params.amount;
            params.balance_amount = params.amount;
            if (accountamount) {
                params.available_amount = params.amount + accountamount.available_amount;
                params.balance_amount = params.amount + accountamount.balance_amount;
            }
            var rtn = await this.dao.create(params);
            return system.getResultSuccess(rtn);
        } catch (e) {
            console.log(e);
            return system.getResultFail();
        }
    }

    async merchanttradesOfList(params) {
        try {
            var currentPage = Number(params.currentPage || 0);
            var pageSize = Number(params.pageSize || 10);
            var where = {};
            if (params.merchant_id) {
                where.merchant_id = {
                    [this.db.Op.eq]: params.merchant_id
                };
            }
            if (params.trade_data_id) {
                where.trade_data_id = {
                    [this.db.Op.eq]: params.trade_data_id
                };
            }
            where.trade_type = {
                [this.db.Op.eq]: 1
            };

            if (params.beginTime) {
                params.beginTime = params.beginTime + " 00:00:00";
            }
            if (params.entTime) {
                params.entTime = params.entTime + " 23:59:59";
            }
            this.addWhereTime(where, 'created_at', params.beginTime, params.entTime, true);
            var orderby = [["id", 'desc']];
            var attributes = [`id`, `trade_data_id`, `trade_time`, `merchant_id`, `amount`, `audit_status`, `audit_remark`,'trade_voucher'];
            var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
            if (page && page.rows) {
                for (var row of page.rows) {
                    this.handleDate(row, ["trade_time"], null);
                }
                await this.setMerchantName(page.rows);
            }
            return system.getResultSuccess(page);
        } catch (e) {
            console.log(e);
            return system.getResultFail();
        }
    }


    async setMerchantName(list) {
        if (!list || list.length == 0) {
            return;
        }
        var merchantIds = [];
        for (var item of list) {
            merchantIds.push(item.merchant_id || 0);
        }
        var merchantMap = await this.merchantDao.findMapByIds(merchantIds, " id, name ");

        for (var item of list) {
            item.merchant = merchantMap[item.merchant_id] || {};
        }
    }

    async auditMerchanttrade(params) {

        try {
            if (!params.id) {
                return system.getResultFail(-1, "请提供ID");
            }
            if (params.audit_status == 0) {
                return system.getResultFail(-1, "请选择审核状态");
            }
            if (params.audit_status == 2 && !params.audit_remark) {
                return system.getResultFail(-1, "请输入失败原因");
            }
            var rtn = await this.dao.update(params);
            if (params.audit_status == 1) {
                var trades = await this.dao.findById(params.id);
                var account = await this.merchantaccountSve.findOne({merchant_id: trades.merchant_id});
                if (account) {
                    await this.merchantaccountSve.addtomerchantrmb(trades.merchant_id, trades.amount);
                } else {
                    await this.merchantaccountSve.create({
                        merchant_id: trades.merchant_id,
                        balance_amount: trades.amount,
                        available_amount: trades.amount
                    });
                }
            }
            return system.getResultSuccess(rtn);
        } catch (e) {
            console.log(e);
            return system.getResultFail();
        }
    }


    async merchanttradesOfListAll(params) {
        try {
            var currentPage = Number(params.currentPage || 0);
            var pageSize = Number(params.pageSize || 10);
            var where = {};
            if (params.merchant_id) {
                where.merchant_id = {
                    [this.db.Op.eq]: params.merchant_id
                };
            }
            if (params.amount_type) {
                where.amount_type = {
                    [this.db.Op.eq]: params.amount_type
                };
            }
            where.audit_status = {
                [this.db.Op.eq]: 1
            };

            if (params.timetype == 1) {
                params.beginTime = moment().startOf('month').format("YYYY-MM-DD");
                params.entTime = moment().endOf('month').format("YYYY-MM-DD");
            } else if (params.timetype == 2) {
                params.beginTime = moment().subtract(6, 'months').format("YYYY-MM-DD");

                params.entTime = moment().format("YYYY-MM-DD");
            } else if (params.timetype == 3) {
                params.beginTime = moment().subtract(12, 'months').format("YYYY-MM-DD");

                params.entTime = moment().format("YYYY-MM-DD");
            }


            if (params.beginTime) {
                params.beginTime = params.beginTime + " 00:00:00";
            }
            if (params.entTime) {
                params.entTime = params.entTime + " 23:59:59";
            }

            this.addWhereTime(where, 'created_at', params.beginTime, params.entTime, true);
            var orderby = [["id", 'desc']];
            var attributes = [];
            var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
            if (page && page.rows) {
                for (var row of page.rows) {
                    this.handleDate(row, ["created_at", "trade_time", "updated_at"], null);
                }
                await this.setMerchantName(page.rows);
            }

            if (params.merchant_id) {
                page.balance_amount = 0;
                page.available_amount = 0;
                var account = await this.merchantaccountSve.findOne({merchant_id: params.merchant_id});
                if (account) {
                    page.balance_amount = account.balance_amount;
                    page.available_amount = account.available_amount;
                }
            }

            return system.getResultSuccess(page);
        } catch (e) {
            console.log(e);
            return system.getResultFail();
        }
    }


    async valetorder(params) {
        try {
            if (!params.merchant_id) {
                return system.getResultFail(-1, "请提供商户ID");
            }
            if (!params.trade_data_id) {
                return system.getResultFail(-1, "请提供流水号");
            }
            if (!params.amount) {
                return system.getResultFail(-1, "请提供交易金额");
            } else if (0 > params.amount) {
                return system.getResultFail(-1, "交易金额错误");
            }
            // if (!params.trade_voucher) {
            //     return system.getResultFail(-1, "请提供业务合同");
            // }
            params.trade_type = 2;  //购买合同
            params.pay_type = 1;    //余额支付
            params.amount_type = 2;//支出
            params.amount = params.amount;

            var accountamount = await this.merchantaccountSve.findOne({merchant_id: params.merchant_id})
            params.available_amount = accountamount.available_amount;
            params.balance_amount =  accountamount.balance_amount;
            var rtn = await this.dao.create(params);
            return system.getResultSuccess(rtn);
        } catch (e) {
            console.log(e);
            return system.getResultFail();
        }
    }

}

module.exports = MerchanttradeService;
