var app = getApp()
var that;
Component({
  mixins: [],
  data: {
    allItems: [],
    item_list: {},
    list: [],
    child_list: [],
    activeIndex: '',//一级索引
  },
  props: {
    onClose: (data) => console.log(data),
    onConfirm: (data) => console.log(data),
    defaultId: '',//默认选中
    tree: false,//是否使用 api/per/package/tree||api/per/package/list
  },
  didMount() {
    that = this;

    this.getData();
  },
  didUpdate() { },
  didUnmount() { },
  methods: {
    //点击一级
    activeTree(e) {
      var item = e.target.dataset.item
      if (item.id == this.data.activeIndex) {
        return false;
      }
      this.setData({
        activeIndex: item.id,
        child_list: item.list
      })
    },
    openDetail(e) {
      var id = e.target.dataset.item.id;
      this.setData({
        activeItemIndex: id,
      });
      this.getItem(id);
    },
    getItem(id) {
      var item_list = this.data.allItems;
      var items = item_list.filter((item) => { return item.rule_id == id });
      that.setData({
        item_list: items,
      })
    },
    radioChange: function (e) {
      this.props.onConfirm(e.detail.value);
      this.plusOne();
    },
    getData() {
      // that.setData({
      //   list: [],
      //   child_list: child_list,
      //   activeIndex: activeIndex
      // })
      let data = {};
      let str = 'api/per/package/tree';
      if (this.props.tree) {
        data = { page: 0, is_manage_scope: 1 };
        str = 'api/per/package/list';
      }
      app.$get2(str, data).then((res) => {
        if (this.props.tree) {
          let obj = res.data.data.list;
          let arr = [
            { name: '月度', id: 2, list: [] },
            { name: '日', id: 1, list: [] },
            { name: '季度', id: 3, list: [] },
            { name: '半年度', id: 4, list: [] },
            { name: '年度', id: 5, list: [] },
            { name: '自定义', id: 6, list: [] }
          ];
          obj.forEach(item => {
            arr.forEach(item2 => {
              if (item2.id == item.cycle_type) {
                item2.list.push(item);
              }
            });
          });
          let data = arr;
          let list = [];
          data.forEach(item => {
            if (item.list.length > 0) {
              list.push(item);
            }
          });
          this.setList(list)
        } else {
          var list = res.data.data
          this.setList(list)
        }
      })
    },
    setList(list) {
      let child_list = [];
      let activeIndex;
      list.some(item => {
        if (item.list.length > 0) {
          child_list = item.list;
          activeIndex = item.id
          return true;
        }
      });
      that.setData({
        list: list,
        child_list: child_list,
        activeIndex: activeIndex
      })
    },
    //关闭
    plusOne(e) {
      this.props.onClose();
    },
  },
});
