const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const sha256 = require("sha256");
class TemplateinfoService extends ServiceBase {
  constructor() {
    super("template", ServiceBase.getDaoName(TemplateinfoService));
    this.templatelinkDao = system.getObject("db.template.templatelinkDao")
    this.redisClient = system.getObject("util.redisClient");
  }

  async findByCompanyId(obj){
    if(obj.company_id){
      obj.search.company_id = obj.company_id;
    }
    var res = await this.dao.findAndCountAll(obj);
    return system.getResultSuccess(res);
  }
  /**
   * 创建模板
   * @param {*} pobj 
   */
  async createTemplate(pobj){
    var ab = {};
    var code = await this.getBusUid("mt");//自动生成模板编码
    var name = "营销模板";//模板名称
    ab.code = code;
    ab.name = name;
    ab.user_id=pobj.userid;
    ab.user_name=pobj.username;
    ab.company_id=pobj.company_id;
    ab.is_enabled=0;
    var res = await this.create(ab);
    return system.getResultSuccess(res);
  }
  /**
   * 根据模板编码获取模板信息
   * 编辑模板时使用此接口
   * @param {*} pobj 
   */
  async findOneByCode(pobj){
    var ab = pobj;
    if(!ab){
      return system.getResultFail(-100,"参数错误");
    }
    if(!ab.code){
      return system.getResultFail(-101,"模板编码不能为空");
    }
    var templateInfo = await this.dao.model.findOne({
      where:{code:ab.code},raw:true
    });
    return system.getResultSuccess(templateInfo);
  }
  async getTemplateInfoById(pobj){
    var ab = pobj;
    if(!ab){
      return system.getResultFail(-100,"参数错误");
    }
    if(!ab.id){
      return system.getResultFail(-101,"模板ID不能为空");
    }
    var templateInfo = await this.dao.model.findOne({
      where:{id:ab.id},raw:true
    });
    return system.getResultSuccess(templateInfo);
  }
  async setTemplateBusinessId(pobj){
    var ab = pobj;
    if(!ab){
      return system.getResultFail(-100,"参数错误");
    }
    if(!ab.id){
      return system.getResultFail(-101,"模板ID不能为空");
    }
    if(!ab.business_code){
      return system.getResultFail(-102,"商品ID不能为空");
    }
    await this.dao.update({id:ab.id,business_code:ab.business_code});
    var templateInfo = await this.dao.model.findOne({
      where:{id:ab.id},raw:true
    });
    return system.getResultSuccess(templateInfo);
  }
  /**
   * 根据模板编码获取模板信息(模板调用)
   * 编辑模板时使用此接口
   * @param {*} pobj 
   */
  async getTemplateInfoByCode(pobj){
    var ab = pobj.actionBody;
    if(!ab){
      return system.getResultFail(-100,"参数错误");
    }
    if(!ab.code){
      return system.getResultFail(-101,"模板编码不能为空");
    }
    var templateInfo = await this.dao.model.findOne({
      where:{code:ab.code},raw:true
    });
    return system.getResultSuccess(templateInfo);
  }
  /**
   * 编辑模板
   * @param {*} pobj 
   */
  async editTemplateContent(pobj){
    var ab = pobj.actionBody;
    var xctx = pobj.xctx;
    if(!ab){
      return system.getResultFail(-100,"参数错误");
    }
    if(!ab.code){
      return system.getResultFail(-101,"模板编码不能为空");
    }
    if(!ab.template_content){
      return system.getResultFail(-102,"模板内容不能为空");
    }
    //根据模板编码获取模板信息
    var templateInfo = await this.dao.model.findOne({
      where:{code:ab.code},raw:true
    });
    if(!templateInfo || !templateInfo.id){
      return system.getResultFail(-300,"未知模板");
    }
    // if(templateInfo.is_enabled===1){
    //   return system.getResultFail(-301,"该模板正在使用中，不能执行此操作");
    // }
    var updateObj = {id:templateInfo.id,template_content:ab.template_content};
    if(ab.form_id){
      updateObj["form_id"] = ab.form_id;
    }
    await this.dao.update(updateObj);
    this.delRedisInfoByLinkByTempId(templateInfo.id);
    return system.getResultSuccess();
  }
  /**
   * 修改启用状态
   * @param {*} pobj 
   */
  async updateSwitchStatus(pobj){
    var ab = pobj;
    if(!ab){
      return system.getResultFail(-100,"参数错误");
    }
    if(!ab.code){
      return system.getResultFail(-101,"模板编码不能为空");
    }
    if(!ab.hasOwnProperty("is_enabled")){
      return system.getResultFail(-102,"启用状态不能为空");
    }
    if(ab.is_enabled!==0 && ab.is_enabled!==1){
      return system.getResultFail(-103,"启用状态参数错误");
    }
    var templateInfo = await this.dao.model.findOne({
      where:{code:ab.code},raw:true
    });
    if(!templateInfo || !templateInfo.id){
      return system.getResultFail(-300,"未知模板");
    }
    await this.dao.update({id:templateInfo.id,is_enabled:ab.is_enabled});
    // 获取模板对应模板链接，并删除其redis缓存
    this.delRedisInfoByLinkByTempId(templateInfo.id);
    return system.getResultSuccess();
  }
  /**
   * 编辑模板tdk信息
   * @param {*} pobj 
   */
  async editTemplateTdk(pobj){
    var ab = pobj;
    var updateObj = {};
    if(!ab){
      return system.getResultFail(-100,"参数错误");
    }
    if(!ab.code){
      return system.getResultFail(-101,"模板编码不能为空");
    }
    if(!ab.title){
      return system.getResultFail(-102,"网页标题不能为空");
    }
    updateObj.title = ab.title;
    if(!ab.keyword){
      return system.getResultFail(-103,"关键词不能为空");
    }
    updateObj.keyword = ab.keyword;
    if(!ab.pic_url){
      return system.getResultFail(-104,"网页图标不能为空");
    }
    updateObj.pic_url = ab.pic_url;
    if(!ab.describe){
      return system.getResultFail(-105,"描述不能为空");
    }
    updateObj.describe = ab.describe;
    //根据模板编码获取模板信息
    var templateInfo = await this.dao.model.findOne({
      where:{code:ab.code},raw:true
    });
    if(!templateInfo || !templateInfo.id){
      return system.getResultFail(-300,"未知模板");
    }
    updateObj.id = templateInfo.id;
    await this.dao.update(updateObj);
    // 获取模板对应模板链接，并删除其redis缓存
    this.delRedisInfoByLinkByTempId(templateInfo.id);
    return system.getResultSuccess();
  }
  
