const BaseClient = require("./baseClient")
const settings = require("../../../config/settings");
const system = require("../../system");
const { appKey, secret } = settings;
/**
 * 工商 产品
 */
class GongshangClient extends BaseClient {
    constructor() {
        super(appKey, secret, "/web/action/regapi/springBoard");
        this.instance = null;
        this.productType = [
            {
                zzbType: system.SERVICECODE.COMPANYCASE,
                qftType: "GSZZ"
            }, {
                zzbType: system.SERVICECODE.OPENBANKACCOUNTCASE,
                qftType: "YHKH"
            }, {
                zzbType: system.SERVICECODE.TAXCASE,
                qftType: "SWBD"
            }, {
                zzbType: system.SERVICECODE.REGADDRCASE1,
                qftType: "DZFW"
            }, {
                zzbType: system.SERVICECODE.AGENTCASE1,
                qftType: "DLJZ"
            },
        ];
        this.CIRCUITSTATUS = {
            RECEIVED: 701,//已接单
            COLLECTING: 702,//材料收集环节
            AUDITING: 703,//工商审核环节
            ENGRAVING: 704,//刻章环节
            SUCCESS: 705,//已完成
            SERVICEING: 706//服务中
        }
    }

    static getInstance() {
        if (!this.instance) {
            this.instance = new GongshangClient();
        }
        return this.instance;
    }

    // ===================== 20220425 百度工商注册新流程 接口  start =====================
    /**
     * 百度工商注册新流程公司注册完成后，供应商将营业执照回传百度
     */
    async submitLicense(username, deliverData, licenseUrl){
        let pushData = {
            deliveryId: deliverData.id,
            who: deliverData.delivery_info.channelMaterials.who,
            licenseUrl: licenseUrl
        }

        console.log(`开始调用百度回传营业执照接口(deliveryId=${deliverData.id})，请求参数：`+JSON.stringify(pushData))
        const res = await this.pushQiFuTong(username, {
            actionType: "submitGongshangLicense",
            actionBody: pushData
        });
        console.log(`结束调用百度回传营业执照接口(deliveryId=${deliverData.id})，返回结果：`+JSON.stringify(res))
        return res;
    }

    /**
     * 百度工商注册新流程：刻章环节，供应商使用此接口同步刻章信息（需多次调用）
     */
    async submitEngraving(username, deliverData, status, expressNum){
        let pushData = {
            deliveryId: deliverData.id,
            who: deliverData.delivery_info.channelMaterials.who,
            content: "公章、财务章、合同章",
            status: status,
            expressNum: expressNum
        }

        console.log(`开始调用百度回传刻章信息接口(deliveryId=${deliverData.id})，请求参数：`+JSON.stringify(pushData))
        const res = await this.pushQiFuTong(username, {
            actionType: "submitGongshangEngraving",
            actionBody: pushData
        });
        console.log(`结束调用百度回传刻章信息接口(deliveryId=${deliverData.id})，返回结果：`+JSON.stringify(res))
        return res;
    }


   /**
     * 百度工商注册新流程: 状态需要及时更新，方便用户了解当前进度。
     */
    async updateGongshangRegStatus(username, deliverData, updateStatus){
        let updateBaiduGongshangStatus = null;
        if(system.SERVERSESTATUS.AUDITING == updateStatus){ // 收集材料环节
            updateBaiduGongshangStatus = 'ICB_AUDITING' // 工商局审核中
        }else if(system.SERVERSESTATUS.ENGRAVING == updateStatus){ // 刻章环节
            updateBaiduGongshangStatus = 'COLLECTING_ENGRAVE_MATERIAL' // 刻章资料收集中
        }else {
            console.log(`【百度工商注册新流程】deliveryId: ${deliverData.id} 交付单状态为:${updateStatus} 不需要通知百度`)
            return ;
        }

        console.log(`【百度工商注册新流程】deliveryId: ${deliverData.id} 交付单状态为:${updateStatus} 告知百度状态为:${updateBaiduGongshangStatus}`)

        let pushData = {
            deliveryId: deliverData.id,
            who: deliverData.delivery_info.channelMaterials.who,
            status: updateStatus
        }

        console.log(`开始调用百度更新工商状态接口(deliveryId=${deliverData.id})，请求参数：`+JSON.stringify(pushData))
        const res = await this.pushQiFuTong(username, {
            actionType: "updateGongshangRegStatus",
            actionBody: pushData
        });
        console.log(`结束调用百度更新工商状态接口(deliveryId=${deliverData.id})，返回结果：`+JSON.stringify(res))
        return res;
    }

    /**
     * 百度工商注册新流程，供应商变更用户申请材料
     * @param {*} username 
     * @param {*} deliverData 
     * @param {*} cacheInfo 
     * @returns 
     */
    async submitMaterialsNew(username, deliverData, cacheInfo){
        let pushData = {
            deliveryId: deliverData.id,
            deliverContent: {
                who: cacheInfo.companyInfo.channelMaterials.who,  // 目标
                com: cacheInfo.companyInfo.channelMaterials.com, // 公司基本信息
                receiver: cacheInfo.companyInfo.channelMaterials.receiver, // 邮寄地址
                shareholders: cacheInfo.companyInfo.channelMaterials.shareholders, // 股东信息
                members: cacheInfo.companyInfo.channelMaterials.members // 主要人员信息
            }
        }

        console.log(`开始调用百度供应商变更用户申请材料(deliveryId=${deliverData.id})，请求参数：`+JSON.stringify(pushData))
        const res = await this.pushQiFuTong(username, {
            actionType: "submitGongshangMaterial",
            actionBody: pushData
        });
        console.log(`结束调用百度供应商变更用户申请材料(deliveryId=${deliverData.id})，返回结果：`+JSON.stringify(res))
        return res;
    }

