const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const moment = require("moment");
const pushQft = require("../../../utils/toqifutongClient")
const TOQFT = require("../../../utils/toQft");


class CompanycaseService extends ServiceBase {
    constructor() {
        super("delivery", ServiceBase.getDaoName(CompanycaseService));
        this.cacheinfoDao = system.getObject("db.delivery.cacheinfoDao");
        this.deliveryDao = system.getObject("db.delivery.deliverDao");
        this.newmaterialDao = system.getObject("db.delivery.newmaterialDao");
        this.statuslogDao = system.getObject("db.bizchance.statuslogDao");
        this.qualificationDao = system.getObject("db.delivery.qualificationDao");
    }

    async receiveSubmitMaterialsFormBaidu(data){
        console.log(`mmmmmmmmmmmm接受到百度推送过来的工商材料信息`+JSON.stringify(data))
        const actionBody = data.d
        const deliverData = await this.deliveryDao.findOne({
            demand_code: actionBody.who.serviceId,
            product_code: 'companyCase'
        });

        if (!deliverData) {
            throw new Error("查不到此交付单");
        }

        // 将百度推送过来的数据入库
        const deliverInfo = deliverData.delivery_info
        deliverInfo.channelMaterials = {
            who: actionBody.who,
            com: actionBody.com,
            receiver: actionBody.receiver,
            shareholders: actionBody.shareholders,
            members: actionBody.members
        }
        
        return this.db.transaction(async (t) => {
            const cacheInf =  await this.cacheinfoDao.findOne({
                deliver_id: deliverData.id
            });

            let pobj = null
            if(cacheInf){
                let cacheInfo = cacheInf.cache_info;
                cacheInfo.companyInfo.channelMaterials = {
                    who: actionBody.who,
                    com: actionBody.com,
                    receiver: actionBody.receiver,
                    shareholders: actionBody.shareholders,
                    members: actionBody.members
                }

                pobj = {
                    deliver_id: deliverData.id,
                    cache_info: cacheInfo
                }
            }else{
                pobj = {
                    deliver_id: deliverData.id,
                    cache_info:{
                        companyInfo: {
                            companyName:actionBody.com.names[0],
                            spareName: [""],
                            serviceArea: "",
                            channelMaterials: {
                                who: actionBody.who,
                                com: actionBody.com,
                                receiver: actionBody.receiver,
                                shareholders: actionBody.shareholders,
                                members: actionBody.members
                            }
                        },
                        materialFile:{
                            applicationFormUrl:{},
                            registDocumentsUrl:{}
                        }
                    }
                }
            }

            await this.cacheinfoDao.createOrUpdate(pobj, t);
            await this.newmaterialDao.createOrUpdate(pobj, t);
            // 更新公司名称
            await this.deliveryDao.updateByWhere({
                company_name: actionBody.com.names[0],
                delivery_info: {
                    ...deliverInfo,
                    companyName: actionBody.com.names[0]
                }
            }, {
                delivery_code: deliverData.delivery_code
            }, t);
            return "SUCCESS"
        });
    }

    async submitMaterials(pobj, qobj, req) {
        const deliverData = await this.deliveryDao.findOne({
            id: pobj.deliver_id
        });
        if (!deliverData) {
            throw new Error("查不到此交付单");
        }
        if(deliverData.delivery_info && deliverData.delivery_info.channelMaterials){
            console.log(`【提交材料】+++++new走百度新接口提交材料${pobj.deliver_id}`)
            await TOQFT.getClientByType(deliverData.product_code).submitMaterialsNew(pobj.username, deliverData, pobj.cache_info);
            if([system.SERVERSESTATUS.COLLECTING].includes(deliverData.delivery_status)){
                console.log(`【提交材料】+++++new走百度新接口更新工商注册状态${pobj.deliver_id}`)
                await TOQFT.getClientByType(deliverData.product_code).updateGongshangRegStatus(pobj.username, deliverData, system.SERVERSESTATUS.AUDITING);
            }
        }else{
            console.log(`+++++old走百度老接口提交材料${pobj.deliver_id}`)
            await TOQFT.getClientByType(deliverData.product_code).submitMaterials(pobj.username, deliverData, pobj.cache_info);
        }

        return this.db.transaction(async (t) => {
            await this.cacheinfoDao.createOrUpdate(pobj, t);
            await this.newmaterialDao.createOrUpdate(pobj, t);
            if ([system.SERVERSESTATUS.COLLECTING].includes(deliverData.delivery_status)) {
                let status = system.SERVERSESTATUS.AUDITING;
                await this.deliveryDao.updateByWhere({
                    delivery_status: status
                }, {
                    id: pobj.deliver_id
                }, t);
                this.statuslogDao.create({
                    flow_type: system.FLOWCODE.DELIVERY,
                    flow_id: pobj.deliver_id,
                    status_code: status,
                    salesman_id: pobj.userid,
                    salesman_name: pobj.username
                });
            }
            // 更新公司名称
            if (pobj && pobj.cache_info && pobj.cache_info.companyInfo && pobj.cache_info.companyInfo.companyName) {
                await this.deliveryDao.updateByWhere({
                    company_name: pobj.cache_info.companyInfo.companyName,
                    delivery_info: {
                        ...deliverData.delivery_info,
                        companyName: pobj.cache_info.companyInfo.companyName
                    }
                }, {
                    delivery_code: deliverData.delivery_code
                }, t);
            }
            return "SUCCESS"
        });
    }

