var system = require("../../system");
var settings = require("../../../config/settings")

const md5 = require("MD5");
const logCtl = system.getObject("web.oplogCtl");
const moment = require("moment");

class ChannelApi {
    constructor() {
        this.channelSve = system.getObject("service.channelSve");
        this.esettleSve = system.getObject("service.esettleSve");
        this.restClient = system.getObject("util.restClient");
        this.esettleofflineitemSve = system.getObject("service.esettleofflineitemSve");
        this.FQURL = settings.FQYF();
        this.pushfqlogSve = system.getObject("service.pushfqlogSve");
        this.esettleofflineSve = system.getObject("service.esettleofflineSve");
        this.busistatSve = system.getObject("service.busistatSve");
    }

    //渠道绑定
    async bindPlatform(queryobj, qobj, req) {
        if (!this.trim(queryobj.platform_id)) {
            return system.getErrResult2("platform_id不能为空")
        }
        if (!this.trim(queryobj.channel_id)) {
            return system.getErrResult2("channel_id不能为空")
        }
        if (!this.trim(queryobj.platform_channel_id)) {
            return system.getErrResult2("platform_channel_id不能为空")
        }
        var result = await this.channelSve.bindPlatform(queryobj);
        return result;
    }

    //绑定渠道推送（弃用）
    async pushbindingchannel(queryobj, qobj, req) {
        if (queryobj.day) {
            queryobj.begin = queryobj.day + ' 00:00:00'; /* 自定义时间 */
            queryobj.end = queryobj.day + ' 23:59:59';   /* 自定义时间 */
        } else {
            queryobj.begin = moment().subtract(1, 'days').format('YYYY-MM-DD 00:00:00'); /*前一天的时间*/
            queryobj.end = moment().subtract(1, 'days').format('YYYY-MM-DD 23:59:59'); /*前一天的时间*/
        }
        var result = await this.channelSve.pushbindingchannel(queryobj);
        var data = result.data || [];
        if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
                if (data[i].channel_id == '10000' && data[i].origin_merchant_id != '') {
                    var busiData = await this.esettleSve.findBybusiId(data[i].origin_merchant_id);
                    if (busiData.length > 0) {
                        for (let j = 0; j < busiData.length; j++) {
                            var pushData = this.getBusiData(busiData[j], data[i]);
                            var rc = system.getObject("util.aliyunClient");
                            var rtn = null;
                            rtn = await rc.post(this.FQURL.pushOrderApi, pushData);
                            console.log(pushData)
                            console.log(rtn)
                            var result = JSON.parse(system.decryption(decodeURIComponent(pushData.param)));
                            if (rtn.success == true) {
                                result.contractNo = rtn.data.contractNo;
                                result.topush = "0";
                                result.param = pushData.param;
                                this.pushfqlogSve.create(result)
                            } else {
                                result.topush = "-1";
                                result.errorMsg = rtn.errorMsg;
                                result.param = pushData.param;
                                this.pushfqlogSve.create(result)
                            }
                        }
                    }
                } else {
                    if (data[i].origin_merchant_id != '') {
                        var esettleoffline = await this.esettleofflineSve.findOne({"ecompany_id": data[i].origin_merchant_id});
                        if (esettleoffline != null) {
                            var pushData = this.getBusiDatas(esettleoffline.dataValues, data[i]);
                            var rc = system.getObject("util.aliyunClient");
                            var rtn = null;
                            rtn = await rc.post(this.FQURL.pushOrderApi, pushData);
                            console.log(pushData)
                            console.log(rtn)
                            var result = JSON.parse(system.decryption(decodeURIComponent(pushData.param)));
                            // var result = JSON.parse(pushData.param);
                            if (rtn.success == true) {
                                result.contractNo = rtn.data.contractNo;
                                result.topush = "0";
                                result.param = pushData.param;
                                this.pushfqlogSve.create(result)
                            } else {
                                result.topush = "-1";
                                result.errorMsg = rtn.errorMsg;
                                result.param = pushData.param;
                                this.pushfqlogSve.create(result)
                            }
                        }
                    }
                }

            }
        }

    }


    //渠道添加
    async pushAddChannel(queryobj, qobj, req) {

        try {
            if (!queryobj.platform_id) {
                return system.getResultFail(-1, "platform_id不能为空");
            }
            if (!queryobj.ctype) {
                return system.getResultFail(-1, "ctype不能为空");
            }
            if (!queryobj.name) {
                return system.getResultFail(-1, "name不能为空");
            }
            if (!queryobj.idcode) {
                return system.getResultFail(-1, "idcode不能为空");
            }
            if (queryobj.ctype == 1) {
                if (!queryobj.business_license) {
                    return system.getResultFail(-1, "business_license不能为空");
                }
            } else {
                if (!queryobj.idcard_front) {
                    return system.getResultFail(-1, "idcard_front不能为空");
                }
                if (!queryobj.idcard_back) {
                    return system.getResultFail(-1, "idcard_back不能为空");
                }
            }
            if (!queryobj.contact_man) {
                return system.getResultFail(-1, "contact_man不能为空");
            }
            if (!queryobj.contact_mobile) {
                return system.getResultFail(-1, "contact_mobile不能为空");
            }
            if (!queryobj.contact_email) {
                return system.getResultFail(-1, "contact_email不能为空");
            }
            if (!queryobj.contact_addr) {
                return system.getResultFail(-1, "contact_addr不能为空");
            }

            var da = await this.channelSve.channelSave(queryobj)
            if (da.data) {
                var bind = {
                    platform_id: queryobj.platform_id,
                    channel_id: da.data.id,
                    platform_channel_id: 10000
                }
                var result = this.channelSve.bindPlatform(bind);
                console.log(result);
            }
            return da;
        } catch (e) {
            console.log(e);
            return system.getResultFail(500, "接口错误");
        }
    }

    //商户添加
    async pushAddMerchant(queryobj, qobj, req) {
        try {
            if (!queryobj.channel_id) {
                return system.getResultFail(-1, "channel_id不能为空");
            }
            // if(!queryobj.origin_id){
            //     return system.getResultFail(-1, "origin_id不能为空");
            // }
            if (!queryobj.merchant_name) {
                return system.getResultFail(-1, "merchant_name不能为空");
            }
            if (!queryobj.contact_man) {
                return system.getResultFail(-1, "contact_man不能为空");
            }
            if (!queryobj.contact_mobile) {
                return system.getResultFail(-1, "contact_mobile不能为空");
            }
            if (!queryobj.contact_email) {
                return system.getResultFail(-1, "contact_email不能为空");
            }
            if (!queryobj.contact_addr) {
                return system.getResultFail(-1, "contact_addr不能为空");
            }
            if (!queryobj.merchanmt_id) {
                return system.getResultFail(-1, "merchanmt_id不能为空");
            }
            if (queryobj.id) {
                if (!queryobj.origin_merchant_id) {
                    return system.getResultFail(-1, "origin_merchant_id不能为空");
                }
                if (!queryobj.origin_merchant_name) {
                    return system.getResultFail(-1, "origin_merchant_name不能为空");
                }
            }
            queryobj.origin_id = 10000;
            return await this.channelSve.merchantSaves(queryobj);
        } catch (e) {
            console.log(e);
            return system.getResultFail(500, "接口错误");
        }
    }


    async paydayCount(queryobj, qobj, req) {
        var data = await this.separateGet(queryobj);
        console.log(data.dataValues)
    }

    async paydayDetails(queryobj, qobj, req) {
        var data = await this.separateGet(queryobj);
    }

    async separateGet(queryobj) {
        let encry = system.decryption(queryobj.param);
        encry = JSON.parse(encry);
        if (encry.channel_id == 10000) {
            var busiData = await this.esettleSve.findByIdList(encry.data_id);
            return busiData;
        }
        var esettleoffline = await this.esettleofflineitemSve.find({"esettleoffline_id": encry.data_id});
        return esettleoffline;
    }

    getBusiData(da, chnanel) {
        var resultData = {
            "idempotentId": da.id.toString(),// 业务编号(订单id)
            "idempotentSource": "bpo_xbg",// 来源编号，写死：bpo_xbg
            "idempotentSourceName": "BPO",// 来源编号，写死：BPO薪必果
            "thirdPartyChannelId": chnanel.channel_id.toString(),// 渠道id
            "thirdPartyCustomerId": chnanel.id.toString(),// 第三方客户id
            "productId": "5e6b02cc3290c3000a3a63dc",// 云服产品id (测试环境)
            //"productId": "5e6c89d54c52bf000a750bc5",// 云服产品id (生产环境)

            // "allotRatio":"50",// 分润比例(百分比的数字部分（如：50代表50%）)
            "orderPrice": da.deduct_amt,// 订单金额
            "productQuantity": "1",// 产品数量
            "companyName": chnanel.merchant_name,// 公司名称
            "phone": chnanel.contact_mobile
        };
        var str = {
            "data_id": da.id,// 发薪批次id tbl_order.id 或者 c_esettle_offline.id
            "channel_id": chnanel.channel_id,//渠道id
            "channel_merchant_id": chnanel.id,//渠道商户id
            "origin_merchant_id": chnanel.origin_merchant_id,//来源商户id
            "platform_channel_id": chnanel.platform_id,//对方渠道id
        };
        resultData.param = encodeURIComponent(system.encryption(System.encryption(JSON.stringify(str))));
        return resultData;
    }

    getBusiDatas(da, chnanel) {
        var resultData = {
            "idempotentId": da.id.toString(),// 业务编号(订单id)
            "idempotentSource": "bpo_xbg",// 来源编号，写死：bpo_xbg
            "idempotentSourceName": "BPO",// 来源编号，写死：BPO薪必果
            "thirdPartyChannelId": chnanel.channel_id.toString(),// 渠道id
            "thirdPartyCustomerId": chnanel.id.toString(),// 第三方客户id
            "productId": "5e6b02cc3290c3000a3a63dc",// 云服产品id (测试环境)
            // "productId": "5e6c89d54c52bf000a750bc5",// 云服产品id (生产环境)
            // "allotRatio":"50",// 分润比例(百分比的数字部分（如：50代表50%）)
            "orderPrice": da.amt,// 订单金额
            "productQuantity": "1",// 产品数量
            "companyName": da.ecompanyName,// 公司名称
            "phone": chnanel.contact_mobile
        };
        var str = {
            "data_id": da.id,// 发薪批次id tbl_order.id 或者 c_esettle_offline.id
            "channel_id": chnanel.channel_id,//渠道id
            "channel_merchant_id": chnanel.id,//渠道商户id
            "origin_merchant_id": chnanel.origin_merchant_id,//来源商户id
            "platform_channel_id": chnanel.platform_id,//对方渠道id
        };
        resultData.param = encodeURIComponent(system.encryption(JSON.stringify(str)));
        return resultData;
    }


    // -------------------------------------

    async pushChannelsAsync(queryobj, qobj, req) {
        this.pushChannels(queryobj, qobj, req);
        return {
            msg: "success start",
            config: settings.FQYF()
        };
    }

    async pushChannels(queryobj, qobj, req) {
        let begin;
        let end;
        if (queryobj.day) {
            begin = queryobj.day + ' 00:00:00'; /* 自定义时间 */
            end = queryobj.day + ' 23:59:59';   /* 自定义时间 */
        } else {
            begin = moment().subtract(1, 'days').format('YYYY-MM-DD 00:00:00'); /*前一天的时间*/
            end = moment().subtract(1, 'days').format('YYYY-MM-DD 23:59:59'); /*前一天的时间*/
        }
        var merchantIds = await this.channelSve.getPushMerchantIds() || [];

        if (merchantIds.length == 0) {
            return system.getErrResult2("暂无绑定渠道");
        }

        for (let merchantId of merchantIds) {
            console.log(merchantId, "----------------------------");
            // 查渠道商户id
            let merchant = (await this.channelSve.merchantInfo({id: merchantId}) || {}).data;
            if (merchant.origin_id == 10000) {
                await this.pushOnlineOrder(merchant, begin, end);
            } else {
                await this.pushOfflineOrder(merchant, begin, end);
                // let order = await this.esettleofflineSve.findById(merchant.data_id);
            }
        }
    }

    async pushOnlineOrder(merchant, begin, end) {
        let orders = await this.esettleSve.findPushInfos(merchant.origin_merchant_id, begin, end) || [];
        if (orders.length == 0) {
            return;
        }
        for (let order of orders) {
            // 获取推送数据
            let pushData = this.getPushData(merchant, order);

            // 创建log
            let log = await this.pushfqlogSve.create(pushData.log);

            // 推送数据
            var rc = system.getObject("util.aliyunClient");
            let rtn = await rc.post(this.FQURL.pushOrderApi, pushData.data);

            // 返回结果都保存到toPush中吧
            log.topush = JSON.stringify(rtn);
            await log.save();
        }
    }

    async pushOfflineOrder(merchant, begin, end) {
        let orders = await this.esettleofflineSve.findPushInfos(merchant.origin_merchant_id, begin, end) || [];
        if (orders.length == 0) {
            return;
        }
        for (let order of orders) {
            // 获取推送数据
            let pushData = this.getPushData(merchant, order);

            // 创建log
            let log = await this.pushfqlogSve.create(pushData.log);

            // 推送数据
            var rc = system.getObject("util.aliyunClient");
            let rtn = await rc.post(this.FQURL.pushOrderApi, pushData.data);

            // 返回结果都保存到toPush中吧
            log.topush = JSON.stringify({rtn});
            await log.save();
        }
    }

    getPushData(merchant, order) {
        let data = {
            "idempotentId": this.trim(order.id),// 业务编号(订单id)
            "idempotentSource": "bpo_xbg",// 来源编号，写死：bpo_xbg
            "idempotentSourceName": "BPO",// 来源编号，写死：BPO薪必果
            "thirdPartyChannelId": this.trim(merchant.channel_id),// 渠道id
            "thirdPartyCustomerId": this.trim(merchant.id).toString(),// 第三方客户id
            // "productId": "5e6b02cc3290c3000a3a63dc",// 云服产品id (测试环境)
            "productId": settings.FQYF().productId,// 云服产品id (生产环境)

            // "allotRatio":"50",// 分润比例(百分比的数字部分（如：50代表50%）)
            "orderPrice": system.f2y(order.deduct_amt),// 订单金额
            "productQuantity": "1",// 产品数量
            "companyName": merchant.merchant_name,// 公司名称
            "phone": merchant.contact_mobile
        };
        var log = {
            "data_id": this.trim(order.id),   // 发薪批次id tbl_order.id 或者 c_esettle_offline.id
            "channel_id": merchant.channel_id, //渠道id
            "channel_merchant_id": merchant.id,//渠道商户id
            "origin_merchant_id": merchant.origin_merchant_id,//来源商户id
        };
        data.param = encodeURIComponent(system.encryption(JSON.stringify(log)));
        log.param = data.param;
        return {
            data: data,
            log: log,
        }
    }

    async orderInfo(queryobj, qobj, req) {
        let param = system.decryption(queryobj.data);
        // {"data_id":17,"channel_id":10002,"channel_merchant_id":"0","origin_merchant_id":"10048","pushplatform_channel_id":10000}
        try {
            param = JSON.parse(param);
        } catch (error) {
            console.log(error);
            return system.getErrResult2("参数解析错误");
        }

        // 测试使用
        // param.channel_merchant_id = 1;
        // param.data_id = 511;

        if (!param.channel_merchant_id) {
            return system.getErrResult2("参数错误, 渠道商户不存在");
        }
        if (!param.data_id) {
            return system.getErrResult2("参数错误, 订单不存在");
        }
        let merchant = await this.channelSve.merchantInfo({id: param.channel_merchant_id}) || {};
        merchant = merchant.data;
        if (!merchant) {
            return system.getErrResult2(`渠道商户${param.channel_merchant_id}不存在`);
        }

        let info = {
            merchantName: merchant.merchant_name
        };
        if (merchant.origin_id == 10000) {
            let order = await this.esettleSve.findTBLOrderById(param.data_id) || {};
            info.createTime = moment(order.create_time).format('YYYY-MM-DD HH:mm:ss');
            info.actualAmt = system.f2y(order.actual_amt);
            info.incomeTax = system.f2y(order.income_tax);
            info.serviceTax = system.f2y(order.service_tax);
            info.deductAmt = system.f2y(order.deduct_amt);
        } else {
            let order = await this.esettleofflineSve.findById(param.data_id);
            info.createTime = moment(order.created_at).format('YYYY-MM-DD HH:mm:ss');
            info.actualAmt = system.f2y(order.actual_amt);
            info.serviceTax = system.f2y(order.service_tax);
            info.deductAmt = system.f2y(order.amt);
            let incomeTax = await this.esettleofflineitemSve.sumIncome(order.id);
            info.incomeTax = system.f2y(incomeTax);
        }
        return system.getResult2(info);
    }

    async itemPage(queryobj, qobj, req) {
        let currentPage = Number(queryobj.currentPage || 1);
        let pageSize = Number(queryobj.pageSize || 10);
        let param = system.decryption(queryobj.data);
        // {"data_id":17,"channel_id":10002,"channel_merchant_id":"0","origin_merchant_id":"10048","pushplatform_channel_id":10000}
        try {
            param = JSON.parse(param);
        } catch (error) {
            console.log(error);
            return system.getErrResult2("参数解析错误");
        }

        // 测试使用
        // param.channel_merchant_id = 9;
        // param.data_id = "1209403539471060994";

        if (!param.channel_merchant_id) {
            return system.getErrResult2("参数错误, 渠道商户不存在");
        }
        if (!param.data_id) {
            return system.getErrResult2("参数错误, 订单不存在");
        }
        let merchant = await this.channelSve.merchantInfo({id: param.channel_merchant_id}) || {};
        merchant = merchant.data;
        if (!merchant) {
            return system.getErrResult2(`渠道商户${param.channel_merchant_id}不存在`);
        }

        let page;
        if (merchant.origin_id == 10000) {
            page = await this.esettleSve.pageByOrderId(param.data_id, currentPage, pageSize);
        } else {
            page = await this.esettleofflineitemSve.pageByByOrderId(param.data_id, currentPage, pageSize);
            if (page.rows) {
                for (let row of page.rows) {
                    row.deduct_amt = row.amt;
                    row.trade_status = "02";
                }
            }
        }
        if (page && page.rows) {
            for (let row of page.rows) {
                row.actual_amt = system.f2y(row.actual_amt);
                row.income_tax = system.f2y(row.income_tax);
                row.service_tax = system.f2y(row.service_tax);
                row.deduct_amt = system.f2y(row.deduct_amt);
            }
        }
        return system.getResult2(page);
    }


    //------------------------------------------------财务中心对账 begin------------------------------------------------------------\\
    async pushReconciliation(queryobj, qobj, req) {
        let begin;
        let end;
        let month;
        if (queryobj.num) {
            //自定义时间
            month = moment().add().month(moment().month() - queryobj.num).startOf('month').format("YYYYMM");
            begin = moment().add().month(moment().month() - queryobj.num).startOf('month').format("YYYYMMDD");
            end = moment().add().month(moment().month() - queryobj.num).endOf('month').format("YYYYMMDD");
        } else {
            month = moment().add().month(moment().month() - queryobj.num).startOf('month').format("YYYYMM");
            begin = moment().add().month(moment().month() - 1).startOf('month').format("YYYYMMDD");
            end = moment().add().month(moment().month() - 1).endOf('month').format("YYYYMMDD");
        }

        var merchantIds = await this.channelSve.getchannelIds() || [];
        if (merchantIds.length == 0) {
            return system.getErrResult2("暂无绑定渠道");
        }
        for (let merchantId of merchantIds) {
            console.log(merchantId, "----------------------------");
            // 查渠道所有商户
            let merchant = await this.channelSve.getchannelmerchantIds({channel_id: merchantId.channel_id}) || {};
            if (merchant.length > 0) {
                let busiId = [];
                for (let mer of merchant) {
                    busiId.push(mer.origin_merchant_id);

                }
                if (busiId) {
                    var list = await this.busistatSve.gettomonthList(busiId, begin, end);
                    if (list) {
                        let pushData = this.gettopushdata(merchantId, list, month, merchant);
                        var rtn = null;
                        var rc = system.getObject("util.aliyunClient");
                        rtn = await rc.post(this.FQURL.pushOrderSum, pushData);
                        // console.log(pushData);
                        console.log(rtn);
                    }
                }
            }
        }
    }

    gettopushdata(merchantId, list, month, merchant) {

        var data = {
            channel_id: merchantId.platform_id, //蜂擎云服渠道id,
            channel_name: merchantId.name || " ",//渠道上名称,
            month: month, //月份（202006YYYYMM）channel_name: 渠道上名称,
            trans_amt_total: 0, //本月充值总额额,
            deduct_amt: 0, //扣除金额,
            amt: 0, //申请发薪金额,
            actual_amt: 0, //实发金额,
            income_tax: 0,//个税,
            service_tax: 0,//服务费金额,
            added_value_tax: 0, //增值税,
            items: list
        }
        for (let item of list) {
            for (let i = 0; i < merchant.length; i++) {
                if (merchant[i].origin_merchant_id == item.busi_id) {
                    item.merchant_id = merchant[i].merchant_id;
                    break;
                }
            }
            item.user_department_name = "渠道销售中心";
            data.trans_amt_total = data.trans_amt_total + item.trans_amt;
            data.deduct_amt = data.deduct_amt + item.deduct_amt;
            data.amt = data.amt + item.amt;
            data.actual_amt = data.actual_amt + item.actual_amt;
            data.income_tax = data.income_tax + item.income_tax;
            data.service_tax = data.service_tax + item.service_tax;
            data.added_value_tax = data.added_value_tax + item.added_value_tax;
        }
        return data;
    }


    //------------------------------------------------财务中心对账 end------------------------------------------------------------\\

    trim(o) {
        if (!o) {
            return "";
        }
        return o.toString().trim();
    }
}

module.exports = ChannelApi;
