<template>
  <div>
    <div v-if="!isIOS" class="container" :style="{ width: _cellWidth + 'px', 'padding-right': padding + 'px' }">
      <div
        class="itemWrap"
        ref="menuItem"
        :style="{ width: _cellWidth + rightWidth(item) + 'px' }"
        v-for="(item, index) in listData"
        :key="index"
        @swipe="slideMenu($event, index, item)"
        @touchend="touchend"
      >
        <div v-if="padding" :style="{ width: padding + 'px' }"></div>
        <div class="cellBox">
          <dof-cell
            ref="cell"
            v-bind="item"
            :isHighlight="isHighlight"
            :click-activied="false"
            @dofCellClicked="cellCanClick ? dofCellClicked(index) : ''"
          >
            <dof-switch
              v-if="item.switchVal !== undefined"
              slot="switch"
              :checked="item.switchVal"
              @dof-change="handleSwitchChange(item)"
            ></dof-switch>
          </dof-cell>
        </div>
        <div
          class="swipe-action-right"
          v-if="item.rightItem && item.rightItem.length > 0"
          :style="{ width: rightWidth(item) + 'px', paddingLeft: padding ? '16px' : '0px' }"
        >
          <div
            :class="['swipeItem']"
            v-for="(rightCon, i) in item.rightItem"
            :key="i"
            :style="{ backgroundColor: rightCon.bgColor }"
          >
            <text class="swipeText">{{ rightCon.text }}</text>
            <text class="swipeText">{{ rightCon.text1 }}</text>
            <text class="swipeText">{{ rightCon.text2 }}</text>
            <div class="mask" @click="onRightNode(index, i, rightCon.text)"></div>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="container" :style="{ width: _cellWidth + 'px', 'padding-right': padding + 'px' }">
      <div
        ref="skid"
        v-for="(item, index) of listData"
        :key="'skid-' + index"
        class="dof-skid"
        :style="{ width: _cellWidth + rightWidth(item) + 'px' }"
        @horizontalpan="handleHorizontalpan(event, item, index)"
        @panend="handlePanEnd(event, item, index)"
      >
        <div v-if="padding" :style="{ width: padding + 'px' }"></div>
        <div class="cellBox">
          <dof-cell
            ref="cell"
            v-bind="item"
            :isHighlight="isHighlight"
            :click-activied="false"
            @dofCellClicked.stop="dofCellClicked(index)"
          >
            <dof-switch
              v-if="item.switchVal !== undefined"
              slot="switch"
              :checked="item.switchVal"
              @dof-change="handleSwitchChange(item)"
            ></dof-switch>
          </dof-cell>
        </div>

        <div
          class="swipe-action-right"
          v-if="item.rightItem && item.rightItem.length > 0"
          :style="{ width: rightWidth(item) + 'px', paddingLeft: padding ? '16px' : '0px' }"
        >
          <div
            :class="['swipeItem']"
            v-for="(rightCon, i) in item.rightItem"
            :key="i"
            :style="{ backgroundColor: rightCon.bgColor }"
          >
            <text class="swipeText">{{ rightCon.text }}</text>
            <text class="swipeText">{{ rightCon.text1 }}</text>
            <text class="swipeText">{{ rightCon.text2 }}</text>
            <div class="mask" @click="onRightNode(index, i, rightCon.text)"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.container {
  /* background-color: #ffffff; */
  overflow: hidden;
}
.dof-skid {
  flex-direction: row;
  /* background-color: #ffffff; */
  overflow: hidden;
}

/* 
.swipe-action-right {
  flex-direction: row;
  align-items: center;
  overflow: hidden;
}

.swipeItem{
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
}
.swipeText{
  flex: 1;
  color: #FFFFFF;
  text-align: center;
  align-items: center;
  lines:1;
  text-overflow: ellipsis;
  overflow: hidden;
} */

/* android */

.itemWrap {
  flex-direction: row;
  justify-content: flex-start;
  align-items: stretch;
}

.swipe-action-right {
  flex-direction: row;
  justify-content: flex-start;
  align-items: stretch;
  overflow: hidden;
}
.swipeItem {
  /* width: 160px; */
  /* height: 160px; */
  justify-content: center;
  align-items: center;
  flex: 1;
  position: relative;
}
.mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0);
}
.mask:active {
  background-color: rgba(255, 255, 255, 0.1);
}

.swipeText {
  font-size: 32px;
  color: #ffffff;
  text-align: center;
  align-items: center;
  lines: 2;
  /* line-height: 48px; */
  text-overflow: ellipsis;
  overflow: hidden;
}
.cellBox {
  flex: 1;
}
</style>
<style scoped src="./colmo.css"></style>

<script>
import Binding from 'weex-bindingx/lib/index.weex.js'
const animation = weex.requireModule('animation')
import Utils from '../utils'
const modal = weex.requireModule('modal')
const dom = weex.requireModule('dom')
import DofCell from '../dof-cell'
import DofSwitch from '../dof-switch'