    // ===================== 20220425 百度工商注册新流程 接口  end =====================

    async submitMaterials(username, deliverData, materials) {
        const { companyInfo, materialFile, } = materials;
        let { applicationFormUrl, registDocumentsUrl } = materialFile;
        let { companyName, spareName, companyProperties, fullAddress, engagedIndustry,
            businessScope, operatingPeriod, addressType, taxpayerType, serviceArea } = companyInfo;
        // if (serviceArea.length == 2) {
        //     if (serviceArea[1] === "市辖区") {
        //         serviceArea = serviceArea[0];
        //     } else {
        //         serviceArea = serviceArea[1];
        //     }
        // } else {
        //     serviceArea = undefined;
        // }
        let status;
        switch (deliverData.delivery_status) {
            case system.SERVERSESTATUS.COLLECTING: // 工商审核环节
                status = this.CIRCUITSTATUS.AUDITING;
                break
            case system.SERVERSESTATUS.AUDITING: // 工商审核环节
                status = this.CIRCUITSTATUS.AUDITING;
                break
            case system.SERVERSESTATUS.ENGRAVING: // 刻章环节
                status = this.CIRCUITSTATUS.ENGRAVING;
                break
            case system.SERVERSESTATUS.SUCCESS:
                return "SUCCESS"
            default:
                throw new Error("此状态手动不能更改");
        }
        let pushData = {
            orderNo: deliverData.delivery_code,
            consultType: deliverData.delivery_info.bizType || "GSREG",
            status,
            deliverContent: {
                applicationFormUrl: applicationFormUrl.url,
                registDocumentsUrl: registDocumentsUrl.url,
                baseInfo: {},
                companyInfo: {
                    companyName,
                    spareName: spareName.filter(item => {
                        return item;
                    }),
                    companyProperties,
                    addressType,
                    fullAddress,
                    taxpayerType,
                    serviceArea,
                    engagedIndustry,
                    businessScope,
                    operatingPeriod
                }
            },
        }
        if (deliverData.is_package) {
            pushData.productType = this.productType.find((item) => {
                return item.zzbType === deliverData.product_code
            }).qftType;
        }
        await this.pushQiFuTong(username, {
            actionType: "regUpdateOrderStatus",
            actionBody: pushData
        });
    }

    async changeStatus(username, deliverData, materials = {}) {
        let status;
        switch (deliverData.delivery_status) {
            case system.SERVERSESTATUS.RECEIVED:
                switch (deliverData.product_code) {
                    case system.SERVICECODE.COMPANYCASE:
                    case system.SERVICECODE.REGADDRCASE1:
                        status = this.CIRCUITSTATUS.COLLECTING;
                        break
                    case system.SERVICECODE.TAXCASE:
                    case system.SERVICECODE.OPENBANKACCOUNTCASE:
                        status = this.CIRCUITSTATUS.SUCCESS;
                        break
                    case system.SERVICECODE.AGENTCASE1:
                        status = this.CIRCUITSTATUS.SERVICEING;
                        break
                    default:
                        throw new Error("异常操作");
                }
                break
            case system.SERVERSESTATUS.COLLECTING: //  收集材料
                status = this.CIRCUITSTATUS.SERVICEING;
                break
            case system.SERVERSESTATUS.AUDITING: // 工商审核环节
                status = this.CIRCUITSTATUS.ENGRAVING;
                break
            case system.SERVERSESTATUS.ENGRAVING: // 刻章环节
                status = this.CIRCUITSTATUS.SUCCESS;
                break
            case system.SERVERSESTATUS.SERVICEING: // 服务中
                status = this.CIRCUITSTATUS.SUCCESS;
                break
            default:
                throw new Error("此状态手动不能更改");
        }
        let pushData = {
            orderNo: deliverData.delivery_code,
            status,
            consultType: deliverData.delivery_info.bizType || "GSREG",
        }
        // 套餐 判断
        if (deliverData.is_package) {
            pushData.productType = this.productType.find((item) => {
                return item.zzbType === deliverData.product_code
            }).qftType;
        }

        // 代理记账、地址服务 的截止时间
        if (
            (system.SERVICECODE.REGADDRCASE1 === deliverData.product_code &&
                deliverData.delivery_status === system.SERVERSESTATUS.SERVICEING) ||
            (system.SERVICECODE.AGENTCASE1 === deliverData.product_code &&
                deliverData.delivery_status === system.SERVERSESTATUS.RECEIVED)
        ) {
            pushData.startTime = new Date(deliverData.delivery_info.startTime).getTime() / 1000;
            pushData.endTime = new Date(deliverData.delivery_info.endTime).getTime() / 1000;
        }

        // 材料信息 
        if (Object.keys(materials).length) {
            pushData = {
                ...pushData,
                ...materials
            }
        }


        await this.pushQiFuTong(username, {
            actionType: "regUpdateOrderStatus",
            actionBody: pushData
        });
    }
}

module.exports = GongshangClient