const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const System = require("../../../system");
const appconfig = system.getSysConfig();
const toFtClient = require("../../../utils/toFtClient");
class DeliverybillService extends ServiceBase {
    constructor() {
        super("bizchance", ServiceBase.getDaoName(DeliverybillService));
        this.logService = system.getObject("service.bizchance.statuslogSve");
        this.fitaxschemeDao = system.getObject("db.bizchance.fitaxschemeDao");
        this.bizoptDao = system.getObject("db.bizchance.bizoptDao");
        this.operationrecordDao = system.getObject("db.bizchance.operationrecordDao");
    }

    async updateOrderStatus(pobj) {
        let deliverData = await this.dao.findOne({
            id: pobj.deliverId
        });
        if (!deliverData) {
            throw new Error("查不到此交付单");
        }
        if (deliverData.delivery_status !== system.SERVERSESTATUS.RECEIVED) {
            throw new Error("该状态下不可处理");
        }
        if (!deliverData.delivery_info.companyName) {
            throw new Error("查不到对应公司名称");
        }
        let updateResult = {};
        let { delivery_info } = deliverData;
        if (pobj.orderStaus === true) {
            updateResult = {
                delivery_info: {
                    ...delivery_info,
                    setupAt: pobj.setupAt//建账时间
                },
                delivery_status: system.SERVERSESTATUS.WAITUSERCONFIRM
            }
        }
        if (pobj.orderStaus === false) {
            updateResult = {
                delivery_status: system.SERVERSESTATUS.CLOSED,
                close_reason: pobj.note
            }
        }
        // 通过消息队列 发送 融易算 
        await toFtClient.feedbackToRys({
            ...pobj,
            bizId: deliverData.delivery_info.bizId
        });
        await this.dao.updateByWhere(updateResult, {
            id: pobj.deliverId
        });
        this.logService.insertInfo({
            flowType: system.FLOWCODE.DELIVERY,
            flowId: pobj.deliverId,
            statusCode: updateResult.delivery_status,
            clerkName: pobj.userid,
            clerkId: pobj.username
        });
        return "SUCCESS"
    }

    async setupBill(pobj) {
        let deliverData = await this.dao.findOne({
            id: pobj.deliverId
        });
        if (!deliverData) {
            throw new Error("查不到此交付单");
        }
        if (deliverData.delivery_status !== system.SERVERSESTATUS.INSERVICE) {
            throw new Error("该状态下不可建账");
        }
        if (deliverData.delivery_info.setupStatus && deliverData.delivery_info.setupStatus === system.SERVERSESTATUS.SETUP) {
            throw new Error("已建账");
        }
        // 通知 财税
        await toFtClient.addCusAccApplyInfo(deliverData, pobj);
        await this.dao.updateByWhere({
            delivery_info: {
                ...delivery_info,
                setupStatus: system.SERVERSESTATUS.SETUP,
                setupInfo: {
                    contactsName: pobj.contactsName,
                    time: pobj.time,
                    accountingType: pobj.accountingType,
                    taxpayerType: pobj.taxpayerType,
                    supplier: pobj.supplier
                }
            }
        }, {
            id: pobj.deliverId
        });
        return "SUCCESS"
    }

