const system = require("../../system");
const ServiceBase = require("../sve.base");
const moment = require("moment");

class EntcompanyService extends ServiceBase {
    constructor(){
        super(ServiceBase.getDaoName(EntcompanyService));
        this.dktemplateDao = system.getObject("db.dktemplateDao");
        this.userDao = system.getObject("db.userDao");
    }

    async isExistsCompanyName(name) {
        //0-不存在，1-存在
        var company = await super.findOne({name:name});
        if(company) {
            return 1;
        }
        return 0;
    }

    async findMapByIds(ids) {
        return await this.dao.findMapByIds(ids);
    }

    async listByCondition(params) {
        var currentPage = Number(params.currentPage || 0);
        var pageSize = Number(params.pageSize || 10);

        var where = {};
        if (params.name) {
            where.name = {
                [this.db.Op.like]: "%" + params.name + "%"
            };
        }

        if(params.ownerIds && params.ownerIds.length > 0) {
            where.owner_id = {[this.db.Op.in]: params.ownerIds};
        }

        if(params.owner_id) {
            where.owner_id = params.owner_id;
        }

        var orderby = [
            ["id", 'desc']
        ];

        var attributes = ["id", "name", "sealName", "sealId", "legal", "contactName", "contactMobile", "addr", "owner_id", "created_at"];
        var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
        if (page && page.rows) {
            for(var row of page.rows) {
                this.handleDate(row, ["created_at"]);
            }
            await this.setOwner(page.rows);
        }
        return page;
    }

    async getInfo(id) {
        var attrs = ["id", "name", "sealUrl", "sealFileKey", "sealId", "legal", "phone", "addr", "owner_id", "created_at"];
        return await this.dao.model.findOne({
            where: { id: id }, attrs, raw: true
        });
    }

    async setOwner(rows) {
        if (!rows || rows.length == 0) {
            return;
        }

        var ownerIds = [];
        for (var row of rows) {
            if (row.owner_id) {
                ownerIds.push(row.owner_id);
            }
        }

        if (ownerIds.length == 0) {
            return;
        }

        var ownerMap = await this.userDao.findMapByIds(ownerIds);
        for (var row of rows) {
            if (row.owner_id) {
                row.owner = ownerMap["id_" + row.owner_id] || {};
            }
        }

        console.log(rows);
    }

    async findNamesByOwnerIds(ownerIds) {
        return await this.dao.findNamesByOwnerIds(ownerIds);
    }

    async findIdsByOwnerIds(ownerIds) {
        return await this.dao.findIdsByOwnerIds(ownerIds);
    }

    async suggest(name, ownerIds) {
        return await this.dao.suggest(name, ownerIds);
    }
}
module.exports = EntcompanyService;