const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
class DeliverybillService extends ServiceBase {
    constructor() {
        super("bizchance", ServiceBase.getDaoName(DeliverybillService));
        this.materialDao = system.getObject("db.bizchance.materialDao");
        this.logDao = system.getObject("db.bizchance.statuslogDao");
        this.cacheDao = system.getObject("db.bizchance.cacheinfoDao");
    }

    async statBizDeliverySettleAmountBySp(settleStatus) {
        let params = {}
        let where = settleStatus != "" ? `where settle_status='${settleStatus}'` : ''

        params.group = {
            byFields: ['facilitator_name'],
            actionType: 'sum',
            aggField: 'cost_price',
            aliasField: ' as  chanceCount',
            tblName: 'delivery_bill',
            where: where,
            having: '',
        }
        let s = await this.dao.statGroupBy(params, null)
        return s
    }
    async statBizDeliveryCountBySp(deliverStatus, betweenTime) {
        let params = {}
        let where = deliverStatus != "" ? `where delivery_status='${deliverStatus}'` : ''
        if (deliverStatus == "handling") {
            where = `where delivery_status  not in ('received', 'success', 'closed')`
        }
        params.group = {
            byFields: ['facilitator_name'],
            actionType: 'count',
            aggField: 'id',
            aliasField: ' as  chanceCount',
            tblName: 'delivery_bill',
            where: where,
            having: '',
        }
        if (betweenTime.length > 0) {
            params.group.where = `${params.group.where} ${params.group.where ? 'AND' : "WHERE"} (created_at BETWEEN '${betweenTime[0]}' AND '${betweenTime[1]}')`
        }
        let s = await this.dao.statGroupBy(params, null)
        return s
    }
    async statBizDelivery(companyId, opath, username, userid, betweenTime) {
        // 时间 筛选
        let andWhere = [];
        if (betweenTime.length > 0) {
            andWhere.push({
                "created_at": { [this.db.Op.between]: betweenTime }
            })
        }
        //如果当前登录人是平台,返回所有商机
        let waittoHandledCount = 0//received
        let handlingCount = 0
        let finishedCount = 0//success
        let closedCount = 0//closed
        let toSettle = 0
        let toSettleAmount = 0
        let settling = 0
        let settlingAmount = 0
        let settled = 0
        let settledAmount = 0
        if (companyId == 1) {
            waittoHandledCount = await this.dao.findCount({ where: { delivery_status: 'received', [this.db.Op.and]: andWhere } })
            handlingCount = await this.dao.findCount({ where: { delivery_status: { [this.db.Op.notIn]: ['received', 'success', 'closed'] }, [this.db.Op.and]: andWhere } })
            finishedCount = await this.dao.findCount({ where: { delivery_status: 'success', [this.db.Op.and]: andWhere } })
            closedCount = await this.dao.findCount({ where: { delivery_status: 'closed', [this.db.Op.and]: andWhere } })
            toSettle = await this.dao.findCount({ where: { settle_status: 'waittosettle', [this.db.Op.and]: andWhere } })
            toSettleAmount = await this.dao.findSum('cost_price', { where: { settle_status: 'waittosettle', [this.db.Op.and]: andWhere } })
            settling = await this.dao.findCount({ where: { settle_status: 'settling', [this.db.Op.and]: andWhere } })
            settlingAmount = await this.dao.findSum('cost_price', { where: { settle_status: 'settling', [this.db.Op.and]: andWhere } })
            settled = await this.dao.findCount({ where: { settle_status: 'settled', [this.db.Op.and]: andWhere } })
            settledAmount = await this.dao.findSum('cost_price', { where: { settle_status: 'settled', [this.db.Op.and]: andWhere } })
        } else {
            let opathstr = ''
            if (opath) {
                opathstr = opath
                waittoHandledCount = await this.dao.findCount({ where: { delivery_status: 'received', salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                handlingCount = await this.dao.findCount({ where: { delivery_status: { [this.db.Op.notIn]: ['received', 'success', 'closed'] }, salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                finishedCount = await this.dao.findCount({ where: { delivery_status: 'success', salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                closedCount = await this.dao.findCount({ where: { delivery_status: 'closed', salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                toSettle = await this.dao.findCount({ where: { settle_status: 'waittosettle', salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                toSettleAmount = await this.dao.findSum('cost_price', { where: { settle_status: 'waittosettle', salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                settling = await this.dao.findCount({ where: { settle_status: 'settling', salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                settlingAmount = await this.dao.findSum('cost_price', { where: { settle_status: 'settling', salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                settled = await this.dao.findCount({ where: { settle_status: 'settled', salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                settledAmount = await this.dao.findSum('cost_price', { where: { settle_status: 'settled', salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
            } else {
                waittoHandledCount = await this.dao.findCount({ where: { delivery_status: 'received', 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                handlingCount = await this.dao.findCount({ where: { delivery_status: { [this.db.Op.notIn]: ['received', 'success', 'closed'] }, 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                finishedCount = await this.dao.findCount({ where: { delivery_status: 'success', 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                closedCount = await this.dao.findCount({ where: { delivery_status: 'closed', 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                toSettle = await this.dao.findCount({ where: { settle_status: 'waittosettle', 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                toSettleAmount = await this.dao.findSum('cost_price', { where: { settle_status: 'waittosettle', 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                settling = await this.dao.findCount({ where: { settle_status: 'settling', 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                settlingAmount = await this.dao.findSum('cost_price', { where: { settle_status: 'settling', 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                settled = await this.dao.findCount({ where: { settle_status: 'settled', 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
                settledAmount = await this.dao.findSum('cost_price', { where: { settle_status: 'settled', 'facilitator_id': companyId, [this.db.Op.and]: andWhere } })
            }

        }
        //成单率
        let allHandled = finishedCount + closedCount
        //如果当前登录人不是平台,那么需要按照opath查询
        return {
            waittoHandledCount: waittoHandledCount,
            handlingCount: handlingCount,
            finishedCount: finishedCount,
            closedCount: closedCount,
            allHandled: allHandled,
            toSettle: toSettle,
            toSettleAmount: toSettleAmount ? toSettleAmount : 0,
            settling: settling,
            settlingAmount: settlingAmount ? settlingAmount : 0,
            settled: settled,
            settledAmount: settledAmount ? settledAmount : 0
        }

    }
    //为租户自己给交付打标记，表示中台已经给予结算，自己记账用
    //租户自己临时记录结算情况
    async settleApplyForTacent(ids, uid, uname, spname, spid) {
        var self = this
        return this.db.transaction(async function (t) {
            //先按照ids查询出交付单的合计服务成本
            let d = await self.dao.customQuery("select sum(cost_price) as settleAmount from delivery_bill where id in (:idstr)", { idstr: ids });
            // let settleAmount=await self.dao.model.sum("cost_price",{where:{id:{[self.db.Op.In]:['40','41','42']}},transaction:t})
            let settleAmount = d[0].settleAmount
            settleAmount = isNaN(settleAmount) ? 0 : settleAmount
            let settlecode = await self.getBusUid("JSD")
            let settleObj = {
                code: settlecode,
                settle_amount: settleAmount,
                creator_id: uid,
                creator: uname,
                facilitator_name: spname,
                facilitator_id: spid,
                isPayedStatus: false,
                auditedStatus: true,
                payer_id: uid,
                payer: uname,
                auditor_id: uid,
                auditor: uname
            }
            //生成结算单，结算单状态直接更改为已经付款
            let newentity = await self.db.models.settlebill.create(settleObj, { transaction: t })
            //然后按照ids更新交付单的状态为结算中，更新结算单的id到交付单表
            for (let idstr of ids) {
                let up = await self.dao.updateByWhere({
                    settle_status: 'settling',
                    settlebill_id: newentity.id
                }, { id: idstr }, t);
            }
            return newentity
        });

    }
    async settleApply(ids, uid, uname, spname, spid) {
        var self = this
        return this.db.transaction(async function (t) {
            //先按照ids查询出交付单的合计服务成本
            let d = await self.dao.customQuery("select sum(cost_price) as settleAmount from delivery_bill where id in (:idstr)", { idstr: ids });
            // let settleAmount=await self.dao.model.sum("cost_price",{where:{id:{[self.db.Op.In]:['40','41','42']}},transaction:t})
            let settleAmount = d[0].settleAmount
            settleAmount = isNaN(settleAmount) ? 0 : settleAmount
            let settlecode = await self.getBusUid("JSD")
            let settleObj = {
                code: settlecode,
                settle_amount: settleAmount,
                creator_id: uid,
                creator: uname,
                facilitator_name: spname,
                facilitator_id: spid
            }
            //生成结算单，结算单状态为待审核
            let newentity = await self.db.models.settlebill.create(settleObj, { transaction: t })
            //然后按照ids更新交付单的状态为结算中，更新结算单的id到交付单表
            for (let idstr of ids) {
                let up = await self.dao.updateByWhere({
                    settle_status: 'settling',
                    settlebill_id: newentity.id
                }, { id: idstr }, t);
            }
            return newentity
        });
    }
    async findAndCountAll(obj) {
        var self = this;
        const apps = await self.dao.findAndCountAll(obj);
        return apps;
    }

    async findInfoByDeliverCode(qobj) {//*根据交付单编号获取交付单详情*/
        return await this.dao.findInfoByDeliverCode(qobj);
    }

    async updateStatusByDeliverCode(qobj) {//* 根据交付单编号更新交付单状态 */
        var self = this;
        return self.db.transaction(async function (t) {
            return await self.dao.updateStatusByDeliverCode(qobj, t);
        });
    }
    /*更新业务员信息*/
    async updateSalesmanInfoByDeliverCode(qobj){
        var self = this;
        return self.db.transaction(async function (t) {
            return await self.dao.updateSalesmanInfoByDeliverCode(qobj, t);
        });
    }
    async updateInfoByDeliverCode(qobj) {//*更新交付单信息 */
        console.log("--------------------------------------------------------------------------------------------------------------------------------------");
        var self = this;
        return self.db.transaction(async function (t) {
            return await self.dao.updateInfoByDeliverCode(qobj, t);
        });
    }

    async insertInfo(qobj) {//*插入交付单信息*/从队列取数据的时候用
        var self = this;
        return self.db.transaction(async function (t) {
            return await self.dao.insertInfo(qobj, t);
        });
    }

    async insertInfoall(pobj) {//*插入交付单信息,大事务*/从队列取数据的时候用
        var self = this;
        return await self.db.transaction(async function (t) {
            var res = await self.dao.insertInfo(pobj);//插入交付单列表
            pobj.deliverId = res.id;
            //插入暂存
            if (pobj.cacheInfo && (pobj.businessType == "companyCase" || pobj.businessType == "psCase")) {
                await self.cacheDao.insertInfo(pobj);
            }
            var logInfo = {
                "flowType": "DELIVERY",
                "flowId": res.id,
                "statusCode": res.delivery_status,
                "statusReason": res.close_reason,
                "clerkName": res.salesman_name,
                "clerkId": res.salesman_id
            }
            await self.logDao.insertInfo(logInfo);//插入状态日至表
            await self.materialDao.insertInfo(pobj);//插入材料信息
            return system.getResultSuccess();
        });
    }

}
module.exports = DeliverybillService;