    async deliverInfo(pobj) {
        let result = {};
        let deliverData = await this.dao.findOne({
            id: pobj.deliverId
        });
        if (!deliverData) {
            throw new Error("查不到此交付单");
        }
        result.deliverData = {
            deliveryId: deliverData.id,                     // id
            deliveryNumber: deliverData.delivery_code,      // 交付单编号        
            companyName: deliverData.delivery_info.companyName,// 企业名称
            uscc: deliverData.delivery_info.creditCode,   //统一信用代码
            taxpayerType: deliverData.delivery_info.taxpayerType, //纳税人类型 1 一般；2 小规模
            companyBizType: deliverData.delivery_info.companyBizType,// 公司类型  1-商贸型；2-服务型；3-特殊行业；4-其他
            areaType: deliverData.delivery_info.areaType, //区域类型 city-城市       
            area: deliverData.service_address,              // 服务 地区 编码
            contactsName: deliverData.delivery_info.contactsName,// 联系人
            contactsPhone: deliverData.delivery_info.contactsPhone,// 联系电话
            owner: deliverData.delivery_man_name,//所属人
            deliveryStatus: deliverData.delivery_status,    // 交付单状态 
            setupStatus: deliverData.delivery_info.setupStatus || System.SERVERSESTATUS.NOTSETUP,//建账状态 notsetup | setup
            createdAt: deliverData.created_at,
            updatedAt: deliverData.updated_at,
            accountingType: (deliverData.delivery_info.setupInfo && deliverData.delivery_info.setupInfo.accountingType) || null //会计准侧
        }
        if (deliverData.scheme_number) {
            let schemeData = await this.fitaxschemeDao.findOne({
                solution_bizid: deliverData.scheme_number
            });
            if (schemeData) {
                result.schemeData = {
                    demandCode: schemeData.demand_code, // 需求编号
                    schemeCode: deliverData.scheme_number,//方案编号
                    // 服务类型
                    companyType: schemeData.company_type,//公司类型
                    area: schemeData.service_name,//服务地区
                    buyDuration: schemeData.buy_duration,//购买时长
                    buyNumber: schemeData.number,//购买数量
                    totalCost: schemeData.total_cost,//总计费用
                    note: schemeData.remarks//备注
                }
            }
        }
        return result
    }

    async distributionPerson(pobj) {
        let { numbers, nickName, userId, opCode, phone, type } = pobj;
        switch (type) {
            case System.FLOWCODE.DELIVERY:
                let bizDatas = await this.dao.findAll({
                    delivery_code: {
                        $in: numbers
                    }
                });
                if (bizDatas.length !== numbers.length) {
                    throw new Error("请检查单号是否正确");
                }
                await this.dao.updateByWhere({
                    delivery_man_id: userId,
                    delivery_man_opcode: opCode,
                    delivery_man_name: nickName
                }, {
                    delivery_code: {
                        $in: numbers
                    }
                });
                // 插入 流转 记录
                let logs = [];
                for (let val of bizDatas) {
                    logs.push({
                        demand_code: val.delivery_code,
                        operator: {
                            id: pobj.userid,
                            username: pobj.username
                        },
                        operation_type: "distribution",
                        operation_details: {
                            isFirst: val.delivery_man_id ? true : false,
                            fromUserId: val.delivery_man_id,
                            fromUserName: val.delivery_man_name,
                            toUserId: userId,
                            toUserName: nickName
                        },
                        order_type: System.FLOWCODE.DELIVERY
                    })
                }
                this.operationrecordDao.bulkCreate(logs);
                break
            case System.FLOWCODE.BIZ:
                let delDatas = await this.bizoptDao.findAll({
                    demand_code: {
                        $in: numbers
                    }
                });
                if (delDatas.length !== numbers.length) {
                    throw new Error("请检查单号是否正确");
                }
                return this.db.transaction(async (t) => {
                    // 更新 操作人
                    await this.bizoptDao.updateByWhere({
                        salesman_id: userId,
                        salesman_opcode: opCode,
                        salesman_phone: phone,
                        salesman_name: nickName
                    }, {
                        demand_code: {
                            $in: numbers
                        }
                    }, t);
                    // 更新 状态
                    await this.bizoptDao.updateByWhere({
                        business_status: "beforeFollowUp"
                    }, {
                        $and: [
                            {
                                demand_code: {
                                    $in: numbers
                                }
                            }, {
                                business_status: "received"
                            }
                        ]
                    }, t);
                    // 插入 流转 记录
                    let logs = [];
                    for (let val of delDatas) {
                        logs.push({
                            demand_code: val.demand_code,
                            operator: {
                                id: pobj.userid,
                                username: pobj.username
                            },
                            operation_type: "distribution",
                            operation_details: {
                                isFirst: val.salesman_id ? true : false,
                                fromUserId: val.salesman_id,
                                fromUserName: val.salesman_name,
                                toUserId: userId,
                                toUserName: nickName
                            },
                            order_type: System.FLOWCODE.BIZ
                        })
                    }
                    this.operationrecordDao.bulkCreate(logs);
                    return "success"
                });
                break
        }
        return "SUCCESS"

    }

