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



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

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

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

const getLoginByUserName = async (mobile = 'icp-deliver', appKey, secret) => {
    const token = await getAppTokenByAppKey(appKey, secret);
    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 && item.file.url
            }).map(item => {
                return item.file.url
            })
        ),
        ...(
            shareholderData.filter(item => {
                return item.file && 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 && PartnerPlan.file.url;

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

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

    //  打包上传 推送
    let PartnerPreviewOtherList = [
        ...otherMaterialsInfo.filter(item => {
            return item.file && item.file.url || false
        }).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_name, {
        actionType: "serviceProviderSubmitMaterial",
        actionBody: {
            orderNo: deliverData.delivery_code,             //订单号 必填
            material: {                                     //材料信息 
                Domain,                                     //备案域名必填
                CorporateName,                              //法人名称必填
                CompanyName: CorporateName,
                IncludeForeignInvestment,                   //必填
                PartnerBusinessLicense,                     //必填
                PartnerIdCardList,                          //相关人员证书必填
                PartnerDomainCertificate,                   //必填
                PartnerPreviewOtherList,                    //合作方递交其他供预览的件，只能传递ZIP包
                PartnerPlan,
                PartnerForeignInvestment,
                PartnerLaw,
            }
        }
    });
}


/**
 * 文网文 递交材料,状态变更
      601: "完成账户注册",
      602: "服务商提交资料",
      603: "服务商完成提交资料到⼯信部",
      604: "⼯商部已受理",
      605: "⼯商部不予受理",
      606: "⼯商部通过",
      607: "⼯商部未通过"
 */
const wangwenSubmitOption = async (deliverData, materials) => {
    const channelType = {
        "wangwen": "esp.wangwen",
        "food": "esp.food"
    };
    let req = {};
    switch (deliverData.delivery_status) {
        case system.SERVERSESTATUS.COLLECTING:
        case system.SERVERSESTATUS.USERCONFIRMATIONREJECT:
            let { basicInfo, materialList } = materials;
            let extInfo = {};

            for (let val in basicInfo) {
                if (basicInfo[val]) {
                    extInfo[val] = basicInfo[val];
                }
            }
            for (let val of materialList) {
                if (val.files || val.files.length > 0) {
                    let urls = [];
                    for (let file of val.files) {
                        if (file && file.url) {
                            urls.push(file.url);
                        }
                    }
                    if (urls.length > 0) {
                        extInfo[val.key] = urls
                    }
                }
            }
            req = {
                "ApplicationStatus": 601,
                "extInfo": JSON.stringify(extInfo)
            }
            break
        case system.SERVERSESTATUS.USERCONFIRMATIONRESOLVE:
            req.ApplicationStatus = 602;
            break
        case system.SERVERSESTATUS.ACCOUNTREGISTRATION:
            req.ApplicationStatus = 603;
            break
        case system.SERVERSESTATUS.SUBMITING:
            req.ApplicationStatus = 604;
            break
        case system.SERVERSESTATUS.DISPOSEING:
            req.ApplicationStatus = 606;
            break
        default:
            throw new Error("此状态手动不能更改");
    }


    await pushQiFuTong(deliverData.salesman_name, {
        actionType: "serviceSubmitOption",
        actionBody: {
            "channelType": channelType[deliverData.product_code],
            "orderNo": deliverData.delivery_code,
            "extInfo": "{}",
            ...req,
        }
    });
}

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

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

/**
 * 易名关闭交付单
 * @param {*} deliverData 
 * @param {*} sendMessage 关闭理由
 */
const enamecloseDelivery = async (deliverData, sendMessage = {}) => {
    await pushQiFuTong(deliverData.salesman_name, {
        actionType: "eNameCloseOrder",
        actionBody: {
            orderNo: deliverData.delivery_code,         //订单号 必填
            ...sendMessage
        }
    });
}

/**
 * 批量创建商机
 * @param {*} data 
 */
const batchCreateBiz = async (data) => {
    const header = await getLoginByUserName('18911818357', "201912031344", "7cbb846246874167b5c7e01cd0016c88");
    await pushQueue({
        "actionType": "produceData",// Y 功能名称
        "actionBody": {
            "pushUrl": "http://center-channel-service/web/opreceive/need/springBoard",//"http://192.168.200.232:8002/testCallback" || Y 推送地址
            "actionType": "needBatchUpload",// Y 推送地址接收时的功能名称
            "notifyUrl": "http://paas-service.newtime/entService/order/springBoard",// N 推送成功后通知的Url                 
            "identifyCode": "batchCreateBiz",// Y 操作的业务标识
            "messageBody": data,
            "headData": {
                ...header,
            }
        },
        "requestId": uuidv4() // N 请求id
    })
}


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

/**
 * 发送请求
 * @param {*} url 
 * @param {*} data 
 */
const postRequest = async (url, data, headers = {}) => {
    try {
        console.log("推送启服通请求数据 ------- ");
        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("启服通返回数据 ------- ");
        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)
    }
}

/**
 * 推送 队列 方法
 * @param {*} data 
 */
const pushQueue = async (data) => {
    try {
        console.log("推送消息队列请求数据 ------- ");
        console.log(JSON.stringify(data))
        let result = await axios.post(queueUrl, data);
        result = result.data;
        console.log("消息队列返回数据 ------- ");
        console.log(result);
        if (result.status === 1) {
            return result.data
        } else {
            throw new Error(result.message)
        }
    } catch (err) {
        console.log("------ 消息队列err -----");
        console.log(err)
        throw (err)
    }
}

module.exports = {
    submitMaterials,
    ALISTATUS,
    changeStatus,
    closeDelivery,
    batchCreateBiz,
    wangwenSubmitOption,
    enamecloseDelivery
}