<template>
  <div class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />
    <el-tabs v-model="searchParams.status">
      <el-tab-pane label="全部" name="-1" />
      <el-tab-pane label="待上架" name="0" />
      <el-tab-pane label="已上架" name="1" />
      <el-tab-pane label="已下架" name="2" />
    </el-tabs>
    <div>
      <el-select
        v-model="searchParams.search_name"
        class="filter-item"
        placeholder="请选择类型"
        @change="
          searchParams.page_index = 1;
          getGoodStock();
        "
      >
        <el-option value="" label="全部" />
        <el-option
          v-for="(item, index) in attrList"
          :key="index"
          :value="item"
        />
      </el-select>
      <el-button type="primary" size="small" @click="exportStock">
        导出
      </el-button>
      <el-button v-read-excel="importStock" type="primary" size="small">
        导入
      </el-button>
      <!-- <el-button v-if="modifyStockId.length > 0" type="primary" @click="modifyStock = true">批量修改库存</el-button> -->
    </div>
    <el-table
      ref="listTable"
      :data="table"
      :header-cell-style="{ background: '#f8fbfc' }"
      class="tableBorder"
      border
      stripe
      @selection-change="orderMulSelect"
    >
      <!-- <el-table-column type="selection" width="50" align="center" :show-overflow-tooltip="true" /> -->
      <el-table-column prop="main_img" label="图片" width="70" align="center">
        <template slot-scope="{ row }">
          <el-image
            style="width: 40px; height: 40px"
            :src="row.main_img"
            fit="scale-down"
            class="hoverImg"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" align="center" />
      <el-table-column prop="size" label="款式" align="center" />
      <el-table-column prop="storage" label="总库存" align="center" />
      <!-- <el-table-column
        prop="goodstotal"
        label="总待出库数量"
        align="center"
      >
        <template slot="header" slot-scope="{ column }">
          <el-tooltip class="item" effect="dark" content="点击查看具体规格" placement="top">
            <i class="el-icon-info">{{ column.label }}</i>
          </el-tooltip>
        </template>
        <template slot-scope="{ row }">
          <el-button type="text" @click="showStockGood(row)">{{ row.goodstotal }}</el-button>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="{ row }">
          <el-button
            type="text"
            @click="showStockGood(row)"
          >查看变更记录</el-button>
          <el-button
            type="text"
            @click="toModifyStock(row)"
          >修改库存</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="batch-container">
      <!-- 分页 -->
      <pagination
        :total="tableTotal"
        :limit="searchParams.page_size"
        :page="searchParams.page_index"
        style="margin-top: 0"
        @pagination="changePagination"
        @update:limit="changePagination"
      />
    </div>
    <el-drawer
      title="库存变更记录"
      :visible.sync="visible.stock"
      direction="rtl"
    >
      <el-form label-width="20px">
        <el-form-item>
          <div
            v-for="(item, i) in stockGoogs"
            :key="i"
            style="line-height: 23px; border-bottom: 1px solid #ccc"
          >
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <p>{{ `管理员: ${item.admin_name}` }}</p>
              <p>{{ `修改时间: ${item.created_at}` }}</p>
            </div>
            <p>{{ `修改内容: ${item.text}` }}</p>
          </div>
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-dialog
      title="修改商品库存"
      :visible.sync="modifyStock"
      width="520px"
      :before-close="resetModifyStock"
    >
      <el-form label-width="100px">
        <el-form-item label="商品库存:">
          <el-input v-model="modifyStockNum" type="text" style="width: 300px" />
        </el-form-item>
        <el-form-item>
          <el-button @click="resetModifyStock">取消</el-button>
          <el-button type="primary" @click="toUpdateStock">修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
// api
import {
  getGoodStock,
  exportStock,
  updateStock,
  seeUpdate,
  importGoodStock
} from '@/api/stock/goods'
import { goodsAttr } from '@/api/goods/index'

