const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
class ChannelService extends ServiceBase {
  constructor() {
    super("common", ServiceBase.getDaoName(ChannelService));
    this.handlers = {}
  }
  async channelHandle(channelobj, path, datajson) {
    let p = channelobj.pts.filter(item => {
      return item.path == path
    })
    if (p.length == 0) {
      throw Error("请配置渠道流量的路径方法映射")
    }
    let fileName = channelobj.code
    let method = p[0].method
    if (!this.handlers[fileName]) {
      this.handlers[fileName] = require("./channelhandlers/" + fileName + ".js")
    }
    if (!this.handlers[fileName][method]) {
      throw Error(`请在${fileName}文件中定义渠道流量的处理方法${method}`)
    }
    let rtn = await this.handlers[fileName][method](datajson, channelobj);
    return rtn;
  }
  async create(p, q, req) {
    let self = this
    return this.db.transaction(async function (t) {
      let u = await self.dao.create(p, t)
      //创建路由--针对于特定来源渠道域名的路由,给中台服务添加路由
      try {
        let ps = ["/"]
        let routeobj = await self.cjsonregister(ChannelService.newRouteUrl(settings.pmappname),
          { name: p.code, paths: ps, hosts: [p.routehost], strip_path: false })
      } catch (e) {
        await self.cdel(ChannelService.routeUrl(p.code))
        throw new Error("创建渠道报错")
      }
      return u
    })
  }
  async update(p, q, req) {
    let self = this
    return this.db.transaction(async function (t) {
      let old = await self.dao.findOne({ id: p.id })
      let u = await self.dao.update(p, t)
      //创建路由--针对于特定来源渠道域名的路由,给中台服务添加路由
      try {
        await self.cdel(ChannelService.routeUrl(old.code))
        let ps = ["/"]
        let routeobj = await self.cjsonregister(ChannelService.newRouteUrl(settings.pmappname),
          { name: p.code, paths: ps, hosts: [p.routehost], strip_path: false })
      } catch (e) {
        throw new Error("创建渠道报错")
      }
      return u
    })
  }
  async delete(p, q, req) {
    let self = this
    return this.db.transaction(async function (t) {
      let u = await self.dao.delete(p, t)
      //创建路由--针对于特定来源渠道域名的路由,给中台服务添加路由
      try {
        await self.cdel(ChannelService.routeUrl(u.code))
      } catch (e) {
        throw new Error("创建渠道报错")
      }
      return u
    })
  }

  async authorizeUser(p, q, req) {
    await this.dao.updateByWhere({
      userids: p.userids
    }, {
      id: p.channelId
    })
  }
}
module.exports = ChannelService;