    async insertInfo(qobj) {
        var self = this;
        return self.db.transaction(async function (t) {
            return await self.dao.insertInfo(qobj, t);
        });
    }

    async updateServer(qobj) {
        var self = this;
        var bill = await self.dao.findOneByDeliveryCodeAndBizId(qobj);
        qobj.delivery_info = JSON.parse((JSON.stringify(bill.delivery_info) + JSON.stringify(qobj.delivery_info)).replace(/}{/, ','));
        return self.db.transaction(async function (t) {
            return await self.dao.updateServer(qobj, t);
        });
    }

    //根据bizId查询deliverybill表中的所有信息
    async getInfo(pobj) {
        let result = {};
        let deliveryBillInfo = await this.dao.findByBizId(pobj);
        // console.log("gggg"+deliveryBillInfo+pobj.bizId)
        if (!deliveryBillInfo) {
            throw new Error("没有服务信息");
        }
        //封装deliverybill表数据
        result.deliveryBillInfo = {
            deliveryCode: deliveryBillInfo.delivery_code,//交付单编号
            sourceNumber: deliveryBillInfo.source_number,//渠道来源编号
            demandCode: deliveryBillInfo.demand_code,//商机编号
            skuCode: deliveryBillInfo.sku_code,//sku编号
            schemeNumber: deliveryBillInfo.scheme_number,//方案编号
            productCode: deliveryBillInfo.product_code,//产品编码
            productName: deliveryBillInfo.product_name,//产品名称
            serviceAddress: deliveryBillInfo.service_address,//服务地区
            deliveryInfo: deliveryBillInfo.delivery_info,//交付单详情
            payStatus: deliveryBillInfo.pay_status,//交付状态-虚拟字段
            vConame: deliveryBillInfo.v_coname,//联系人-虚拟字段
            vCophone: deliveryBillInfo.v_cophone,//联系电话-虚拟字段
            delivery_status: deliveryBillInfo.delivery_status,//交付单状态
            sellingPrice: deliveryBillInfo.selling_price,//交付单价格
            costPrice: deliveryBillInfo.cost_price,//成本价
            closeReason: deliveryBillInfo.close_reason,//状态为关闭原因
            facilitatorId: deliveryBillInfo.facilitator_id,//服务商id
            facilitatorName: deliveryBillInfo.facilitator_name,//服务商名称
            salesmanOpcode: deliveryBillInfo.salesman_opcode,//业务员opcode
            salesmanId: deliveryBillInfo.salesman_id,//业务员id
            salesmanName: deliveryBillInfo.salesman_name,//业务员名称
            salesmanPhone: deliveryBillInfo.salesman_phone,//业务员联系方式
            sourceName: deliveryBillInfo.source_name,//渠道名称
            vftClientId: deliveryBillInfo.v_ftClientId,//  客户ID（帐套）
            createdAt: deliveryBillInfo.created_at,//创建时间
            updatedAt: deliveryBillInfo.updated_at,//更新时间
            version: deliveryBillInfo.version,//o
            masterSourceNumber: deliveryBillInfo.master_source_number,//主来源单
            settleStatus: deliveryBillInfo.settle_status,//结算状态
            settlebillId: deliveryBillInfo.settlebill_id,//结算单id
            deliveryManId: deliveryBillInfo.delivery_man_id,//销售员id
            deliveryManName: deliveryBillInfo.delivery_man_name,//销售员姓名
            deliveryManOpcode: deliveryBillInfo.delivery_man_opcode,//销售员opcode
            bizId: pobj.bizId//融易算-服务实例id
        }
        return result;
    }
    //根据客户ID（帐套）查询deliverybill表中的所有信息
    async getInfobyClientId(pobj) {
        let result = {};
        let deliveryBillInfo = await this.dao.findByClientId(pobj);
        // console.log("gggg"+deliveryBillInfo+pobj.bizId)
        if (!deliveryBillInfo) {
            throw new Error("没有服务信息");
        }
        //封装deliverybill表数据
        result.deliveryBillInfo = {
            deliveryCode: deliveryBillInfo.delivery_code,//交付单编号
            sourceNumber: deliveryBillInfo.source_number,//渠道来源编号
            demandCode: deliveryBillInfo.demand_code,//商机编号
            skuCode: deliveryBillInfo.sku_code,//sku编号
            schemeNumber: deliveryBillInfo.scheme_number,//方案编号
            productCode: deliveryBillInfo.product_code,//产品编码
            productName: deliveryBillInfo.product_name,//产品名称
            serviceAddress: deliveryBillInfo.service_address,//服务地区
            deliveryInfo: deliveryBillInfo.delivery_info,//交付单详情
            payStatus: deliveryBillInfo.pay_status,//交付状态-虚拟字段
            vConame: deliveryBillInfo.v_coname,//联系人-虚拟字段
            vCophone: deliveryBillInfo.v_cophone,//联系电话-虚拟字段
            delivery_status: deliveryBillInfo.delivery_status,//交付单状态
            sellingPrice: deliveryBillInfo.selling_price,//交付单价格
            costPrice: deliveryBillInfo.cost_price,//成本价
            closeReason: deliveryBillInfo.close_reason,//状态为关闭原因
            facilitatorId: deliveryBillInfo.facilitator_id,//服务商id
            facilitatorName: deliveryBillInfo.facilitator_name,//服务商名称
            salesmanOpcode: deliveryBillInfo.salesman_opcode,//业务员opcode
            salesmanId: deliveryBillInfo.salesman_id,//业务员id
            salesmanName: deliveryBillInfo.salesman_name,//业务员名称
            salesmanPhone: deliveryBillInfo.salesman_phone,//业务员联系方式
            sourceName: deliveryBillInfo.source_name,//渠道名称
            vftClientId: deliveryBillInfo.v_ftClientId,//  客户ID（帐套）
            createdAt: deliveryBillInfo.created_at,//创建时间
            updatedAt: deliveryBillInfo.updated_at,//更新时间
            version: deliveryBillInfo.version,//o
            masterSourceNumber: deliveryBillInfo.master_source_number,//主来源单
            settleStatus: deliveryBillInfo.settle_status,//结算状态
            settlebillId: deliveryBillInfo.settlebill_id,//结算单id
            deliveryManId: deliveryBillInfo.delivery_man_id,//销售员id
            deliveryManName: deliveryBillInfo.delivery_man_name,//销售员姓名
            deliveryManOpcode: deliveryBillInfo.delivery_man_opcode,//销售员opcode
            bizId: pobj.bizId//融易算-服务实例id
        }
        return result;
    }


    /**
     * 通过 财税给的数据 组装  融易算 所需 数据格式 发送
     */
    async fromFtToRys(pobj) {
        let { option, data } = pobj;
        let deliverData = await this.dao.findOne({
            $or: [
                {
                    v_creditCode: data.creditCode
                },
                {
                    v_ftClientId: data.customerId
                }
            ]
        });
        if (!deliverData) {
            throw new Error("查不到 对应服务单")
        }
        const bizId = deliverData.delivery_info.bizId;
        switch (option) {
            case "1": // 创建 套餐
                await this.dao.updateByWhere({
                    delivery_info: {
                        ...deliverData.delivery_info,
                        ftClientId: data.customerId,
                    }
                }, {
                    id: deliverData.id
                });
                await toFtClient.accountingFinishToRys(bizId, data);
                break
            case "2": // 结账 
                break
            case "3": // 报税
                await toFtClient.taxSubmitToRys(bizId, data);
                break
            default:
                throw new Error("option 错误")
        }
    }
}
module.exports = DeliverybillService;