    async companyCaseDeliverCommonSubmitMaterials(pobj, qobj, req) {
        const deliverData = await this.deliveryDao.findOne({
            id: pobj.deliver_id
        });
        if (!deliverData) {
            throw new Error("查不到此交付单");
        }
        await this.newmaterialDao.createOrUpdate(pobj);
        return "SUCCESS"
    }

    /**
     * 工商信息初审未通过、工商信息提交中、工商局审核未通过、工商局审核通过、补正复审中、补正复审未通过、刻章中、刻章完成、证件已上传、证件已邮寄
     * 
     * @param {*} pobj 
     * @param {*} qobj 
     * @param {*} req 
     */
    async updateGongshangStatus(pobj, qobj, req) {
        console.log(`更新百度工商注册新流程状态开始:`+JSON.stringify(pobj));
        const deliverData = await this.deliveryDao.findOne({
            id: pobj.id
        });
        if (!deliverData) {
            throw new Error("查不到此交付单");
        }

        if(!deliverData.delivery_info){
            throw new Error("交付单详情为空");
        }

        if(!deliverData.delivery_info.channelMaterials){
            throw new Error("百度未同步公司注册申请材料");
        }

        if(!deliverData.delivery_info.channelMaterials.who){
            throw new Error("who参数为空");
        }

        let statusArr = [
            "EXPERT_AUDIT_FAILED", // 工商信息初审未通过
            "ICB_SUBMITTING",// 工商信息提交中
            "ICB_AUDIT_FAILED",// 工商局审核未通过
            "ICB_AUDIT_PASS",// 工商局审核通过
            "ICB_RE-AUDITING",// 补正复审中
            "ICB_RE-AUDIT_FAILED",// 补正复审未通过
            "ENGRAVING",// 刻章中
            "ENGRAVED",// 刻章完成
            "LICENSE_UPLOADED",// 证件已上传
            "LICENSE_POSTED"// 证件已邮寄
        ]

        let isExist = statusArr.includes(pobj.status)
        if(!isExist){
            throw new Error("状态非法");
        }

        let licenseUrl = null;
        let expressNum = null;
        if("LICENSE_UPLOADED" == pobj.status){
            if(!pobj.licenseUrl || pobj.licenseUrl== ''){
                throw new Error("营业执照地址不能为空");
            }
            licenseUrl = pobj.licenseUrl;
        }else if("LICENSE_POSTED" == pobj.status){
            if(!pobj.expressNum || pobj.expressNum== ''){
                throw new Error("快递号不能为空");
            }
            expressNum = pobj.expressNum;
        }

        // 更新百度工商注册流程状态
        let client =  TOQFT.getClientByType(deliverData.product_code);

        console.log(">>>>开始调用百度接口更新工商状态接口："+pobj.id)
        const res = await client.updateGongshangRegStatus(pobj.username, deliverData, pobj.status);

        if("LICENSE_UPLOADED" == pobj.status){
            console.log(">>>>开始调用百度接口更新回传营业执照："+pobj.id)
            await client.submitLicense(pobj.username,deliverData,licenseUrl)
        }else if("LICENSE_POSTED" == pobj.status){
            console.log(">>>>开始调用百度接口更新回传刻章信息："+pobj.id)
            await client.submitEngraving(pobj.username,deliverData,licenseUrl)
        }

        return "SUCCESS"
    }