export default {
  props: {
    listData: {
      type: Array,
      default: () => []
    },
    // styles: {
    //   type: Object,
    //   default: ()=>({})
    // }
    cellWidth: {
      type: Number,
      default: 0
    },
    padding: {
      type: Number,
      default: 0
    }
  },
  computed: {
    _cellWidth() {
      if (this.cellWidth) return this.cellWidth
      if (this.padding) return 750 - this.padding
      return 750
    }
  },
  components: {
    DofCell,
    DofSwitch
  },
  data() {
    return {
      mobileX: 0,
      webStarX: 0,
      saveIdx: null,
      isAndroid: Utils.env.isAndroid(),
      isIOS: Utils.env.isIOS(),

      cellCanClick: true, //android
      isHighlight: false
    }
  },

  mounted() {},

  methods: {
    dofCellClicked(index) {
      //点击触发滑动恢复初始化
      if (!this.isIOS) {
        this.rightSlide() // 列表初始化
        this.cellCanClick && this.$emit('dofCellClicked', { index })
      } else {
        for (let index = 0; index < this.listData.length; index++) {
          this.special(this.$refs.skid[index], {
            transform: 'translate(0, 0)'
          })
        }
        this.$emit('dofCellClicked', { index })
      }
    },

    special(dom, styles) {
      animation.transition(dom, {
        styles,
        duration: 150, // ms
        timingFunction: 'ease',
        delay: 0 // ms
      })
    },
    onRightNode(index, i, text) {
      if (!this.isIOS) {
        this.rightSlide()
        this.$emit('dofRightClicked', { index, i, text })
      } else {
        this.special(this.$refs.skid[this.saveIdx], {
          transform: 'translate(0, 0)'
        })
        this.$emit('dofRightClicked', { index, i, text })
      }
    },

    onPanEnd(e, node, i) {
      if (Utils.env.isWeb()) {
        const webEndX = e.changedTouches[0].pageX
        this.movingDistance(webEndX - this.webStarX, node, this.$refs.skid[i])
      }
    },

    handleHorizontalpan(e, item, index) {
      !this.isAndroid && this.onPanStart(e, item, index, item.rightItem ? item.rightItem.length : 0)
    },
    handlePanEnd(e, item, index) {
      this.onPanEnd(e, item, index)
    },
    // 使用官方的pan事件解决某些ios设备使用@swipe不能滑动的问题
    onPanStart: function(e, node, i, len) {
      const { saveIdx } = this
      if (saveIdx !== i && saveIdx !== null && this.$refs.skid[saveIdx]) {
        this.special(this.$refs.skid[saveIdx], {
          transform: 'translate(0, 0)'
        })
        this.mobileX = 0
      }
      this.saveIdx = i
      this.mobile(e, node, i, len)
      // !Utils.env.isWeb() ? this.mobile(e, node, i, len) : this.web(e, node, i)
      // e.stopPropagation()
    },
    web(e, node, i) {
      this.webStarX = e.changedTouches[0].pageX
    },
    mobile(e, node, i, len) {
      var el = this.$refs['skid'][i]
      Binding.bind(
        {
          anchor: el.ref,
          eventType: 'pan',
          props: [
            {
              element: el.ref,
              property: 'transform.translateX',
              // expression: `x+${this.isAndroid ? 0 : this.mobileX}`
              expression: this.rightWidth(node) //处理ios设备左滑移动距离，防止闪烁
            }
          ]
        },
        e => {
          const { state, deltaX } = e
          if (state === 'end') {
            this.mobileX = deltaX
            // this.movingDistance(this.mobileX, node, el);
            this.movingDistance(e.deltaX, node, el) //add by lau
          }
        }
      )
    },
    movingDistance(scope, node, el) {
      const len = node.rightItem ? node.rightItem.length : 0
      const distance = -this.rightWidth(node)
      // if (scope < -80*len) {
      //   this.special(el, {
      //     transform: `translate(${distance}px, 0)`
      //   });
      //   this.mobileX = distance;
      // } else {
      //   this.special(el, {
      //     transform: 'translate(0, 0)'
      //   });
      //   this.mobileX = 0;
      // }

      //modify by lau
      if (scope < 0) {
        this.special(el, {
          transform: `translate(${distance}px, 0)`
        })
      } else if (scope > 0) {
        this.special(el, {
          transform: 'translate(0, 0)'
        })
      } else {
        return
      }
    },

    // 适配Android
    // 经n次尝试和测试后，发现weex的click事件和touchend事件冲突, 防止滑动后触发click事件
    // 这里异步处理，touchend事件结束后才激活向上传递的click事件
    touchend() {
      setTimeout(() => {
        this.cellCanClick = true
      }, 100)
    },

    slideMenu(e, index, item) {
      let length = item.rightItem.length
      this.cellCanClick = false
      let listItems = this.$refs.menuItem
      let ele = this.$refs.menuItem[index]
      let direction = e.direction
      if (direction == 'left') {
        this.leftSlide(e, ele, length, this.listData[index])
      } else if (direction == 'right') {
        this.rightSlide(ele)
      }
      e.stopPropagation()
    },

    // @params ele 要执行动画的元素
    leftSlide(e, ele, length, item) {
      this.rightSlide()
      animation.transition(ele, {
        styles: {
          transform: `translateX(-${this.rightWidth(item)}px)`
        },
        duration: 150, //ms
        timingFunction: 'ease',
        // needLayout: false,   //变化后是否刷新页面
        delay: 0 //ms
      })
      e.stopPropagation()
    },

    rightSlide() {
      let listItems = this.$refs.menuItem
      for (let i = 0; i < listItems.length; i++) {
        animation.transition(
          listItems[i],
          {
            styles: {
              transform: 'translateX(0px)'
            },
            duration: 100, //ms
            timingFunction: 'ease-in',
            needLayout: true,
            delay: 0 //ms
          },
          function() {}
        )
      }
      return false
    },

    rightWidth(item) {
      if (item.rightItem && item.rightItem.length) {
        return item.rightItem.reduce((pre, cur) => pre + (cur.width || 160), 0)
      }
      return 0
    },
    handleSwitchChange(item) {
      item.switchVal = !item.switchVal
      this.$emit('switchChange', item)
    }
  }
}
</script>
