<template>
  <div class="app-container">
    <div class="head-container">
      <el-row :gutter="20">
        <el-col :span="3">
          <el-input v-model="query.name" size="small" clearable placeholder="请输入商品名称" style="width: 100%;"
            class="filter-item" @keyup.enter.native="getTableData" />
        </el-col>
        <el-col :span="3">
          <el-select v-model="query.categoryId" placeholder="请选择商品分类" style="width: 100%;">
            <el-option :label="item.name" :value="item.id" v-for="item in categorys" :key="item.id" />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select v-model="query.typeEnum" placeholder="请选择商品规格" style="width: 100%;">
            <el-option :label="item.label" :value="item.typeEnum" v-for="item in typeEnums" :key="item.typeEnum" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="queryHandle">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="head-container">
      <el-row>
        <el-col>
          <router-link :to="{ name: 'add_shop' }">
            <el-button type="primary" icon="el-icon-plus">添加商品</el-button>
          </router-link>
        </el-col>
      </el-row>
    </div>
    <div class="head-container" id="table_drag">
      <el-table ref="table" :data="tableData.data" v-loading="tableData.loading" row-key="id"
        :tree-props="{ children: 'skuList', hasChildren: 'hasChildren' }">
        <el-table-column width="50px"></el-table-column>
        <el-table-column label="商品信息">
          <template v-slot="scope">
            <div class="shop_info">
              <el-image :src="scope.row.coverImg"
                style="width: 50px;height: 50px;border-radius: 4px;background-color: #efefef;"
                v-if="scope.row.coverImg">
                <div class="img_error" slot="error">
                  <i class="icon el-icon-document-delete"></i>
                </div>
              </el-image>
              <div class="info">
                <span>{{ scope.row.name }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="售价">
          <template v-slot="scope">
            <el-button type="text" v-if="scope.row.typeEnum == '多规格' && scope.row.skuList.length">
              {{ scope.row.lowPrice }}
            </el-button>
            <el-button type="text" v-else @click="changePrice('salePrice', scope.row,)">
              ￥{{ scope.row.lowPrice }}
              <i class="el-icon-edit"></i>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="商品规格" prop="typeEnum"></el-table-column>
        <el-table-column label="库存">
          <template v-slot="scope">
            <el-button type="text" v-if="scope.row.typeEnum" @click="changePrice('stockNumber', scope.row,)">
              {{ scope.row.stockNumber }}
              <i class="el-icon-edit"></i>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="耗材信息">
          <template v-slot="scope">
            <div v-if="scope.row.conInfos && scope.row.conInfos.length">
              <span v-for="item in scope.row.conInfos" :key="item.id">{{ item.conName }}、</span>
            </div>
            <el-button type="text" @click="showBindCons(scope.row)">
              绑定
              <i class="el-icon-edit"></i>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="上架">
          <template v-slot="scope">
            <!-- <el-button type="text" icon="el-icon-edit" v-if="scope.row.isShowCash">收银端</el-button>
            <el-button type="text" icon="el-icon-edit" v-if="scope.row.isShowMall">小程序</el-button>
            <el-button type="text" icon="el-icon-edit"
              v-if="!scope.row.isShowCash && !scope.row.isShowMall">未上架</el-button> -->
            <el-switch v-model="scope.row.isGrounding" :active-value="1" :inactive-value="0"
              @change="changeGrounding($event, scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sort" sortable />
        <el-table-column label="更新时间" prop="createdAt" width="150">
          <template v-slot="scope">
            {{ dayjs(scope.row.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="设为热门" prop="createdAt">
          <template v-slot="scope">
            <el-switch v-model="scope.row.isHot" :active-value="1" :inactive-value="0"
              @change="changeHot($event, scope.row)"></el-switch>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="150">
          <template v-slot="scope">
            <!-- <el-button type="text" icon="el-icon-rank" v-if="isPcBowser">排序</el-button> -->
            <!-- <router-link :to="{ path: '/product/add_shop', query: { goods_id: scope.row.id } }"
              style="margin-left: 20px !important;">
              <el-button type="text" icon="el-icon-edit">编辑</el-button>
            </router-link> -->
            <router-link :to="{ path: '/product/add_shop', query: { goods_id: scope.row.id } }">
              <el-button type="text" icon="el-icon-edit">编辑</el-button>
            </router-link>
            <el-popconfirm title="确定删除吗？" @confirm="delTableHandle([scope.row.id])">
              <el-button type="text" icon="el-icon-delete" style="margin-left: 20px !important;"
                slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="head-container">
      <el-pagination :total="tableData.total" @size-change="handleSizeChange" :current-page="tableData.page + 1"
        :page-size="tableData.size" @current-change="paginationChange"
        layout="total, sizes, prev, pager, next, jumper"></el-pagination>
    </div>
    <!-- 绑定耗材 -->
    <BindCons ref="bindCons" />
    <!-- 编辑售价、库存 -->
    <el-dialog :title="editorEumn[editorForm.key]" :visible.sync="editorVisable" :show-close="false" width="300px">
      <el-form :model="editorForm">
        <el-form-item>
          <el-input-number v-model="editorForm.value" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editorVisable = false">取 消</el-button>
        <el-button type="primary" :loading="editorFormLoading" @click="editorConfirmChange">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import dayjs from 'dayjs'
import settings from '@/settings'
import BindCons from './components/bindCons.vue'
import { tbProductListV2, tbShopCategoryGet, tbProductDelete, tbProductIsHot, upProSort, updateProductData } from '@/api/shop'
export default {
  components: {
    BindCons
  },
  data() {
    return {
      dayjs,
      query: {
        productId: '',
        name: '',
        categoryId: '',
        typeEnum: ''
      },
      categorys: [],
      typeEnums: settings.typeEnum,
      tableData: {
        data: [],
        page: 0,
        size: 30,
        loading: false,
        total: 0
      },
      editorEumn: {
        grounding: '上下架',
        pauseSale: '商品',
        stockNumber: '库存数量',
        salePrice: '售价'
      },
      editorVisable: false,
      editorFormLoading: false,
      editorForm: {
        shopId: localStorage.getItem('shopId'),
        isSku: '',
        id: '',
        key: '',
        value: ''
      }
    }
  },
  async mounted() {
    console.log(this.$route.query.productId, 'tiaoshi1')
    if (this.$route.query.productId) {
      this.query.productId = this.$route.query.productId
    }
    console.log(this.query)

    await this.tbShopCategoryGet()
    await this.getTableData()
    if (this.isPcBowser) {
      this.$nextTick(() => {
        this.tableDrag()
      })
    }
  },
  methods: {
    changeGrounding(event, row) {
      this.editorForm.key = 'grounding'
      this.editorForm.id = row.id
      this.editorForm.isSku = !row.typeEnum
      this.editorForm.value = event

      this.editorConfirmChange()
    },
    // 确认修改
    async editorConfirmChange() {
      try {
        this.editorFormLoading = true
        const res = await updateProductData([this.editorForm])
        this.editorFormLoading = false
        this.$message.success('修改成功')
        this.editorVisable = false
        this.getTableData()
      } catch (error) {
        console.log(error);
        this.editorFormLoading = false
      }
    },
    // 修改售价
    changePrice(type, row) {
      this.editorVisable = true
      this.editorForm.key = type
      this.editorForm.id = row.id
      this.editorForm.isSku = !row.typeEnum

      switch (type) {
        case 'salePrice':
          // 修改售价
          this.editorForm.value = row.lowPrice
          break;
        case 'stockNumber':
          // 修改库存
          this.editorForm.value = row.stockNumber
          break;
        default:
          break;
      }
    },
    // 显示绑定耗材
    showBindCons(item) {
      // console.log(item);
      this.$refs.bindCons.show(item)
    },
    // 选择分类
    queryHandle() {
      localStorage.setItem('shopIndexQuery', JSON.stringify(this.query))
      this.getTableData()
    },
    //表格拖拽
    tableDrag() {
      const el = document.querySelector('#table_drag .el-table__body-wrapper tbody')
      new Sortable(el, {
        animation: 150,
        onEnd: async e => {
          // console.log('拖拽结束===', e);
          if (e.oldIndex == e.newIndex) return
          let oid = this.tableData.data[e.oldIndex].id
          let nid = this.tableData.data[e.newIndex].id
          let ids = this.tableData.data.map(item => item.id)
          try {
            await upProSort({
              strId: oid,
              endId: nid,
              ids: ids
            })
            await this.getTableData()
          } catch (error) {
            console.log(error);
          }
        }
      });
    },
    // 设置热门
    async changeHot(e, row) {
      try {
        this.tableData.loading = true
        await tbProductIsHot({
          isHot: e,
          id: row.id
        })
        this.getTableData()
      } catch (error) {
        console.log(error);
      }
    },
    // 重置查询
    resetHandle() {
      this.query.name = ''
      this.query.categoryId = ''
      this.query.typeEnum = ''
      this.query.productId = ''
      this.tableData.page = 0
      localStorage.setItem('shopIndexQuery', JSON.stringify(this.query))
      this.getTableData()
    },
    // 分页回调
    paginationChange(e) {
      this.tableData.page = e - 1
      this.getTableData()
    },
    // 获取商品列表
    async getTableData() {
      try {
        let localQuery = JSON.parse(localStorage.getItem('shopIndexQuery'))
        if (localQuery != null && localQuery.hasOwnProperty('productId')) {
          // this.query = localQuery
        }

        this.tableData.loading = true
        console.log(this.query, '调试2')
        const res = await tbProductListV2({
          page: this.tableData.page,
          size: this.tableData.size,
          name: this.query.name,
          categoryId: this.query.categoryId,
          id: this.query.productId,
          type: this.query.typeEnum,
          shopId: localStorage.getItem('shopId')
        })
        this.tableData.loading = false
        this.tableData.data = res.content
        this.tableData.total = res.totalElements
      } catch (error) {
        console.log(error)
      }
    },
    handleSizeChange(val) {
      this.tableData.size = val
      this.getTableData()
    },
    // 获取商品分类列表
    async tbShopCategoryGet() {
      try {
        const res = await tbShopCategoryGet({
          shopId: localStorage.getItem('shopId'),
          page: 0,
          size: 100,
          sort: 'id'
        })
        this.categorys = res.content
      } catch (error) {
        console.log(error)
      }
    },
    // 删除商品
    async delTableHandle(ids) {
      try {
        await tbProductDelete(ids)
        this.getTableData()
      } catch (error) {
        console.log(error)
      }
    },
  }
}
</script>

<style scoped lang="scss">
.handle {
  font-size: 18px;
  color: #999;

  &:hover {
    cursor: grab;
  }
}

.shop_info {
  display: flex;

  .info {
    flex: 1;
    padding-left: 8px;
    display: flex;
    flex-direction: column;

    .tag_wrap {
      display: flex;
    }
  }
}
</style>
