import { Controller, Context } from 'egg';
const url = require('url');
export default class NavigatorController extends Controller {
  public async getNavigatorConfigList(ctx: Context) {
    // 查询导航配置列表
    const { pageNo, pageSize, name, author} = ctx.query;
    try {
      const list = await ctx.service.navigator.getList(pageNo, pageSize, name, author);
      ctx.body = ctx.helper.ok(list);
    } catch (e) {
      ctx.logger.info(`获取导航配置数据异常, ${JSON.stringify(e)}`);
      ctx.body = ctx.helper.fail({
        message: '获取数据异常'
      });
    }
  }
  // 查询导航配置列表(父子接口，供选择页面使用，且带有分页)
  public async getNavigatorConfigListWithRelation(ctx: Context) {
    const { pageNo, pageSize, name, author, id } = ctx.query;
    try {
      const list = await ctx.service.navigator.getNavigatorConfigListWithRelation(pageNo, pageSize, name, author, id);
      ctx.body = ctx.helper.ok(list);
    } catch (e) {
      ctx.logger.info(`获取导航配置数据异常, ${JSON.stringify(e)}`);
      ctx.body = ctx.helper.fail({
        message: '获取数据异常'
      });
    }
  }
  // 删除导航配置
  public async deleteNavigatorConfig(ctx: Context) {
    const { id } = ctx.request.body;
    try {
      await ctx.service.navigator.deleteById(id);
      ctx.body = ctx.helper.ok({});
    } catch (e) {
      ctx.logger.info(`删除导航配置异常, ${JSON.stringify(e)}`);
      ctx.body = ctx.helper.fail({
        message: '删除导航配置失败'
      });
    }
  }
  // 保存导航配置
  public async saveNavigatorConfig(ctx: Context) {
    const pageInfo = ctx.request.body;
    if (!pageInfo.id) {
      delete pageInfo.id;
    }
    try {
      for (let i = 0; i < pageInfo.navigatorData.length; i++) {
        let item = pageInfo.navigatorData[i];
        if (item.pageType != 1) {
          // let url = new URL(item.pageUrl);

          let urlObj = url.parse(item.pageUrl, true)
          let pageUUID = urlObj.pathname.replace('/activity/', '');
          console.log(pageUUID);
          await ctx.service.redis.del(`page:${pageUUID}`);
          await ctx.service.redis.del(`pageInfo:${pageUUID}`);
          ctx.logger.info(`del redis page key page:${pageUUID}`);
        }
      }
      await ctx.service.navigator.saveOrUpdate(pageInfo);
      ctx.body = ctx.helper.ok({});
    } catch (e) {
      ctx.logger.info(`保存导航配置异常, ${JSON.stringify(e)}`);
      ctx.body = ctx.helper.fail({
        message: '保存导航配置失败'
      });
    }
  }
  // 获取导航配置详细信息
  public async getNavigatorDetail(ctx: Context) {
    const { navId } = ctx.query;
    try {
      const res = await ctx.service.navigator.getDetail(navId);
      ctx.body = ctx.helper.ok(res);
    } catch (e) {
      ctx.logger.info(`查询导航配置异常, ${JSON.stringify(e)}`);
      ctx.body = ctx.helper.fail({
        message: '查询导航配置失败'
      });
    }
    return 
  }
}