import { Context, Service } from 'egg';

// 添加或修改url中的参数
function addOrEditUrlParams (url, paramName, replaceWith) {
  if (url.indexOf(paramName) > -1) {
    let re = /(' + paramName + '=)([^&]*)/gi;
    url = url.replace(re, paramName + '=' + replaceWith);
  } else {
    let paraStr = paramName + '=' + replaceWith;
    let idx = url.indexOf('?');
    if (idx < 0) {
      url += '?';
    } else if (idx >= 0 && idx !== url.length - 1) {
      url += '&';
    }
    url = url + paraStr;
  }
  return url;
};

function deleteUrlParams(url, ref) {
    let str = "";
    if (url.indexOf('?') != -1) {
      str = url.substr(url.indexOf('?') + 1);
    } else {
      return url;
    }
    let arr = [];
    let returnurl = "";
    let setparam = "";
    if (str.indexOf('&') != -1) {
      arr = str.split('&');
      for (let i in arr) {
          if (arr[i].split('=')[0] != ref) {
              returnurl = returnurl + arr[i].split('=')[0] + "=" + arr[i].split('=')[1] + "&";
          }
      }
      return url.substr(0, url.indexOf('?')) + "?" + returnurl.substr(0, returnurl.length - 1);
    } else {
      arr = str.split('=');
      if (arr[0] == ref) {
        return url.substr(0, url.indexOf('?'));
      } else {
        return url;
      }
    }
}

export default class NavService extends Service {
  private context: Context;
  constructor(ctx: Context) {
    super(ctx);
    this.context = ctx;
  }
  // 获取导航列表
  async getList(pageNo, pageSize, name = '', author = '') {
    const offset = (+pageNo - 1) * pageSize;
    const condition = {
      author: null,
      name: null
    };
    // 模糊匹配作者
    if (author) {
      condition.author = {
        $like: '%' + author + '%'
      };
    }
    if (name) {
      condition.name = {
        $like: '%' + name + '%'
      };
    }
    if (!condition.author) delete condition.author;
    if (!condition.name) delete condition.name;
    const res = await this.context.model.NavigatorConfig
      .findAndCountAll({
        where: condition,
        limit: +pageSize,
        offset,
        order: [
          ['id', 'DESC']
        ],
      })
    const result = {
      total: res.count || 0,
      data: res.rows || []
    }  
    return result;
  }
  // 选择页面 导航配置 获取列表
  async getNavigatorConfigListWithRelation(pageNo, pageSize, name = '', author = '', id) {
    const offset = (+pageNo - 1) * pageSize;;
    const condition = {
      author: null,
      name: null,
      id: null
    };
    if (author) {
      condition.author = {
        $like: '%' + author + '%'
      };
    }
    if (name) {
      condition.name = {
        $like: '%' + name + '%'
      };
    }
    if (id) {
      condition.id = {
        $notIn: [id]
      }
    }
    if (!condition.author) delete condition.author;
    if (!condition.name) delete condition.name;
    if (!condition.id) delete condition.id;
    const res = await this.context.model.NavigatorConfig
      .findAndCountAll({
        where: condition,
        limit: +pageSize,
        offset
      })
    const result = {
      total: res.count || 0,
      data: res.rows || []
    }  
    return result;
  }
  // 删除导航配置
  async deleteById(id) {
    const res = await this.context.model.NavigatorConfig.destroy({
      where: {
        id
      }
    })
    return res;
  }
  // 保存或编辑
  async saveOrUpdate(data) {
    if (data.id) {
      // 编辑
      const id = data.id;
      const saveData = Object.assign({}, data);
      const navigatorData = saveData.navigatorData;
      for (let i = 0; i < navigatorData.length; i++) {
        if(navigatorData[i].pageType == 2) {
          let url = navigatorData[i].pageUrl;
          if (!navigatorData[i].carryNav) {
            url = deleteUrlParams(url, 'navId');
            url = deleteUrlParams(url, 'index');
          } else {
            url = addOrEditUrlParams(url, 'navId', id);
            url = addOrEditUrlParams(url, 'index', i);
          }
          navigatorData[i].pageUrl = url;
        }
      }
      delete saveData.id;
      const res = await this.context.model.NavigatorConfig.update(saveData, {
        where: {
          id
        }
      })
      return res;
    }
    // 保存
    const res = await this.context.model.NavigatorConfig.create(data);
    const id = res.dataValues.id;
    const navigatorData = JSON.parse(res.dataValues.navigatorData);
    // 更新保存数据的链接，pageType为2的要进行更新
    for (let i = 0; i < navigatorData.length; i++) {
      if(navigatorData[i].pageType == 2 && navigatorData[i].carryNav) {
        navigatorData[i].pageUrl += `&navId=${id}&index=${i}`;
      }
    }
    const result = await this.context.model.NavigatorConfig.update({
      navigatorData
    }, {
      where: {
        id
      }
    })
    return result;
  }
  // 查询导航配置信息
  async getDetail(id) {
    const res = await this.context.model.NavigatorConfig.findOne({
      where: {
        id
      }
    })
    return res;
  }
}
