const axios = require("axios");
const settings = require("../../../config/settings");
const Moment = require("moment");
const centerChannelUrl = settings.QIFUTONG.centerChannelUrl();
const qifutongUrl = settings.QIFUTONG.qifutongUrl();
const { appKey, secret } = settings.QIFUTONG;

class BaseClient {
    constructor() {
        this.appKey = appKey;
        this.secret = secret;
        this.instance = null;
    }
    static getInstance() {
        if (!this.instance) {
            this.instance = new BaseClient();
        }
        return this.instance;
    }
    /**
     * 推送到 启服通
     * @param {*}  user 
     * @param {*} data 
     */
    async pushQiFuTong(url, data, user = 'center-manage',) {
        const header = await this.getLoginByUserName(user);
        return await this.postRequest(`${qifutongUrl}${url}`, data, header);
    }

    async getLoginByUserName(user) {
        const token = await this.getAppTokenByAppKey(this.appKey, this.secret);
        const data = await this.postRequest(`${centerChannelUrl}/api/opreceive/accessAuth/springBoard`, {
            "actionType": "getLoginByUserName",
            "actionBody": {
                "channelUserId": user,
                "user": user,
                "userName": user
            }
        }, {
            token
        });
        return {
            token,
            userpin: data.userpin
        }
    }

    async getAppTokenByAppKey(appKey, secret) {
        const data = await this.postRequest(`${centerChannelUrl}/api/opreceive/accessAuth/getAppTokenByAppKey`, {
            "actionType": "getAppTokenByAppKey",
            "actionBody": {
                "appkey": appKey,
                "secret": secret
            }
        });
        return data.token
    }

    async postRequest(url, data, headers = {}) {
        try {
            // console.log(` ${url} : 请求信息 ------- `);
            // console.log(JSON.stringify(data))
            // console.log(JSON.stringify(headers))
            let result = await axios.post(`${url}`, data, {
                headers: {
                    'Content-Type': 'application/json',
                    ...headers
                }
            });
            result = result.data;
            // console.log(` ${url} : 返回信息 ------- `);
            // console.log(result);
            if (result.status === 0) {
                return result.data
            } else {
                throw new Error(result.msg)
            }
        } catch (err) {
            console.log(` ${url} : 返回错误信息 ------- `);
            console.log(err)
            throw (err)
        }
    }

    async getAllChannels() {
        const data = await this.pushQiFuTong('/web/auth/accessAuth/springBoard', {
            "actionType": "getAllChannels",
            "actionBody": {
            }
        });
        return data;
    }
    async getAllProducts() {
        const data = await this.pushQiFuTong('/web/action/product/springBoard', {
            "actionType": "getAllProducts",
            "actionBody": {
            }
        });
        return data;
    }
    async getNeedProductType() {
        const data = await this.pushQiFuTong('/web/action/opNeed/springBoard', {
            "actionType": "getNeedProductType",
            "actionBody": {
            }
        });
        return data;
    }
    async getStatisticsByUappId(pobj) {
        const data = await this.pushQiFuTong('/web/action/opNeed/springBoard', {
            "actionType": "getStatisticsByUappId",
            "actionBody": pobj
        });
        return data;
    }
    async getOrderStatisticsByUappId(pobj) {
        const data = await this.pushQiFuTong('/web/opaction/order/springBoard', {
            "actionType": "getOrderStatisticsByUappId",
            "actionBody": pobj
        });
        return data;
    }
    async getNeedFunnelStatistics(pobj) {
        const data = await this.pushQiFuTong('/web/action/opNeed/springBoard', {
            "actionType": "getNeedFunnelStatistics",
            "actionBody": pobj
        });
        return data;
    }
    async getStatisticsByProduct(pobj) {
        const data = await this.pushQiFuTong('/web/action/opNeed/springBoard', {
            "actionType": "getStatisticsByProduct",
            "actionBody": pobj
        });
        return data;
    }
    async getOrderStatisticsByProduct(pobj) {
        const data = await this.pushQiFuTong('/web/opaction/order/springBoard', {
            "actionType": "getOrderStatisticsByProduct",
            "actionBody": pobj
        });
        return data;
    }
    async getStatisticsByArea(pobj) {
        const data = await this.pushQiFuTong('/web/action/opNeed/springBoard', {
            "actionType": "getStatisticsByArea",
            "actionBody": pobj
        });
        return data;
    }
    async getNeedComparison(pobj) {
        const data = await this.pushQiFuTong('/web/action/opNeed/springBoard', {
            "actionType": "getNeedComparison",
            "actionBody": pobj
        });
        return data;
    }
    async getOrdersComparison(pobj) {
        const data = await this.pushQiFuTong('/web/opaction/order/springBoard', {
            "actionType": "getOrdersComparison",
            "actionBody": pobj
        });
        return data;
    }

    async getStatisticsList(pobj) {
        let url;
        let query;
        switch (pobj.listType) {
            case "business":
                delete pobj.listType;
                url = '/web/action/opNeed/springBoard'
                query = {
                    "actionType": "getNeedComparisonList",
                    "actionBody": {
                        ...pobj,
                        tag: "need"
                    }
                }
                break
            case "businessToOrder":
                delete pobj.listType;
                url = '/web/action/opNeed/springBoard'
                query = {
                    "actionType": "getNeedComparisonList",
                    "actionBody": {
                        ...pobj,
                        tag: "needToOrder"
                    }
                }
                break
            case "order":
                delete pobj.listType;
                pobj.status = Number(pobj.status)
                url = '/web/opaction/order/springBoard'
                query = {
                    "actionType": "getOrdersComparisonList",
                    "actionBody": pobj
                }
                break
        }
        const data = await this.pushQiFuTong(url, query);
        return data;
    }

    async importTxNeeds(pobj) {
        let url;
        let query;
        switch (pobj.type) {
            case "biz":
                url = '/web/opreceive/need/springBoard'
                query = {
                    "actionType": "importNeeds",
                    "actionBody": {
                        "uapp_id": "53",
                        "needsArr": pobj.list
                    }
                }
                break
            case "order":
                url = '/web/opaction/order/springBoard'
                query = {
                    "actionType": "importOrders",
                    "actionBody": {
                        "uapp_id": "53",
                        "ordersArr": pobj.list
                    }
                }
                break
        }
        const data = await this.pushQiFuTong(url, query);
        return data;
    }



    // 获取一段时间内的所有日期
    getAllDate(begin, end) {
        let data = [];
        begin = Moment(begin).format("YYYY-MM-DD");
        end = Moment(end).format("YYYY-MM-DD");
        if (begin == end) {
            return [begin]
        }
        if ((new Date(end).getTime() - new Date(begin).getTime()) == 86400000) {
            return [begin, end]
        }
        let ab = begin.split("-");
        let ae = end.split("-");
        let db = new Date();
        db.setUTCFullYear(ab[0], ab[1] - 1, ab[2]);
        let de = new Date();
        de.setUTCFullYear(ae[0], ae[1] - 1, ae[2]);
        let unixDb = db.getTime();
        let unixDe = de.getTime();
        data.push(begin);
        for (let k = unixDb + 24 * 60 * 60 * 1000; k < unixDe;) {
            data.push(Moment(new Date(parseInt(k))).format("YYYY-MM-DD"));
            k = k + 24 * 60 * 60 * 1000;
        }
        data.push(end);
        return data;
    }
    judgeSize(a, b) {
        return a >= b ? (a == b ? "rgba(0, 0, 0, 0.45)" : "red") : "green"
    }
}
module.exports = BaseClient;