const BaseClient = require("./baseClient")
const system = require("../../system");
const settings = require("../../../config/settings");
const { appKey, secret } = settings;
const qualificationDao = system.getObject("db.delivery.qualificationDao");
const moment = require("moment");

/**
 * 增值电信 产品
 */
class VatClient 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             // 工信部未通过
        }
    }


    static getInstance() {
        if (!this.instance) {
            this.instance = new VatClient();
        }
        return this.instance;
    }
    /**
     * 递交材料
     * @param {*} deliverData 
     * @param {*} materials 
     */
    async submitMaterials(username, deliverData, materials) {
        const { businessLicense, materialFile, otherInformation } = materials;
        const {
            address, businessTerm, createdAt,
            enterpriseCode, legalRepresentative, name,
            registeredCapital, scopeBusiness, type
        } = businessLicense;
        const { domain, corporateName, includeForeignInvestment } = otherInformation;
        const {
            companyBasicForm, companyServiceQualityForm,
            icpCertificate, networkSecurityInformationForm,
            partnerBusinessLicense, partnerDomainCertificate,
            partnerForeignInvestment, partnerIdCardList,
            partnerLaw, partnerPlan, partnerPreviewOtherList,
            partnerSignAndStampOtherList, partnerSignOtherList,
            businessDevelopmentForm, partnerStampOtherList
        } = materialFile;

        if (deliverData.source_number === "ename") {
            await this.pushQiFuTong(username, {
                actionType: "serviceProviderNotification",
                actionBody: {
                    orderNo: deliverData.delivery_code,
                    status: 506,
                }
            });
        }

        await this.pushQiFuTong(username, {
            actionType: "serviceProviderSubmitMaterial",
            actionBody: {
                orderNo: deliverData.delivery_code,
                material: {
                    BusinessLicense: {
                        Address: address,
                        BusinessTerm: businessTerm,
                        CreatedAt: createdAt ? createdAt : undefined,
                        EnterpriseCode: enterpriseCode,
                        LegalRepresentative: legalRepresentative,
                        Name: name,
                        RegisteredCapital: registeredCapital,
                        ScopeBusiness: scopeBusiness,
                        Type: type
                    },
                    Domain: domain,
                    CorporateName: corporateName,
                    IncludeForeignInvestment: includeForeignInvestment === "是",
                    PartnerBusinessLicense: partnerBusinessLicense.url,
                    PartnerIdCardList: partnerIdCardList.map(item => item.url),
                    PartnerDomainCertificate: partnerDomainCertificate.url,
                    PartnerPreviewOtherList: (partnerPreviewOtherList && partnerPreviewOtherList.length > 0) ? partnerPreviewOtherList.map(item => item.url) : undefined,
                    PartnerPlan: partnerPlan.url,
                    PartnerForeignInvestment: partnerForeignInvestment.url,
                    PartnerLaw: partnerLaw.url,
                    IcpCertificate: icpCertificate.url,
                    BusinessDevelopmentForm: businessDevelopmentForm.url,
                    CompanyBasicForm: companyBasicForm.url,
                    CompanyServiceQualityForm: companyServiceQualityForm.url,
                    NetworkSecurityInformationForm: networkSecurityInformationForm.url,
                    PartnerSignAndStampOtherList: partnerSignAndStampOtherList.url && [partnerSignAndStampOtherList.url],
                    PartnerSignOtherList: partnerSignOtherList.url && [partnerSignOtherList.url],
                    PartnerStampOtherList: partnerStampOtherList.url && [partnerStampOtherList.url]
                }
            }
        });
    }


    /**
     * 改变 状态
     * @param {*} status 
     * @param {*} sendMessage 办理的资质文件等
     */
    async changeStatus(username, deliverData, materials = {}) {
        let status;
        switch (deliverData.delivery_status) {
            case system.SERVERSESTATUS.USERCONFIRMATIONRESOLVE:
            case system.SERVERSESTATUS.COLLECTSUCCESS:
                status = this.CIRCUITSTATUS.ACCOUNTREGISTRATION
                break
            case system.SERVERSESTATUS.ACCOUNTREGISTRATION:
                status = this.CIRCUITSTATUS.SUBMITING
                break
            case system.SERVERSESTATUS.SUBMITING:
                status = this.CIRCUITSTATUS.DISPOSEING
                break
            case system.SERVERSESTATUS.DISPOSEING:
                const qualificationData = await qualificationDao.findOne({
                    deliver_id: deliverData.id
                });
                if (qualificationData) {
                    materials.officialFileURL = qualificationData.file && qualificationData.file.url;
                    if (deliverData.source_number === "aliCloud") {
                        materials.certificateNumber = qualificationData.certificateNumber;
                        materials.certificateStartTime = moment(qualificationData.startAt).format('YYYY-MM-DD');
                        materials.certificateEndTime = moment(qualificationData.endAt).subtract(1, 'days').format('YYYY-MM-DD');
                    }
                } else {
                    if (deliverData.source_number === "aliCloud") {
                        throw new Error("请上传办理的资质证照信息");
                    }
                }
                status = this.CIRCUITSTATUS.THROUGH
                break
            case system.SERVERSESTATUS.THROUGH:
                return "SUCCESS"
            default:
                throw new Error("此状态不能手动更改");
        }
        await this.pushQiFuTong(username, {
            actionType: "serviceProviderNotification",
            actionBody: {
                orderNo: deliverData.delivery_code,
                status,
                ...materials
            }
        });
    }
}

module.exports = VatClient