const axios = require("axios");
const settings = require("../../config/settings");
const system = require("../system");
const centerChannelUrl = settings.centerChannelUrl();
const qifutongUrl = settings.qifutongUrl();
const { appKey, secret } = settings;
const OSS = system.getObject("util.ossClient");


axios.defaults.timeout = 3 * 1000; // 4s

const ALISTATUS = {
    ACCOUNTREGISTRATION: 507,   // 完成账户注册
    SUBMITING: 508,             // 提交材料到工信部 
    DISPOSEING: 509,            // 工信部已受理
    DISPOSEINGFAIL: 510,        // 工信不予受理
    THROUGH: 511,               // 工信部通过
    THROUGHFAIL: 512             // 工信部未通过
}

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

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

/**
 * 递交材料
 * @param {*} deliverData 
 * @param {*} materials 
 */
const submitMaterials = async (deliverData, materials) => {
    let { delivery_info: { serviceName } } = deliverData;
    let { proposerInfo: { principalInfo, businessLicense }, shareholderData, otherMaterialsInfo, implementationPlanInfo: { webApp, serviceProjectEdi, serviceProjectIcp, specialApproval } } = materials;

    let Domain = webApp[0].domain;
    let CorporateName = businessLicense.name;
    let IncludeForeignInvestment = ["含外资", "全外资"].includes(serviceName);

    let PartnerBusinessLicense = otherMaterialsInfo.find(item => {
        return item.title === '营业执照'
    });
    PartnerBusinessLicense = PartnerBusinessLicense && PartnerBusinessLicense.file.url


    let PartnerIdCardList = [
        ...(
            principalInfo.filter(item => {
                return item.file.url
            }).map(item => {
                return item.file.url
            })
        ),
        ...(
            shareholderData.filter(item => {
                return item.file.url
            }).map(item => {
                return item.file.url
            })
        )
    ];


    let PartnerDomainCertificate = otherMaterialsInfo.find(item => {
        return item.title === '域名证书'
    });
    PartnerDomainCertificate = PartnerDomainCertificate && PartnerDomainCertificate.file.url;

    let PartnerPlan = otherMaterialsInfo.find(item => {
        return item.title === '收费方案'
    });
    PartnerPlan = PartnerPlan && PartnerPlan.file.url;

    let PartnerForeignInvestment = otherMaterialsInfo.find(item => {
        return item.title === '股东追溯承诺书'
    });
    PartnerForeignInvestment = PartnerForeignInvestment && PartnerForeignInvestment.file.url;

    let PartnerLaw = otherMaterialsInfo.find(item => {
        return item.title === '依法经营电信业务承诺书'
    });
    PartnerLaw = PartnerLaw && PartnerLaw.file.url;

    //  打包上传 推送
    let PartnerPreviewOtherList = [
        ...otherMaterialsInfo.map(item => {
            return {
                url: item.file.url, //文件的oss存储路径 (必填)
                name: item.title, // 文件名 (可选, 不需要填扩展名)
                foldPath: '材料清单/'//(可选, 文件在压缩包中的存储路径)
            }
        }),
        ...serviceProjectEdi.filter(item => {
            return item.file && item.file.url || false
        }).map(item => {
            return {
                url: item.file.url,
                name: item.title,
                foldPath: '拟开展服务项目/'
            }
        }),
        ...specialApproval.filter(item => {
            return item.file && item.file.url || false
        }).map(item => {
            return {
                url: item.file.url,
                name: item.title,
                foldPath: '专项审批项目/'
            }
        }),
    ];

    let partnerPreviewOtherUrl = await OSS.batchDownloadAndZip(PartnerPreviewOtherList, `${deliverData.delivery_code}_${CorporateName}_供预览文件`);
    PartnerPreviewOtherList = [partnerPreviewOtherUrl];
    await pushQiFuTong(deliverData.salesman_phone, {
        actionType: "serviceProviderSubmitMaterial",
        actionBody: {
            orderNo: deliverData.delivery_code,             //订单号 必填
            material: {                                     //材料信息 
                Domain,                                     //备案域名必填
                CorporateName,                              //法人名称必填
                IncludeForeignInvestment,                   //必填
                PartnerBusinessLicense,                     //必填
                PartnerIdCardList,                          //相关人员证书必填
                PartnerDomainCertificate,                   //必填
                PartnerPreviewOtherList,                    //合作方递交其他供预览的件，只能传递ZIP包
                PartnerPlan,
                PartnerForeignInvestment,
                PartnerLaw,
            }
        }
    });
}

/**
 * 改变 状态
 * @param {*} status 
 * @param {*} sendMessage 办理的资质文件等
 */
const changeStatus = async (deliverData, status, sendMessage = {}) => {
    await pushQiFuTong(deliverData.salesman_phone, {
        actionType: "serviceProviderNotification",
        actionBody: {
            orderNo: deliverData.delivery_code,         //订单号 必填
            status,                                //交付状态 必填
            // officialFileURL: ""                         //官文url 非必填
            ...sendMessage
        }
    });
}

/**
 * 关闭交付单
 * @param {*} deliverData 
 * @param {*} sendMessage 关闭理由
 */
const closeDelivery = async (deliverData, sendMessage = {}) => {
    await pushQiFuTong(deliverData.salesman_phone, {
        actionType: "closeOrderDelivery",
        actionBody: {
            orderNo: deliverData.delivery_code,         //订单号 必填
            // officialFileURL: ""                      //官文url 非必填
            ...sendMessage
        }
    });
}



/**
 * 推送到 启服通
 * @param {*} mobile 
 * @param {*} data 
 */
const pushQiFuTong = async (mobile, data) => {
    const header = await getLoginByUserName(mobile);
    await postRequest(`${qifutongUrl}/web/action/qcapi/springBoard`, data, header);
}



/**
 * 发送请求
 * @param {*} url 
 * @param {*} data 
 */
const postRequest = async (url, data, headers = {}) => {
    try {
        console.log("推送启服通请求数据 ------- ");
        console.log(JSON.stringify(data))
        let result = await axios.post(url, data, {
            headers: {
                'Content-Type': 'application/json',
                ...headers
            }
        });
        result = result.data;
        console.log("启服通返回数据 ------- ");
        console.log(result);
        if (result.status === 0) {
            return result.data
        } else {
            throw new Error(result.msg)
        }
    } catch (err) {
        console.log("------ 启服通err -----");
        console.log(err)
        throw (err)
    }
}




module.exports = {
    submitMaterials,
    ALISTATUS,
    changeStatus,
    closeDelivery
}