var system = require("../../../system");
const http = require("http");
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const moment = require("moment");
class MaterialCtl extends CtlBase {
    constructor() {
        super("delivery", CtlBase.getServiceName(MaterialCtl));
        this.db = system.getObject("db.common.connection").getCon();
    }
    // 获取 组装 excl 文件 数据
    async waitGenerate(pobj, qobj, req) {
        const rs = await this.service.findAll({
            ifDownload: false
        }, [
            {
                model: this.db.models.deliver,
                attributes: ["product_code", "source_name", "source_number"],
            }
        ]);
        // 组装数据
        return system.getResult(rs.map(item => {
            const type = item.deliver.product_code;
            const channel = item.deliver.source_number;
            const { proposerInfo, otherMaterialsInfo, implementationPlanInfo, safetyInfo, shareholderData } = item;
            const { businessLicense, businessInformation, principalInfo, contactInfo } = proposerInfo;
            const { webApp, targetUser, profitableWay, specialApproval, serviceProjectEdi, serviceProjectIcp } = implementationPlanInfo;
            // 1. id ,type

            // 2.注册认证
            let registeredAddressData = {
                authentication: {},
                files: []
            };
            let legalRepresentative = principalInfo.filter(item => {
                return item.title === "法定代表人"
            });
            legalRepresentative = legalRepresentative.length > 0 ? legalRepresentative[0] : {};
            registeredAddressData.authentication = {
                personType: "法人",
                companyType: businessLicense.type,
                enterpriseCode: businessLicense.enterpriseCode,
                name: businessLicense.name,
                legalTypes: businessInformation.legalTypes,
                legalName: legalRepresentative.name,
                legalCertificateId: legalRepresentative.certificateId,
                legalCertificateType: legalRepresentative.certificateType,
                contactAddress: contactInfo.address
            };
            registeredAddressData.files.push(
                ...(Array.isArray(otherMaterialsInfo) ? otherMaterialsInfo.filter(item => {
                    return item.title === "营业执照";
                }) : [])
                , {
                    title: "法定代表人身份证件",
                    file: legalRepresentative.file
                });

            // 3. 发展和实施计划
            let implementationPlanData = {
                // ICP
                // EDI
                webApp: webApp,
                files: []
            };
            let serviceProject = {};
            if (type === "ICP") {
                serviceProject = {
                    releaseAndDelivery: "",
                    community: "",
                    protectiveProcessing: "",
                    interactive: "",
                    search: ""
                }
                serviceProjectIcp.map(item => {
                    switch (item.title) {
                        case "信息发布平台和递送服务":
                            serviceProject["releaseAndDelivery"] = item.value.join().replace(/其他/, item.otherValue);
                            break
                        case "信息搜索查询服务":
                            serviceProject["search"] = item.value.join().replace(/其他/, item.otherValue);
                            break
                        case "信息社区服务":
                            serviceProject["community"] = item.value.join().replace(/其他/, item.otherValue);
                            break
                        case "信息保护加工处理服务":
                            serviceProject["protectiveProcessing"] = item.value.join().replace(/其他/, item.otherValue);
                            break
                        case "信息及时交互服务":
                            serviceProject["interactive"] = item.value.join().replace(/其他/, item.otherValue);
                            break
                    }
                })
            } else if (type === 'EDI') {
                serviceProject = {
                    electronicExchange: "",
                    transactionProcessing: "",
                    dataProcessing: ""
                }
                serviceProjectEdi.map(item => {
                    switch (item.title) {
                        case "电子交换业务":
                            serviceProject["electronicExchange"] = item.value.join();
                            break
                        case "交易处理业务":
                            serviceProject["transactionProcessing"] = item.value.join();
                            break
                        case "网络/电子设备数据处理业务":
                            serviceProject["dataProcessing"] = item.value.join();
                            break
                    }
                })
            }
            implementationPlanData[type] = {
                ...serviceProject,
                targetUser: targetUser.join(),
                profitableWay: profitableWay.join()
            };
            // 专项审批项目 ICP
            if (type === "ICP") {
                implementationPlanData.files.push(...specialApproval.filter(item => {
                    return item.file && item.file.url ? true : false
                }).map(item => {
                    return {
                        file: item.file,
                        title: `专项审批项-${item.title}`
                    }
                }));
            }
            implementationPlanData.files.push(...otherMaterialsInfo.filter(item => {
                return item.title === "域名证书"
            }));

            if (type === "EDI") {
                implementationPlanData.files.push(...serviceProjectEdi.filter(item => {
                    return item.file && item.file.url ? true : false
                }).map(item => {
                    return {
                        title: item.title,
                        file: item.file
                    }
                }));
            }

            // 4. 增值电信申请表
            let licenceData = {
                licence: {
                    companyName: businessLicense.name,
                    enterpriseCode: businessLicense.enterpriseCode,
                    registeredCapital: businessLicense.registeredCapital,
                    registerAddress: businessLicense.address,
                    fixedTelephone: businessInformation.fixedTelephone,
                    workAddress: businessInformation.address,
                    zipCode: businessInformation.zipCode,
                    comapnyNature: businessInformation.comapnyNature,
                    ifListed: businessInformation.ifListed ? "是" : "否"
                },
                files: [
                    ...(Array.isArray(otherMaterialsInfo) ? otherMaterialsInfo.filter(item => {
                        return item.title === "营业执照";
                    }) : [])
                ]
            }

            // 5. 公司及人员情况
            let companyPersonnelData = {
                personnelInfo: principalInfo,
                companyInfo: {
                    bussinessDirection: businessInformation.bussinessDirection,
                    staffSize: businessInformation.staffSize,
                    businessScale: businessInformation.businessScale
                },
                files: []
            }
            companyPersonnelData.files.push(...principalInfo.filter(item => {
                return item.file && item.file.url ? true : false
            }).map(item => {
                return {
                    "title": `${item.title}身份证`,
                    file: item.file
                }
            }), ...(Array.isArray(otherMaterialsInfo) ? otherMaterialsInfo.filter(item => {
                return item.title === "社保证明文件";
            }) : []))

            // 6. 网络与信息安全
            let safetyData = {
                safety: {
                    qualification: safetyInfo.qualification,
                    responsibility: safetyInfo.responsibility
                },
                files: []
            }
            // 7. 股东信息
            let shareholdersData = {
                shareholdes: shareholderData,
                files: []
            }
            shareholdersData.files.push(...(Array.isArray(otherMaterialsInfo) ? otherMaterialsInfo.filter(item => {
                return ["股东追溯承诺书", "申请者国家企业信用信息公示系统截图"].includes(item.title);
            }) : []))
            shareholdersData.files.push(...shareholderData.filter(item => {
                return item.file && item.file.url ? true : false
            }).map(item => {
                return {
                    file: item.file,
                    title: `${item.name}身份证`
                }
            }));

            // 8. 电信业务承诺书 
            let telecommunicationServiceData = {
                files: [...(Array.isArray(otherMaterialsInfo) ? otherMaterialsInfo.filter(item => {
                    return ["依法经营电信业务承诺书"].includes(item.title);
                }) : [])]
            }

            // 9. 其他材料
            let otherMaterialsData = {
                files: [...(Array.isArray(otherMaterialsInfo) ? otherMaterialsInfo.filter(item => {
                    return ["收费方案", "服务器托管协议", "服务器托管商IDC许可证"].includes(item.title) || item.fixed === false;
                }) : [])]
            }

            return {
                id: item.id,
                type,
                channel,
                registeredAddressData,
                implementationPlanData,
                licenceData,
                companyPersonnelData,
                safetyData,
                shareholdersData,
                telecommunicationServiceData,
                otherMaterialsData,
            }
        }));
    }
    // 更新 下载 url
    async updateUrl(pobj) {
        if (!pobj.id) {
            return system.getResult(null, "id  can not be empty，100290");
        }
        if (!pobj.url) {
            return system.getResult(null, "url  can not be empty，100290");
        }
        await this.service.updateByWhere({
            ifDownload: true,
            downloadUrl: pobj.url
        }, {
            id: pobj.id,
        });
        return system.getResultSuccess();
    }

    // 返回 下载url
    async getUrl(pobj) {
        if (!pobj.deliver_id) {
            return system.getResult(null, "id  can not be empty，100290");
        }
        const rs = await this.service.findOne({ deliver_id: pobj.deliver_id }, ["downloadUrl", "ifDownload"]);
        if (!rs) {
            return system.getResult(null, "查不到数据");
        }
        return system.getResult(rs);
    }
}
module.exports = MaterialCtl;
