const BaseClient = require("./baseClient")
const settings = require("../../../config/settings");
const system = require("../../system");
const moment = require("moment");
const qualificationDao = system.getObject("db.delivery.qualificationDao");
const { appKey, secret } = settings;
/**
 * 通用资质类 产品
 */
class CommonVatClient extends BaseClient {
    constructor() {
        super(appKey, secret, "/web/action/qcapi/springBoard");
        this.instance = null;
        this.CIRCUITSTATUS = {
            ACCOUNTREGISTRATION: 507,   // 完成账户注册
            SUBMITING: 508,             // 提交材料到工信部
            DISPOSEING: 509,            // 工信部已受理
            DISPOSEINGFAIL: 510,        // 工信不予受理
            THROUGH: 511,               // 工信部通过
            THROUGHFAIL: 512             // 工信部未通过
        }
        this.newmaterialDao = system.getObject("db.delivery.newmaterialDao");
        this.qualificationDao = system.getObject("db.delivery.qualificationDao");
    }


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

    /**
     * 递交材料
     * @param {*} deliverData
     * @param {*} materials
     */
    async submitMaterials(username, deliverData, materials) {
        const params={
            username,
            deliverData,
            materials,
        }
        console.log(`【commonVatClient-submitMaterials】递交材料 方法入参,(deliveryId=${deliverData.id})，请求参数：`+JSON.stringify(params))
        // 如果办理材料为空，则查询数据库
        let businessLicense = {};
        let recipientInfo = {};
        let applyMaterial = {}; //办理材料
        let acceptNotifyFileUrl = ''; // 受理通知书url
        let certificateFileUrl = ''; // 证书文件url

        let status;
        switch (deliverData.delivery_status) {
            case system.SERVERSESTATUS.COLLECTING: // 收集材料中
            case system.SERVERSESTATUS.USERCONFIRMATIONRESOLVE:
            case system.SERVERSESTATUS.COLLECTSUCCESS: // 完成材料收集
            case system.SERVERSESTATUS.ACCOUNTREGISTRATION: // 完成账号注册
                status = this.CIRCUITSTATUS.ACCOUNTREGISTRATION  // =>507
                break
            case system.SERVERSESTATUS.SUBMITING:  // 完成递交材料
                status = this.CIRCUITSTATUS.SUBMITING // =>508
                break
            case system.SERVERSESTATUS.DISPOSEING: // 工信部已受理
                status = this.CIRCUITSTATUS.THROUGH // => 509
                break
            case system.SERVERSESTATUS.THROUGH: // 工信部已通过
            case system.SERVERSESTATUS.SUCCESS: // 服务已完成
                status = this.CIRCUITSTATUS.THROUGH // => 511
                break
            default:
                throw new Error("状态错误");
        }


        if(!materials || Object.keys(materials).length == 0){
            const materialData = await this.newmaterialDao.findOne({
                deliver_id: deliverData.id,
            });

            if(materialData && materialData.materialInfo && materialData.materialInfo.businessLicense){
                businessLicense = materialData.materialInfo.businessLicense;
            }

            if(materialData && materialData.materialInfo && materialData.materialInfo.recipientInfo){
                recipientInfo = materialData.materialInfo.recipientInfo;
            }

            if(materialData && materialData.materialInfo && materialData.materialInfo.materialFile &&  materialData.materialInfo.materialFile.applyMaterial){
                applyMaterial = materialData.materialInfo.materialFile.applyMaterial;
            }
        }else{
            if( materials.businessLicense){
                businessLicense = materials.businessLicense;
            }

            if( materials.recipientInfo){
                recipientInfo = materials.recipientInfo;
            }

            if(materials.materialFile &&  materials.materialFile.applyMaterial){
                applyMaterial = materials.materialFile.applyMaterial;
            }
        }

        const qualificationData = await this.qualificationDao.findOne({
            deliver_id: deliverData.id
        });

        if(qualificationData){
            if(qualificationData.acceptNotifyFile&&qualificationData.acceptNotifyFile.url){
                acceptNotifyFileUrl = qualificationData.acceptNotifyFile.url;
            }

            if(qualificationData.file&&qualificationData.file.url){
                certificateFileUrl = qualificationData.file.url
            }
        }

        const pushParams = {
            orderNo: deliverData.delivery_code,
            companyName:  businessLicense.name != null && businessLicense.name != undefined && businessLicense.name != '' ? businessLicense.name: null,
            applyMaterial: applyMaterial.url !=null && applyMaterial.url != undefined && applyMaterial.url!=''? applyMaterial.url: null,
            user: {
                name: recipientInfo.name != null && recipientInfo.name != undefined && recipientInfo.name !=''? recipientInfo.name: null,
                phone: recipientInfo.phone != null && recipientInfo.phone != undefined && recipientInfo.phone !='' ? recipientInfo.phone: null,
                addr: recipientInfo.addr != null &&recipientInfo.addr != undefined  && recipientInfo.addr !=''? recipientInfo.addr: null,
            },
            acceptNotifyFile: acceptNotifyFileUrl != null && acceptNotifyFileUrl != undefined && acceptNotifyFileUrl != '' ? acceptNotifyFileUrl:null, // 受理通知书
            certificateFile: certificateFileUrl!=null && certificateFileUrl!=undefined && certificateFileUrl != '' ? certificateFileUrl:null,// 证书文件
            expressNum: recipientInfo.expressNum!=null && recipientInfo.expressNum!=undefined && recipientInfo.expressNum != '' ? recipientInfo.expressNum:null,
            status: status,
        };

        console.log(`【commonVatClient-submitMaterials】开始调用启服通 递交材料 接口(deliveryId=${deliverData.id})，请求参数：`+JSON.stringify(pushParams))

        const res = await this.pushQiFuTong(username, {
            actionType: "serviceProviderNotification",
            actionBody: pushParams
        });

        console.log(`【commonVatClient-submitMaterials】结束调用启服通 递交材料 接口(deliveryId=${deliverData.id})，请求参数：${JSON.stringify(pushParams)} `)
        // system.execLogs(`请求启服通`, {url, data, headers }, '交付请求', result, null)

    }

