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

class LaunchchannelService extends ServiceBase {
    constructor() {
        super("configmag", ServiceBase.getDaoName(LaunchchannelService));
        this.templatelinkSve = system.getObject("service.template.templatelinkSve");
    }

    /**
     * 根据company_id 和 code 去重
     * @param pobj
     * @returns {Promise<{msg: string, data: *, bizmsg: string, status: number}|{msg: *, data: *, status: *}>}
     */
    async createChannel(pobj) {
        if (!pobj.company_id) {
            return system.getResultFail(-1, 'company_id can not be empty');
        }
        if (!pobj.name) {
            return system.getResultFail(-1, 'name can not be empty');
        }
        if (!pobj.code) {
            return system.getResultFail(-1, 'code can not be empty');
        }
        let whereParams = {
            code: pobj.code,
            company_id: pobj.company_id
        }
        let searchResult = await this.findOne(whereParams, []);
        if (searchResult) {
            return system.getResultFail(-1,'渠道已存在，请勿重复添加');
        }
        let channelData = {
            name: pobj.name,
            code: pobj.code,
            user_id: pobj.userid,
            user_name: pobj.username,
            company_id: pobj.company_id
        }
        let result = await this.create(channelData);
        return system.getResult(result);
    }

    /**
     * 编辑渠道
     * @param pobj
     * @returns {Promise<void>}
     */
    async updateChannel(pobj){
        let link = await this.templatelinkSve.findAll({channel_code:pobj.code,is_enabled:1},[]);
        if(link.length>0){
            return system.getResultFail(-1,'该业务正在投放中，不能修改');
        }
        let up = await this.update(pobj);
        return system.getResult(up);
    }


    /**
     * 删除
     * @param pobj
     * @returns {Promise<void>}
     */
    async deleteChannel(pobj){
        let channael = await this.findOne({id:pobj.id},['code'])
        let link = await this.templatelinkSve.findAll({channel_code:channael.code},[]);
        if(link.length>0){
            return system.getResultFail(-1,'该业务正在投放中，不能删除');
        }
        let de = await this.delete(pobj);
        return system.getResult(de);
    }
}

module.exports = LaunchchannelService;