const ServiceBase = require("../../sve.base");
const ydzPush = require("./../../../utils/ydzClient");
const settings = require("./../../../../config/settings");
const System = require("../../../system");
const moment = require("moment");
const TOQFT = require("../../../utils/toQft");

class ServicebillService extends ServiceBase {
    constructor() {
        super("agriculture", ServiceBase.getDaoName(ServicebillService));
        this.accountsetSve = System.getObject("service.agriculture.accountsetSve");
        this.accountingSve = System.getObject("service.agriculture.accountingSve");
    }

    async findAndCountAll(obj) {
        var self = this;
        console.log('---------------findAndCountAll ------------------');
        const apps = await super.findAndCountAll(obj);
        return apps;
    }

    async updateStatus(obj) {
        obj.id = obj.bizId;
        const res = await this.dao.update(obj);
        return res;
    }

    async updateAndPush(obj) { //服务单分配会计推企服通回传会计信息、并推易代账新建帐套
        const res = await this.dao.update(obj);
        const findService = await this.dao.findOne({ bizId: obj.bizId });
        const findAccount = await this.accountingSve.findOne({ id: obj.accountantEmployeeId });
        if (findService) {
            //推企服通回传会计信息;
            const data = this.mappingQiFuTong(findService, findAccount);
            await TOQFT.getClientByType("pannong").pushQiFuTong(obj.username, { "actionType": "accountingInfo", "actionBody": data });

            //分配会计并推送易代账新建帐套 
            const setData = this.mappingYDZ(findService);
            const pushYDZResult = await ydzPush.pushYiDaZhang(setData)

            //新建本地帐套
            const createData = this.mappingSetToLocalCreate(pushYDZResult, setData.accountBook);
            delete createData.id; //删除易代账返回ID
            const createAccountset = await this.accountsetSve.create(createData);
            console.log(createAccountset);

            //推送企服通帐套信息
            const toQFTSetData = this.mappingSetToQiFuTong(pushYDZResult, findService);
            await TOQFT.getClientByType("pannong").pushQiFuTong(obj.username, { "actionType": "booksInfo", "actionBody": toQFTSetData });
        } else {
            console.log('查无此单：' + obj.bizId);
        }
        return res;
    }

    async updateAndFeedback(obj) { //服务单审核并推送企服通
        const res = await this.dao.update(obj);
        const findOne = await this.dao.findOne({ id: obj.id });
        let backData = {};
        if (res && findOne) {
            backData.bizId = findOne.bizId;
            backData.auditResult = findOne.status;
            backData.orderNo = findOne.orderNo;
            if (backData.auditResult == 1) { //审核通过
                backData.serviceStartTime = moment(findOne.updated_at).format('YYYY-MM-DD');
                backData.serviceEndTime = moment(moment(findOne.updated_at).add(findOne.quantity, 'years')).format('YYYY-MM-DD');
            }
            if (backData.auditResult == 2) { // 审核未通过
                backData.note = findOne.feedback_notes;
            }
            //推送企服通
            const result = await TOQFT.getClientByType("pannong").pushQiFuTong(obj.username, { "actionType": "feedback", "actionBody": backData });
            if (result.code == 200) {
                return result;
            } else {
                console.log(result);
                throw new Error(result);
            }
        } else {
            console.log('未查询到此服务单' + obj.bizId);
            throw new Error('未查询到此服务单' + obj.bizId);
        }
    }
    mappingQiFuTong(findService, findAccount) {
        let data = {
            bizId: findService.bizId,
            accInfo: {
                accCode: findAccount.accCode,
                accName: findAccount.accName,
                accaddress: findAccount.accaddress,
                // workingYears: findAccount.workingYears,
                accCredentials: findAccount.accCredentials,
                accAccount: findAccount.accAccount,
                accountingName: findAccount.name,
                note: findAccount.note || '无'
            }
        }
        return data;
    }
    mappingYDZ(findService) {
        let setData = {};
        setData.accountBook = {};
        for (let key in findService.companyInfo) {
            setData[key] = findService.companyInfo[key];
            if (key == 'acctgSystemId' || key == 'taxpayerTypeEnum') {
                setData.accountBook[key] = findService.companyInfo[key];
            }
        }
        setData.custName = findService.companyInfo.corpName; //客户名称
        setData.accountantEmployeeId = findService.accountantAgentAccountId; //所属会计 易代账ID
        setData.isBuild = true;
        setData.accountBook.name = findService.companyInfo.corpName; //账套名称
        setData.accountBook.openingPeriod = `${moment().year()}${moment().month()+1}`; //开账期间 当年当月，格式是 “YYYYMM” 
        return setData;
    }
    mappingSetToQiFuTong(setInfo, findService) {
        let toQFTSetData = {
            bizId: findService.bizId,
            custId: setInfo.custId,
            bookId: setInfo.assocTenantId,
            bkDomainName: setInfo.bkDomainName,
            contactName: findService.companyInfo.companyName,
            contactMobile: setInfo.customer.contactMobile,
            timeUnit: findService.timeUnit,
            quantity: findService.quantity,
            note: findService.note || '无',
            companyInfo: findService.companyInfo
        }
        return toQFTSetData;
    }
    mappingSetToLocalCreate(setInfo, accountBook) {
        let createData = {};
        for (let key in setInfo.customer) {
            if (key == 'tenantId') {
                createData.manageId = setInfo.customer[key];
            }
            createData[key] = setInfo.customer[key];
        }
        createData.accountBook = accountBook;
        return createData;
    }
}
module.exports = ServicebillService;