<template>
  <div>
    <div v-if="shopId" style="height: calc(100vh - 200px)">
      <obj-table-plus
        ref="oTable"
        style="height: 100%"
        :tableCols="tableCols"
        :tableProp="tableProp"
        @query="queryList"
        v-model="dataList"
        :tableEvent="tableEvent"
      >
        <template slot="tableTop">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <!-- <el-form-item label="平台分类">
              <el-select v-model="formInline.region" placeholder="活动区域">
                <el-option label="区域一" value="shanghai"></el-option>
                <el-option label="区域二" value="beijing"></el-option>
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="商户分类">
              <el-select v-model="formInline.region" placeholder="活动区域">
                <el-option label="区域一" value="shanghai"></el-option>
                <el-option label="区域二" value="beijing"></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item label="商品搜索">
              <el-input
                v-model="formInline.name"
                placeholder="商品搜索"
              ></el-input>
            </el-form-item>
            <el-form-item v-if="marketList.length > 0" label="摊铺">
              <el-select v-model="formInline.marketId" placeholder="请选择摊铺">
                <el-option
                  v-for="item in marketList"
                  :key="item.marketId"
                  :label="item.marketName"
                  :value="item.marketId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="$refs.oTable.reload()"
                >查询</el-button
              >
              <el-button type="primary" @click="Reset">重置</el-button>
            </el-form-item>
          </el-form>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="在售" name="在售"></el-tab-pane>
            <el-tab-pane label="仓库中" name="仓库中"></el-tab-pane>
            <el-tab-pane label="折扣" name="折扣"></el-tab-pane>
          </el-tabs>
          <div class="mb-2">
            <el-button type="primary" size="small" @click="addProduct"
              >添加商品</el-button
            >
            <el-button
              :disabled="selectList.length <= 0"
              type="danger"
              size="small"
              @click="deleteProduct"
              >批量删除</el-button
            >
          </div>
        </template>
      </obj-table-plus>
      <!-- 添加或编辑 -->
      <add-or-update
        @queryList="$refs.oTable.reload()"
        ref="addOrUpdate"
      ></add-or-update>
      <!-- 改价格 -->
      <AddPrice ref="AddPrice" @queryList="$refs.oTable.reload()"></AddPrice>
      <!-- 改库存 -->
      <addStock ref="addStock" @queryList="$refs.oTable.reload()"></addStock>
      <!-- 打折扣 -->
      <AddDiscount
        ref="AddDiscount"
        @queryList="$refs.oTable.reload()"
      ></AddDiscount>
    </div>
    <div style="height: calc(100vh - 200px)" v-else>
      <el-empty :image-size="200" description="请先去完成商品哦"></el-empty>
    </div>
  </div>
</template>

