// components/My_switch/index.js
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        list: {
            type: Array,
            value: ['最新', '最热']
        },
        change: {
            type: Function
        },
        sort: {
            type: Array
        },
        reversed: {
            type: Number,
            value: 0
        }
    },
    lifetimes: {
        ready: function () {
            const that = this;
            let query = wx.createSelectorQuery().in(this)
            query.select('.switch-box').boundingClientRect();
            query.exec(function (res) {
                that.setData({
                    baseLeft: res[0].left
                })
                that.chengeSelect()
            })
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        checkedItem: 0, //选中项
        animationData: {}, //横线平移动画
        baseLeft: 0,
    },

    /**
     * 组件的方法列表
     */
    methods: {
        changeSwitch(e) {
            this.setData({
                checkedItem: this.data.checkedItem == 0 ? 1 : 0
            })
            let name = this.data.list[this.data.checkedItem],
                sort = this.data.sort;
            for (let i = 0; i < sort.length; i++) {
                sort[i].sorted = sort[i].sortname == name ? 1 : 0;
                sort[i].reversed = this.data.reversed
            }
            this.triggerEvent('change', sort)
            this.chengeSelect()
        },
        chengeSelect() {
            let animation = wx.createAnimation({
                duration: 1000,
                timingFunction: 'ease',
            })
            let that = this;
            let query = wx.createSelectorQuery().in(this)
            query.select('.active').boundingClientRect();
            query.exec(function (res) {
                animation.translate(res[0].left - that.data.baseLeft + 2).step({
                    duration: 300
                })
                that.setData({
                    animationData: animation.export()
                })
            })
        }
    }
})