export default {
  data() {
    return {
      searchParams: {
        search_name: '',
        page_size: 10,
        page_index: 1,
        status: '-1'
      },
      table: [],
      tableTotal: 0,
      stockGoogs: [],
      visible: {
        stock: false
      },
      loadingFull: false,
      modifyStock: false,
      modifyStockNum: '',
      modifyStockId: [],
      attrList: [], // 类型列表
      attr: ''
    }
  },
  watch: {
    'searchParams.status'() {
      this.getGoodStock()
    }
  },
  created() {
    this.getAttr()
    this.getGoodStock()
  },
  methods: {
    getAttr() {
      // 获取商品类型
      goodsAttr().then((res) => {
        if (res.code === 200) {
          this.attrList = res.data
        }
      })
    },
    async toUpdateStock() {
      if (this.modifyStockId.length < 1) {
        this.$message.error('请选择修改的商品')
        return false
      }
      if (!this.modifyStockNum) {
        this.$message.error('请输入新的商品库存')
        return false
      }
      this.loadingFull = true
      try {
        const res = await updateStock({
          ids: this.modifyStockId,
          num: this.modifyStockNum
        })
        if (res.code === 200) {
          this.$message.success('修改库存成功')
          this.resetModifyStock()
          this.getGoodStock()
        } else {
          this.$message.error(res.message)
        }
      } catch (e) {
        this.$message.error('修改商品库存失败')
      } finally {
        this.loadingFull = false
      }
    },
    importStock(list) {
      this.loadingFull = true
      console.log(list, 'pppp')
      importGoodStock({
        data: list
      })
        .then((res) => {
          this.loadingFull = false
          if (res.code === 200) {
            this.$message.success(res.message || '成功')
            this.getGoodStock()
          } else {
            this.$message.error(res.message || '批量修改失败')
          }
        })
        .catch((e) => {
          this.loadingFull = false
        })
    },
    resetModifyStock() {
      this.modifyStockNum = ''
      this.modifyStockId = []
      this.modifyStock = false
    },
    toModifyStock(row) {
      this.modifyStockId = [row.id]
      this.modifyStock = true
    },
    orderMulSelect(val) {
      this.modifyStockId = val.map((item) => item.id)
      console.log(this.modifyStockId)
    },
    async exportStock() {
      this.loadingFull = true
      try {
        const res = await exportStock({
          search_name: this.searchParams.search_name,
          status: this.searchParams.status
        })
        if (res.code === 200) {
          if (!res.data.list || res.data.list.length < 0) {
            this.$message.error('没有可导出数据')
          } else {
            const list = res.data.list.map((item) => ({
              商品id: item.id,
              商品名称: item.name,
              款式: item.size,
              总库存: item.storage
            }))
            import('@/vendor/Export2Excel').then((excel) => {
              excel.export_json_to_excel({
                header: Object.keys(list[0]),
                data: list.map((listItem) =>
                  Object.keys(list[0]).map((j) => listItem[j])
                ),
                filename: `${new Date().toLocaleDateString()}商品库存`,
                bookType: 'xlsx'
              })
            })
          }
        }
      } catch (e) {
        this.$message.error('导出失败')
      } finally {
        this.loadingFull = false
      }
    },
    // 获取列表
    async getGoodStock() {
      this.loadingFull = true
      try {
        const res = await getGoodStock(this.searchParams)
        const { code, message } = res
        if (code === 200) {
          const { data } = res
          const { total, list } = data
          this.tableTotal = total
          this.table = list
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error('获取商品库存失败!!')
      }
      this.loadingFull = false
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.searchParams.page_size = limit
      this.searchParams.page_index = page
      this.getGoodStock()
    },
    // 查看库存规格
    showStockGood(row) {
      const { id } = row
      this.loadingFull = true
      seeUpdate({ id })
        .then((res) => {
          this.loadingFull = false
          if (res.code === 200) {
            this.visible.stock = true
            this.stockGoogs = res.data
          }
        })
        .catch((e) => {
          this.loadingFull = false
          this.$message.error('查看变更记录失败')
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.tableBorder {
  border: 1px solid #ebeef5;
  margin: 20px 0;
}
</style>
