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);
    }


    //根据渠道编码获取渠道信息（用于媒体聚合页移动端）
    async getSourceChannelInfo(pobj){
        if(!pobj || !pobj.actionBody){
            return system.getResultSuccess(-100,"参数错误");
        }
        if(!pobj.actionBody.code){
            return system.getResultSuccess(-101,"来源渠道编码错误");
        }
        var channelinfo = await this.dao.model.findOne({
            attributes:["code","name"],
            where:{code:pobj.actionBody.code},raw:true
        });
        if(!channelinfo || !channelinfo.code){
            return system.getResultFail(-300,"未知渠道")
        }
        return system.getResultSuccess(channelinfo);
    }
}

module.exports = LaunchchannelService;