<template>
  <div>
    <div v-if="isMerchant" style="height: calc(100vh - 200px)">
      <obj-table-plus
        ref="oTable"
        style="height: 100%"
        :tableCols="tableCols"
        :tableProp="tableProp"
        @query="queryList"
        v-model="dataList"
        :tableEvent="tableEvent"
        :enableAutoQuery="false"
      >
        <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
                @change="getData"
                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 v-if="marketList.length > 0" label="店铺">
              <el-select v-model="formInline.shopId" placeholder="请选择店铺">
                <el-option
                  v-for="item in storeList"
                  :key="item.shopId"
                  :label="item.shopName"
                  :value="item.shopId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否预售商品">
              <el-select
                v-model="formInline.isAdvanceSell"
                placeholder="请选择是否预售"
              >
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></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>
          <div class="stat-list">
            <div class="stat-item">
              <i style="font-size: 22px" class="el-icon-s-goods"></i>
              <div class="stat-right">
                <div class="stat-title">总商品数量（个）</div>
                <div class="stat-value">
                  <span style="font-size: 20px">{{
                    overview.productCount
                  }}</span>
                </div>
              </div>
            </div>
            <div class="stat-item">
              <i style="font-size: 22px" class="el-icon-s-shop"></i>
              <div class="stat-right">
                <div class="stat-title">上架中商品数量（个）</div>
                <div class="stat-value">
                  <span style="font-size: 20px">{{
                    overview.productOnSaleCount
                  }}</span>
                </div>
              </div>
            </div>
            <div class="stat-item">
              <i style="font-size: 22px" class="el-icon-s-marketing"></i>
              <div class="stat-right">
                <div class="stat-title">折扣商品数量（个）</div>
                <div class="stat-value">
                  <span style="font-size: 20px">{{
                    overview.productDiscountCount
                  }}</span>
                </div>
              </div>
            </div>
            <div class="stat-item">
              <i style="font-size: 22px" class="el-icon-s-promotion"></i>
              <div class="stat-right">
                <div class="stat-title">仓库中商品数量（个）</div>
                <div class="stat-value">
                  <span style="font-size: 20px">{{
                    overview.productWarehouseCount
                  }}</span>
                </div>
              </div>
            </div>
          </div>
          <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 { mapState } from "vuex";
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: "",
        shopId: "",
        isAdvanceSell: 0
      },
      tableProp: {
        "auto-resize": true,
        border: true,
        height: "auto",
        "row-id": "id",
        "show-overflow": false
      },
      productFilterType: "SALE",
      selectList: [],
      overview: {}
    };
  },
  created() {
    this.formInline = {
      name: "",
      marketId: this.marketId,
      shopId: this.shopId,
      isAdvanceSell: 0
    };
    this.$nextTick(() => {
      this.$refs.oTable.reload();
    });
  },
  methods: {
    //如果有多个菜市场调用
    getData() {
      // this.$api.mer_admin
      //   .storeList({ marketId: this.formInline.marketId })
      //   .then((res) => {
      //     this.formInline.shopId = res.data.data[0].shopId;
      //     this.$nextTick(() => {
      //       this.$refs.oTable.reload();
      //     });
      //   });
    },
    addProduct() {
      this.$refs.addOrUpdate.toggle().add(this.formInline.shopId);
    },
    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) {
      console.log(this.formInline);
      this.$api.mer_admin
        .getProductPage({
          p: {
            pageNumber: pageNo,
            pageSize: pageSize
          },
          ...this.formInline,
          productFilterType: this.productFilterType,
          merchantId: JSON.parse(sessionStorage.getItem("userInfo")).merchantId,
          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);
        });
      this.$api.mer_admin.getProductOverview(this.formInline).then(res => {
        console.log(res, "概况");
        this.overview = res.data.data;
      });
    },
    Reset() {
      this.formInline = {
        name: "",
        marketId: this.marketId,
        shopId: this.shopId,
        isAdvanceSell: 0
      };
      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: "是否为预售商品",
          align: "center",
          field: "isAdvanceSell",
          type: "jsx",
          render: ({ row }) => {
            return <span>{row.isAdvanceSell == 1 ? "是" : "否"}</span>;
          }
        },
        {
          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 = () => {
              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];
        }
      };
    },
    ...mapState("userData", [
      "isMerchant",
      "marketList",
      "storeList",
      "marketId",
      "shopId"
    ])
  }
};
</script>

<style lang="scss" scoped>
.stat-list {
  display: flex;
  align-items: center;
  /* justify-content: space-between; */
  // flex-wrap: wrap;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
}
.stat-item {
  width: 20%;
  margin: 20px 20px;
  display: flex;
  align-items: center;
}
.stat-right {
  margin-left: 12px;
  font-size: 18px;
}
.stat-title {
  margin-bottom: 5px;
}
</style>
