// packageF/storeManagement/components/collapse/collapse-item.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    item:{
      type:Object,
      value:{}
    },
    name:{
      type:Number,
      value:0
    },
    level:{
      type:[String,Number],
      value:1
    }
  },
  relations: {
    './collapse': {
      type: 'parent', // 关联的目标节点应为父节点
      linked: function(target) {
        this.parent = target;
        
        // 每次被插入到custom-ul时执行，target是custom-ul节点实例对象，触发在attached生命周期之后
      },
      linkChanged: function(target) {
        // 每次被移动后执行，target是custom-ul节点实例对象，触发在moved生命周期之后
      },
      unlinked: function(target) {
        // 每次被移除时执行，target是custom-ul节点实例对象，触发在detached生命周期之后
      }
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    flag:false,
    height:0,
    expanded:false,

  },
  ready(){
    this.animation = wx.createAnimation({
      duration: 0,
      timingFunction: 'ease-in-out',
    });
  },
  /**
   * 组件的方法列表
   */
  methods: {
    handOperation(){
      this.triggerEvent("operation",{name:this.data.name,level:this.data.level});
    },
    onClick(){
      // if(this.parent){
      //   this.parent.switch(this.data.name)
      // }
      this.setData({
        flag:!this.data.flag
      });
      this.updateStyle(this.data.flag);
    },
    updateExpanded(){
      if (!this.parent) {
        return Promise.resolve();
      }
      const { active } = this.parent.data;
      const { name } = this.data;
      const currentName = name;
      const expanded = (active || []).some((name) => name === currentName);
      if(expanded !== this.data.expanded){
        this.updateStyle(expanded);
      }
      
      this.setData({expanded});
    },
    updateStyle(expanded) {
      this.getRect('.collapseContent')
        .then((rect) => rect.height)
        .then((height) => {

          const { animation } = this;
          if (expanded) {

            if (height === 0) {
              animation.height('auto').top(1).step();
            } else {
              animation
                .height(height)
                .top(1)
                .step({
                  duration: 300,
                })
                .height('auto')
                .step();
            }
            this.setData({
              animation: animation.export(),
            });
            return;
          }

          animation.height(height).top(0).step({ duration: 1 }).height(0).step({
            duration: 300,
          });
          this.setData({
            animation: animation.export(),
          });
        });
    },
    getRect(selector) {
      var _this = this;
  
      return new Promise(function (resolve, reject) {
        _this.createSelectorQuery().select(selector).boundingClientRect(function (rect) {
          if (rect) {
            resolve(rect);
          } else {
            reject(new Error("can not find selector: " + selector));
          }
        }).exec();
      });
    },
  }
});