    /**
     * 改变 状态
     * @param {*} status
     * @param {*} sendMessage 办理的资质文件等
     */
    async changeStatus(username, deliverData, materials = {}) {
        const params ={
            username,
            deliverData,
            materials
        }
        console.log(`【commonVatClient-changeStatus】改变状态 方法入参,(deliveryId=${deliverData.id})，请求参数：`+JSON.stringify(params))

        let status;
        switch (deliverData.delivery_status) {
            case system.SERVERSESTATUS.USERCONFIRMATIONRESOLVE:
            case system.SERVERSESTATUS.COLLECTSUCCESS: // 完成收集材料 变更为 完成账号注册
                status = this.CIRCUITSTATUS.ACCOUNTREGISTRATION // =>507
                break
            case system.SERVERSESTATUS.ACCOUNTREGISTRATION: // 完成账号注册 变更为 完成递交材料
                status = this.CIRCUITSTATUS.SUBMITING // => 508
                break
            case system.SERVERSESTATUS.SUBMITING: // 完成递交材料 变更为 工信部已受理
                status = this.CIRCUITSTATUS.DISPOSEING // => 509
                break
            case system.SERVERSESTATUS.DISPOSEING: // 工信部已受理 变更为 工信部已通过
                status = this.CIRCUITSTATUS.THROUGH // => 511
                break
            case system.SERVERSESTATUS.THROUGH:
                return "SUCCESS"
            default:
                throw new Error("此状态不能手动更改");
        }

        // 如果办理材料为空，则查询数据库
        let businessLicense = {};
        let recipientInfo = {};
        let applyMaterial = {}; //办理材料
        let acceptNotifyFileUrl = ''; // 受理通知书url
        let certificateFileUrl = ''; // 证书文件url

        if(!materials || Object.keys(materials).length == 0){
            const materialData = await this.newmaterialDao.findOne({
                deliver_id: deliverData.id,
            });

            if(materialData && materialData.materialInfo && materialData.materialInfo.businessLicense){
                businessLicense = materialData.materialInfo.businessLicense;
            }

            if(materialData && materialData.materialInfo && materialData.materialInfo.recipientInfo){
                recipientInfo = materialData.materialInfo.recipientInfo;
            }

            if(materialData && materialData.materialInfo && materialData.materialInfo.materialFile &&  materialData.materialInfo.materialFile.applyMaterial){
                applyMaterial = materialData.materialInfo.materialFile.applyMaterial;
            }
        }

        const qualificationData = await this.qualificationDao.findOne({
            deliver_id: deliverData.id
        });

        if(qualificationData){
            if(qualificationData.acceptNotifyFile&&qualificationData.acceptNotifyFile.url){
                acceptNotifyFileUrl = qualificationData.acceptNotifyFile.url;
            }

            if(qualificationData.file&&qualificationData.file.url){
                certificateFileUrl = qualificationData.file.url
            }
        }

        const pushParams = {
            orderNo: deliverData.delivery_code,
            companyName: businessLicense.name != null && businessLicense.name != undefined && businessLicense.name != '' ? businessLicense.name: null,
            applyMaterial: applyMaterial.url !=null && applyMaterial.url != undefined && applyMaterial.url!='' ? applyMaterial.url: null,
            user: {
                name: recipientInfo.name != null && recipientInfo.name != undefined && recipientInfo.name !=''? recipientInfo.name: null,
                phone: recipientInfo.phone != null && recipientInfo.phone != undefined && recipientInfo.phone !='' ? recipientInfo.phone: null,
                addr: recipientInfo.addr != null &&recipientInfo.addr != undefined  && recipientInfo.addr !=''? recipientInfo.addr: null,
            },
            acceptNotifyFile: acceptNotifyFileUrl != null && acceptNotifyFileUrl != undefined && acceptNotifyFileUrl != '' ? acceptNotifyFileUrl:null, // 受理通知书
            certificateFile: certificateFileUrl!=null && certificateFileUrl!=undefined && certificateFileUrl != '' ? certificateFileUrl:null,// 证书文件
            expressNum: recipientInfo.expressNum!=null && recipientInfo.expressNum!=undefined && recipientInfo.expressNum != '' ? recipientInfo.expressNum:null,
            status: status
        };

        console.log(`【commonVatClient-changeStatus】开始调用启服通提交材料接口 ,(deliveryId=${deliverData.id})，请求参数：`+JSON.stringify(pushParams))

        await this.pushQiFuTong(username, {
            actionType: "serviceProviderNotification",
            actionBody: pushParams
        });

        console.log(`【commonVatClient-changeStatus】结束调用启服通提交材料接口 ,(deliveryId=${deliverData.id})，请求参数：${JSON.stringify(pushParams)} `)

    }
}

module.exports = CommonVatClient