  async update(qobj, tm = null) {
    // 获取模板对应模板链接，并删除其redis缓存
    if(qobj && qobj.id){
      this.delRedisInfoByLinkByTempId(qobj.id);
    }
    return this.dao.update(qobj, tm);
  }


  /**
   * 编辑模板2
   * @param {*} pobj 
   */
  async editTemplate (pobj) {
    var ab = pobj.actionBody;
    // var xctx = pobj.xctx;
    // 检查传入参数
    if(!ab){
      return system.getResultFail(-100,"参数错误");
    }
    if(!ab.code){
      return system.getResultFail(-101,"模板编码不能为空");
    }
    if(!ab.template_content){
      return system.getResultFail(-102,"模板内容不能为空");
    }
    // 获取对应模板
    let template = await this.findOne({code: ab.code});
    if (!template || !template.id) {
      return system.getResultFail(-300, "未知模板");
    }
    if (!template.is_enable === 1) {
      return system.getResultFail(-301, "该模板使用中，不能执行此操作");
    }

    // 更新模板
    let obj = {template_content: ab.template_content};
    if(ab.form_id){
      obj["form_id"] = ab.form_id;
    }
    await template.update(obj);
    // 获取模板对应模板链接，并删除其redis缓存
    this.delRedisInfoByLinkByTempId(template.id);
    return system.getResultSuccess();
  }

  //清除模板缓存数据
  async delRedisInfoByLinkByTempId(template_id){
    try {
      let tls = await this.templatelinkDao.findAll({"template_id": template_id});
      tls.forEach(async (tl) => {
        let obj = {
          is_enabled:1,
          template_id: tl.template_id?tl.template_id.toString():"",
          channel_code: tl.channel_code,
          else_channel_param: tl.else_channel_param,
          business_type_code: tl.business_type_code,
          lauch_type_code: tl.lauch_type_code,
          marketing_subject_code: tl.marketing_subject_code
        };
        let shaStr = sha256(JSON.stringify(obj));
        shaStr = "templink_"+template_id+"_"+shaStr;
        await this.redisClient.publish("delTemplateCache",shaStr);
        await this.redisClient.delete(shaStr);
      });
    } catch (e) {
      console.log(e)
    }
  }
}
module.exports = TemplateinfoService;