<template>
  <div class="app-container">
    <!-- 组合按钮 -->
    <el-button-group class="m-b-20 m-r-20">
      <el-button type="primary" icon="el-icon-plus" @click="$router.replace('/spu/add')">添加</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="deleteSpu(countSelIdArr($refs.myTable.selection))">删除
      </el-button>
      <el-button type="warning" icon="el-icon-edit" @click="toEditPage()">编辑</el-button>
    </el-button-group>
    <!-- 用户select选项 -->
    <el-button-group class="m-b-20 m-r-20">
      <SelectionShopId v-model="form.shop_id" :allSel="true" />
    </el-button-group>
    <!-- 分类select选项 -->
    <el-button-group class="m-b-20">
      <SelectionPath v-model="form.path" :shop_id="form.shop_id" :allSel="true" />
    </el-button-group>
    <!-- 商品spu表格 -->
    <el-table class="w-100" ref="myTable"
      :data="spuListArr.slice((currentPage - 1) * pageSize, currentPage * pageSize)" border tooltip-effect="dark">
      <el-table-column align="center" type="selection" width="40">
      </el-table-column>
      <el-table-column align="center" label="排序" width="70">
        <template slot-scope="scope">
          <el-input v-model="scope.row.sort" @focus="tempSort = scope.row.sort"
            @blur="blurOrder(scope.row.id, scope.row.sort)"></el-input>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="id" label="id" width="50">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="150" min-width="150">
      </el-table-column>
      <el-table-column prop="spu_number" label="编号" min-width="120">
      </el-table-column>
      <el-table-column label="图片" width="120" min-width="120">
        <template v-if="scope.row.photo != ''" slot-scope="scope">
          <el-image :src="scope.row.photo[0]"
            :preview-src-list="scope.row.photo">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="controler" label="操作" width="420" min-width="420">
        <template slot-scope="scope">
          <el-button-group>
            <el-button :type="scope.row.recommend == '1' ? 'success' : 'info'" class="iconfont icon-tuijian"
              @click="handeleRecommend(scope.row.id, scope.row.recommend)"><span class="m-l-5">推荐</span></el-button>
            <el-button :type="scope.row.show == '1' ? 'primary' : 'info'"
              :class="scope.row.show == '1' ? 'iconfont icon-yanjing' : 'iconfont icon-biyanjing'"
              @click="handeleShow(scope.row.id, scope.row.show)"><span class="m-l-5">显示</span></el-button>
            <el-button type="warning" icon="el-icon-edit"
              @click="$router.replace(`/spu/edit/${scope.row.id}`)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteSpu([scope.row.id])">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination class="m-t-20" layout="prev, pager, next" :current-page.sync="currentPage" :page-size="pageSize"
      :total="spuListArr.length">
    </el-pagination>
  </div>
</template>

<script>
import { countSelIdArr } from '@/utils'
import SelectionShopId from '@/components/SelectionShopId'
import SelectionPath from '@/components/SelectionPath'

export default {
  name: 'Spu',
  data () {
    return {
      pageSize: 30, // 每页显示记录条数
      currentPage: 1, // 当前页
      form: {
        shop_id: '',
        path: ''
      },
      tempSort: ''// 临时记录 商品排序序号
    }
  },
  components: {
    SelectionShopId,
    SelectionPath
  },
  computed: {
    // 获取商品列表
    spuList () {
      return this.$store.state.spuList
    },
    // 获取分类列表
    categoryList () {
      return this.$store.state.categoryList
    },
    /**
     * @description: 按照shop_id path条件过滤 商品列表
     * @return: 商品列表
     */
    spuListArr () {
      // 过滤出对应商铺的商品
      let pList = this.spuList
      if (this.form.shop_id !== '') { // 如果不是"所有商铺" 则按shop_id过滤
        pList = pList.filter((item) => item.shop_id === this.form.shop_id)
      }
      // 过滤出 分类已经被删除的商品 （未分类）
      if (this.form.path === 'none') {
        const list = pList.filter((item) => {
          let t = true
          for (let index = 0; index < this.categoryList.length; index++) {
            if (this.categoryList[index].path === item.path) {
              t = false
              break
            }
          }
          return t
        })
        return list
      } else if (this.form.path !== '') {
        var pattern = this.form.path // selection path分类条件
        // 对特殊字符进行转义，以防止它们影响正则表达式的匹配
        var escapedPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
        // 构建动态正则表达式对象
        var regexPattern = new RegExp('^' + escapedPattern + '(-|$)')
        const list = pList.filter((item) => {
          let t = false
          for (let index = 0; index < this.categoryList.length; index++) { // 先确保 商品的path 在分类列表path中是存在的
            if (this.categoryList[index].path === item.path) {
              t = true
              break
            }
          }
          if (t) {
            return regexPattern.test(item.path)
          } else {
            return false
          }
        })
        return list
      } else {
        return pList // 所有分类显示所有商品
      }
    }
  },
  methods: {
    countSelIdArr,
    // 搜索标签
    handleClose (tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm () {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    /**
     * @description: 跳转到编辑页面
     */
    toEditPage () {
      const selId = this.countSelIdArr(this.$refs.myTable.selection)
      switch (selId.length) {
        case 0:
          this.$message.error('请选择一条需要编辑的记录')
          break
        case 1:
          this.$router.push('/spu/edit/' + selId['0'])
          break
        default:
          this.$message.error('只能选择一条记录')
      }
    },
    /**
     * @description: 删除spu
     */
    deleteSpu (idArr) {
      this.$store.dispatch('fetchDelSpu', idArr)
    },
    /**
     * @description: 排序input失焦 更新数据库的排序
     * @param {*} id 商品id
     * @param {*} sort 排序序号
     */
    async blurOrder (id, sort) {
      if (this.tempSort !== sort) { // 失焦时 和 之前点击时 排序做一下对比 有更新 再向api提交数据
        this.form.id = id
        this.form.sort = sort
        const res = await this.$store.dispatch('fetchOrderSpu', this.form)
        if (res.data.status === 1) {
          this.$router.push({ path: '/spu/index', query: { refresh: Date.now() } })
        }
      }
    },
    /**
     * @description: 设置前端是否显示 商品
     * @param {*} id 商品id
     * @param {*} show 0隐藏 1显示
     */
    async handeleShow (id, show) {
      this.form.id = id
      if (show === '0') {
        this.form.show = '1'
      } else {
        this.form.show = '0'
      }
      const res = await this.$store.dispatch('fetchShowSpu', this.form)
      if (res.data.status === 1) {
        this.$router.push({ path: '/spu/index', query: { refresh: Date.now() } })
      }
    },
    /**
     * @description: 设置前端是否推荐 商品
     * @param {*} id 商品id
     * @param {*} recommend 0推荐 1不推荐
     */
    async handeleRecommend (id, recommend) {
      this.form.id = id
      if (recommend === '0') {
        this.form.recommend = '1'
      } else {
        this.form.recommend = '0'
      }
      const res = await this.$store.dispatch('fetchRecommendSpu', this.form)
      if (res.data.status === 1) {
        this.$router.push({ path: '/spu/index', query: { refresh: Date.now() } })
      }
    }
  },
  watch: {
  },
  created () {
  },
  filters: {
    countSelIdArr
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/theme.scss";

i {
  font-size: 18px !important;
  margin-right: 12px;
  vertical-align: middle;
}
</style>