<script>
import AddDiscount from "./popup/add-discount.vue";
import AddPrice from "./popup/add-price.vue";
import AddOrUpdate from "./popup/add-or-update.vue";
import addStock from "./popup/add-stock.vue";
export default {
  components: { AddOrUpdate, AddPrice, addStock, AddDiscount },
  data() {
    return {
      activeName: "在售",
      dataList: [],
      formInline: {
        name: "",
        marketId: "",
      },
      marketList: [],
      tableProp: {
        "auto-resize": true,
        border: true,
        height: "auto",
        "row-id": "id",
        "show-overflow": false,
      },
      productFilterType: "SALE",
      selectList: [],
      shopId: "",
    };
  },
  created() {
    if (JSON.parse(sessionStorage.getItem("userInfo")).markets.length > 0) {
      this.shopId = true;
      this.formInline.marketId = JSON.parse(
        sessionStorage.getItem("userInfo")
      ).markets[0].marketId;
      this.marketList = JSON.parse(sessionStorage.getItem("userInfo")).markets;
      console.log(this.marketList);
    } else if (JSON.parse(sessionStorage.getItem("userInfo")).shopId) {
      this.shopId = true;
    } else {
      this.shopId = false;
    }
  },
  methods: {
    addProduct() {
      this.$refs.addOrUpdate.toggle().add();
    },
    deleteProduct() {
      console.log(this.selectList);
      let integers = this.selectList.map((item) => {
        return item.id;
      });
      this.$confirm("此操作将删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("111");
          this.$api.mer_admin.BatchDeleteProducts(integers).then((res) => {
            this.$refs.oTable.reload();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    queryList(pageNo, pageSize) {
      this.$api.mer_admin
        .getProductPage({
          p: {
            pageNumber: pageNo,
            pageSize: pageSize,
          },
          ...this.formInline,
          productFilterType: this.productFilterType,
          merchantId: JSON.parse(sessionStorage.getItem("userInfo")).merchantId,
          shopId: JSON.parse(sessionStorage.getItem("userInfo")).shopId,
          productQuerySortParam: [],
        })
        .then((res) => {
          console.log(res);
          this.$refs.oTable.complete(
            res.data.data.data,
            Number(res.data.data.total)
          );
        })
        .catch((err) => {
          this.$refs.oTable.complete(false);
        });
    },
    Reset() {
      this.formInline = {
        name: "",
        marketId: JSON.parse(sessionStorage.getItem("userInfo")).markets[0]
          .marketId,
      };
      this.$refs.oTable.reload();
    },
    handleClick() {
      switch (this.activeName) {
        case "在售":
          this.productFilterType = "SALE";
          break;
        case "仓库中":
          this.productFilterType = "WAREHOUSE";
          break;
        case "折扣":
          this.productFilterType = "DISCOUNT";
          break;
      }
      this.$refs.oTable.reload();
    },
  },
  computed: {
    tableCols() {
      return [
        { type: "checkbox", width: "60px", fixed: "left" },
        // { type: "seq", width: "60px", align: "center", title: "序号" },
        {
          title: "商品图",
          field: "productPhotoList",
          align: "center",
          width: "80px",
          type: "jsx",
          render: ({ row }) => {
            if (row.productPhotoList.length > 0) {
              return (
                <el-image
                  preview-src-list={row.productPhotoList.map((item) => {
                    return item.url;
                  })}
                  src={row.productPhotoList[0].url}
                ></el-image>
              );
            } else {
              return <span>暂无商品图</span>;
            }
          },
        },
        {
          title: "商品名称",
          align: "center",
          field: "name",
        },
        {
          title: "商品售价",
          align: "center",
          field: "minSalePrice",
          type: "jsx",
          render: ({ row }) => {
            if (row.minSalePrice == row.maxSalePrice) {
              return <span>￥{row.minSalePrice}</span>;
            } else {
              return (
                <span>
                  ￥{row.minSalePrice}~￥{row.maxSalePrice}
                </span>
              );
            }
          },
        },
        {
          title: "折扣",
          align: "center",
          field: "discountActivity",
          type: "jsx",
          render: ({ row }) => {
            if (row.discountActivity) {
              return <span>{row.discountActivity.ruleObject.discount}折</span>;
            }
          },
        },
        {
          title: "销量",
          align: "center",
          field: "saleNum",
        },
        {
          title: "库存",
          align: "center",
          field: "stockNum",
        },
        {
          title: "状态",
          // fixed: "right",
          type: "jsx",
          align: "center",
          "title-suffix": {
            message: "点击上架/下架切换责任书状态",
            icon: "vxe-icon-question-circle-fill",
          },
          render: ({ row }) => {
            let Enable = () => {
              let data = {
                ids: [row.id],
                status: "UP",
              };
              if (row.status == "UP") {
                data.status = "DOWN";
              } else {
                data.status = "UP";
              }
              this.$api.mer_admin.putOnShelvesProducts(data).then((res) => {
                console.log(res);
                this.$refs.oTable.reload();
              });
            };
            return (
              <el-popconfirm
                title={
                  row.status == "DOWN"
                    ? "当前为下架状态，是否更改为上架状态？"
                    : "当前为上架状态，是否更改为下架状态？"
                }
                confirmButtonText={
                  row.status == "DOWN" ? "确认上架" : "确认下架"
                }
                onConfirm={Enable}
              >
                <el-button
                  slot="reference"
                  size="mini"
                  plain
                  type={row.status == "DOWN" ? "info" : "success"}
                >
                  {row.status == "DOWN" ? "已下架" : "上架中"}
                </el-button>
              </el-popconfirm>
            );
          },
        },
        {
          title: "操作",
          fixed: "right",
          type: "jsx",
          align: "center",
          width: "340px",
          render: ({ row }) => {
            let edit = () => {
              console.log(row);

              this.$refs.addOrUpdate.toggle(row).update();
            };
            let priceAdjustment = () => {
              console.log(row);
              this.$refs.AddPrice.toggle(row).update();
            };
            let changeInventory = () => {
              this.$refs.addStock.toggle(row).update();
            };
            let setDiscounts = () => {
              this.$refs.AddDiscount.toggle(row).update();
            };
            return (
              <div>
                <el-button
                  size="mini"
                  disabled={row.status != "DOWN"}
                  type="primary"
                  onClick={edit}
                >
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  disabled={row.status != "DOWN"}
                  type="primary"
                  onClick={priceAdjustment}
                >
                  改价
                </el-button>
                <el-button
                  size="mini"
                  disabled={row.status != "DOWN"}
                  type="primary"
                  onClick={changeInventory}
                >
                  改库存
                </el-button>
                <el-button
                  size="mini"
                  disabled={row.status != "DOWN"}
                  type="primary"
                  onClick={setDiscounts}
                >
                  设置折扣
                </el-button>
              </div>
            );
          },
        },
      ];
    },
    tableEvent() {
      return {
        "checkbox-all": ({ records, reserves }) => {
          this.selectList = [...records, ...reserves];
        },
        "checkbox-change": ({ records, reserves }) => {
          this.selectList = [...records, ...reserves];
        },
      };
    },
  },
};
</script>

<style lang="scss" scoped></style>