    async changeDeliveryStatus(pobj, qobj, req) {
        const deliverData = await this.deliveryDao.findOne({
            id: pobj.id
        });
        if (!deliverData) {
            throw new Error("没有此交付单");
        }
        let updateData = {};
        let status;
        let materials = {};
        switch (deliverData.delivery_status) {
            case system.SERVERSESTATUS.RECEIVED:
                switch (deliverData.product_code) {
                    case system.SERVICECODE.COMPANYCASE:
                    case system.SERVICECODE.REGADDRCASE1:
                        status = system.SERVERSESTATUS.COLLECTING;
                        break
                    case system.SERVICECODE.TAXCASE:
                    case system.SERVICECODE.OPENBANKACCOUNTCASE:
                        status = system.SERVERSESTATUS.SUCCESS;
                        break
                    case system.SERVICECODE.AGENTCASE1:
                        status = system.SERVERSESTATUS.SERVICEING;
                        break
                    default:
                        throw new Error("异常操作");
                }
                break
            case system.SERVERSESTATUS.COLLECTING: //  收集材料
                const materialData = await this.newmaterialDao.findOne({
                    deliver_id: deliverData.id
                })
                if (materialData && materialData.materialInfo && materialData.materialInfo.file && materialData.materialInfo.file.url) {
                    materials = {
                        deliverContent: {
                            deliverMaterialUrl: materialData.materialInfo.file.url
                        }
                    }
                }
                status = system.SERVERSESTATUS.SERVICEING;
                break
            case system.SERVERSESTATUS.AUDITING: // 工商审核环节
                status = system.SERVERSESTATUS.ENGRAVING;
                break
            case system.SERVERSESTATUS.ENGRAVING: // 刻章环节
                status = system.SERVERSESTATUS.SUCCESS;
                break
            case system.SERVERSESTATUS.SERVICEING: // 服务中
                status = system.SERVERSESTATUS.SUCCESS;
                break
            default:
                throw new Error("此状态手动不能更改");
        }
        if (
            (system.SERVICECODE.REGADDRCASE1 === deliverData.product_code &&
                deliverData.delivery_status === system.SERVERSESTATUS.SERVICEING) ||
            (system.SERVICECODE.AGENTCASE1 === deliverData.product_code &&
                deliverData.delivery_status === system.SERVERSESTATUS.RECEIVED)
        ) {
            if (!pobj.startTime) {
                throw new Error("请传入 服务的起止时间")
            } else {
                const delivery_info = {
                    ...deliverData.delivery_info,
                    startTime: system.SERVICECODE.REGADDRCASE1 === deliverData.product_code
                        ? moment(pobj.startTime).startOf("day").format('YYYY-MM-DD HH:mm:ss')
                        : moment(pobj.startTime).startOf("month").format('YYYY-MM-DD HH:mm:ss'),
                    endTime: system.SERVICECODE.REGADDRCASE1 === deliverData.product_code
                        ? moment(pobj.startTime).add(12, 'month').add(-1, 'day').endOf("day").format('YYYY-MM-DD HH:mm:ss')
                        : moment(pobj.startTime).add(11, 'month').endOf("month").format('YYYY-MM-DD HH:mm:ss'),
                }
                updateData = {
                    delivery_status: status,
                    delivery_info
                }
                deliverData.delivery_info = delivery_info;
            }
        } else {
            updateData = {
                delivery_status: status
            }
        }

        if(system.SERVICECODE.COMPANYCASE == deliverData.product_code && deliverData.delivery_info.channelMaterials){
            console.log(`【更新交付单状态】new 调用百度新接口更新工商注册状态.(id=${pobj.id})`)
            await TOQFT.getClientByType(deliverData.product_code).updateGongshangRegStatus(pobj.username, deliverData, status);
        }else{
            console.log(`【更新交付单状态】old 调用百度老接口更新工商注册状态.(id=${pobj.id})`)
            await TOQFT.getClientByType(deliverData.product_code).changeStatus(pobj.username, deliverData, materials);
        }

        await this.deliveryDao.updateByWhere(updateData, {
            id: pobj.id
        })
        this.statuslogDao.create({
            flow_type: system.FLOWCODE.DELIVERY,
            flow_id: pobj.id,
            status_code: status,
            salesman_id: pobj.userid,
            salesman_name: pobj.username
        });
        return "SUCCESS"
    }


    async companyCaseDeliverCommonSubmitQualification(pobj, qobj, req) {
        const deliverData = await this.deliveryDao.findOne({
            id: pobj.deliver_id
        });
        if (!deliverData) {
            throw new Error("查不到此交付单");
        }
        await this.qualificationDao.createOrUpdate(pobj);
        return "SUCCESS"
    }
}
module.exports = CompanycaseService;
