<template>
  <div class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />

    <div class="filter-container">
      <el-select v-model=" searchParams.search_name" class="filter-item" placeholder="请选择类型" @change="getList()">
        <el-option v-for="(item, index) in attrList" :key="index" :value="item" />
      </el-select>
      <el-button type="primary" icon="el-icon-edit" class="filter-item" @click="handleAdd">添加</el-button>
      <el-button type="primary" icon="el-icon-sort" class="filter-item" @click="handlerSort">排序</el-button>
    </div>

    <el-table ref="goodsList" :data="goodList" :header-cell-style="{ background: '#f8fbfc' }" class="tableBorder" border stripe>
      <el-table-column prop="id" label="编号" align="center" />
      <el-table-column prop="img_url" align="center" label="图片" width="70">
        <template slot-scope="{ row }">
          <el-image :src="row.img_url" fit="contain" class="hoverImg" />
        </template>
      </el-table-column>
      <el-table-column prop="name" align="center" label="名称" />
      <el-table-column prop="type" label="类型" align="center" />
      <el-table-column prop="tag" label="款式" align="center" />
      <el-table-column prop="unit" label="单位" align="center" />
      <el-table-column prop="hgprice" label="价格" align="center" />
      <el-table-column prop="total" label="商品数量" align="center">
        <template slot-scope="{ row: { num } }">
          {{ num }}
        </template>
      </el-table-column>
      <el-table-column prop="status" align="center" label="状态" width="222">
        <template slot-scope="{ row }">
          <el-tag :type="row.is_deleted ? 'info' : goodsStatus(row).type">{{ row.is_deleted ? '已删除' : goodsStatus(row).message }}</el-tag>
          <br>
          <div v-if="row.is_deleted == false && goodsStatus(row).message === '定时上架'">上架时间：{{ row.start }}</div>
          <div v-if="row.is_deleted == false && goodsStatus(row).message === '定时下架'">下架时间：{{ row.end }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="updated_at" align="center" label="更新时间" width="180" />
      <el-table-column label="操作" align="center" width="280">
        <template slot-scope="{ row }">
          <el-button type="text" @click="handleSeeInfo(row)">详情</el-button>
          <el-button type="text" size="mini" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" size="mini" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="batch-container">
      <pagination :total="goodListTotal" :limit="searchParams.page_size" :page="searchParams.page_index" @pagination="changePagination" @update:limit="changePagination" />
    </div>

    <el-dialog title="商品详情" top="50px" width="425px" :visible.sync="dialogGoodsVisible">
      <div class="goods_info">
        <el-carousel v-if="goodsInfo.banner_url" trigger="click" :loop="true" class="banner_img">
          <el-carousel-item v-for="item in goodsInfo.banner_url.length ? goodsInfo.banner_url : [goodsInfo.main_img]" :key="item">
            <el-image :src="item" fit="scale-down" style="width: 100%;height:100%" />
          </el-carousel-item>
        </el-carousel>
        <p class="title">商品名称: {{ goodsInfo.name }}</p>
        <p>副标题: {{ goodsInfo.desc }}</p>
        <p class="title">商品价格: {{ goodsInfo.hgPrice }}</p>
        <div v-if="goodsInfo.tagList" class="title">
          商品尺寸:
          <p v-for="(item, index) in goodsInfo.tagList.size" :key="item" style="text-indent: 2em;">{{ item + ' : ' + goodsInfo.tagList.num[index] }}</p>
        </div>
        <div class="bottom">
          <p>商品详情:</p>
          <div class="goodsInfoDesc" v-html="goodsInfo.content" />
        </div>
      </div>
    </el-dialog>

    <el-dialog title="商品排序" width="666px" :visible.sync="dialogSortVisible" :destroy-on-close="true" :close-on-click-modal="false">
      <el-table id="sortList" :data="sortList" border stripe>
        <el-table-column label="编号" type="index" align="center" width="50" />
        <el-table-column prop="img_url" align="center" label="图片" width="70">
          <template slot-scope="{ row: { main_img } }">
            <el-image :src="main_img" fit="contain" class="hoverImg" />
          </template>
        </el-table-column>
        <el-table-column prop="name" align="center" label="名称" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            dialogSortVisible = false;
            sortList = [];
            sortIdList = [];
          "
        >
          取 消
        </el-button>
        <el-button type="primary" @click="comfirmSort">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 商品详情字段
const goodsInfo = {
  contents: '',
  id: '',
  img_url: '',
  name: '',
  sku: [],
  spec: {},
  status: 0,
  title: ''
}

import Sortable from 'sortablejs'
import { getList, deleteGoods, getInfo, getSortList, sortGood, goodsAttr } from '@/api/studio/good'

export default {
  name: 'GoodsList',
  data() {
    return {
      goodList: [],
      sortList: [],
      sortIdList: [],
      goodListTotal: 0,
      goodsInfo: goodsInfo,
      dialogSortVisible: false,
      dialogGoodsVisible: false,
      searchParams: {
        page_size: 20,
        page_index: 1,
        search_name: '',
        status: '-1'
      },

      loadingFull: false,
      attrList: [], // 类型列表
      attr: ''
    }
  },
  created() {
    this.getAttr()
    this.getList()
  },
  methods: {
    getAttr() {
      // 获取商品类型
      goodsAttr().then(res => {
        if (res.code === 200) {
          this.attrList = res.data
          this.attrList.unshift('全部')
        }
      })
    },
    handlerSort() {
      // 点击排序
      this.$request(getSortList(), ({ list }) => {
        this.dialogSortVisible = true
        this.sortList = list
        this.sortIdList = this.sortList.map(e => e.attr_id)
        this.$nextTick(() => {
          new Sortable(document.querySelector('#sortList tbody'), {
            onUpdate: ({ oldIndex, newIndex }) => {
              const value = this.sortIdList[oldIndex]
              this.sortIdList.splice(oldIndex, 1)
              this.sortIdList.splice(newIndex, 0, value)
            }
          })
        })
      })
    },
    comfirmSort() {
      this.$request(sortGood({ attr_id: this.sortIdList }), data => {
        this.sortList = this.sortIdList = []
        this.dialogSortVisible = false
        this.getList()
      })
    },
    handleTagToggle(tab) {
      this.searchParams.status = tab.name
      this.getList()
    },
    // 添加商品
    handleAdd() {
      this.$router.push({
        name: 'studioGoodAdd'
      })
    },
    // 获取列表
    async getList() {
      this.loadingFull = true
      console.log(this.searchParams.search_name)
      let attr = ''
      if (this.searchParams.search_name === '全部') {
        attr = ''
      } else {
        attr = this.searchParams.search_name
      }
      try {
        const { page_size, page_index, status } = this.searchParams
        const res = await getList({ page_size, page_index, search_name: attr, status })

        console.log(res)
        const { message, code, data } = res
        if (code === 200) {
          const { list, total } = data
          console.log(list)
          this.goodList = list
          this.goodListTotal = total
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`获取商品列表失败:${e}`)
        this.loadingFull = false
      }
      this.loadingFull = false
    },
    // 转换显示
    changeKeyShow(key) {
      let out
      switch (key) {
        case 'size':
          out = '尺码'
          break
        case 'color':
          out = '颜色'
          break
        case 'type':
          out = '款式'
          break
        case 'price':
          out = '价格'
          break
        default:
          out = '规格'
      }
      return out
    },
    // 商品状态
    goodsStatus(row) {
      const { is_show } = row
      let message = ''
      let type = ''
      switch (+is_show) {
        case 0:
          message = '未上架'
          type = 'info'
          break
        case 1:
          message = '定时上架'
          type = ''
          break
        case 2:
          message = '已上架'
          type = 'success'
          break
        case 3:
          message = '定时下架'
          type = 'warning'
          break
        case 4:
          message = '已下架'
          type = 'danger'
          break
      }
      return { message, type }
    },
    // 删除
    handleDelete(row) {
      const { id } = row
      this.$confirm('确认要删除该商品吗?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteGoods(id)
      })
    },
    // 删除
    async deleteGoods(id) {
      const res = await deleteGoods({ id })
      try {
        const { message, code } = res
        this.$message({
          message,
          type: code === 200 ? 'success' : 'error'
        })
        if (code === 200) {
          this.getList()
        }
      } catch (e) {
        let message = res.message ? res.message : e.message
        message = e.message ? e.message : '请求失败'
        this.$message.error(message)
      }
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.searchParams.page_size = limit
      this.searchParams.page_index = page
      this.getList()
    },
    // 查看商品详情
    handleSeeInfo(row) {
      const { id } = row
      this.getInfo(id)
    },
    // 查看商品详情
    async getInfo(id) {
      this.loadingFull = true
      try {
        const res = await getInfo({ id })
        const { message, code, data } = res
        if (code === 200) {
          this.goodsInfo = data
          this.dialogGoodsVisible = true
          this.loadingFull = false
        } else {
          this.$message.error(message)
          this.loadingFull = false
        }
      } catch (e) {
        console.log(`查看商品详情失败:${e}`)
        this.loadingFull = false
      }
    },
    // 商品详情sku展示
    skuShow(sku) {
      if (sku.length < 1) {
        return []
      }
      const item = sku[0]
      const keyArr = Object.keys(item)
      return keyArr
    },
    // 修改商品信息
    handleEdit(row) {
      const { id } = row
      this.$router.push({
        name: 'studioGoodEdit',
        params: { id }
      })
    },
    // 编号
    indexMethod(index) {
      const { page_index, page_size } = this.searchParams
      index += (page_index - 1) * page_size + 1
      return index
    }
  }
}
</script>

<style lang="scss" scoped>
.goods_info {
  width: 375px;
  margin: 0 auto;

  .banner_img {
    display: block;
    width: 100%;
    height: auto;
  }
}
</style>

<style lang="scss">
.goodsInfoDesc {
  img {
    display: block;
    width: 100%;
    height: auto;
  }
}
</style>
