<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-row v-if="storeList.length > 1">
              <el-col :span="24">
                <!-- <el-form-item 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 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-col>
            </el-row>
            <el-form-item label="商品名称">
              <el-input
                v-model="formInline.name"
                placeholder="商品名称搜索"
              ></el-input>
            </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
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :name="item.value"
            ></el-tab-pane>
          </el-tabs>
          <div class="mb-2">
            <el-button @click="addEarlyWarning" type="primary" size="small"
              >库存预警设置</el-button
            >
            <el-button
              :disabled="selectList.length <= 0"
              type="danger"
              size="small"
              @click="deleteProduct"
              >批量删除</el-button
            >
            <el-button type="primary" size="small" @click="addProduct"
              >添加商品</el-button
            >
          </div>
        </template>
      </obj-table-plus>
      <!-- 添加或编辑 -->
      <add-or-update
        :marketId="formInline.marketId"
        :shopId="formInline.shopId"
        @queryList="$refs.oTable.reload()"
        ref="addOrUpdate"
      ></add-or-update>
      <earlyWarning
        ref="earlyWarning"
        @queryList="$refs.oTable.reload()"
      ></earlyWarning>
      <!-- 查看商品 -->
      <viewProducts ref="viewProducts"></viewProducts>
    </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 viewProducts from "./popup/view-products.vue";
import AddOrUpdate from "./popup/add-or-update.vue";
import earlyWarning from "./popup/early-warning.vue";
export default {
  components: { earlyWarning, AddOrUpdate, viewProducts },
  data() {
    return {
      activeName: "5",
      advanceSellStatus: "",
      dataList: [],
      formInline: {
        name: "",
        marketId: "",
        shopId: "",
      },
      tableProp: {
        "auto-resize": true,
        border: true,
        height: "auto",
        "row-id": "id",
        "show-overflow": false,
      },
      statusList: [
        {
          label: "全部",
          value: "5",
        },
        {
          label: "未开始",
          value: "0",
        },
        {
          label: "进行中",
          value: "1",
        },
        {
          label: "已结束",
          value: "2",
        },
        {
          label: "已关闭",
          value: "3",
        },
      ],
      productFilterType: "SALE",
      selectList: [],
    };
  },
  created() {
    this.formInline = {
      marketId: this.marketId,
      shopId: this.shopId,
    };
    this.$nextTick(() => {
      this.$refs.oTable.reload();
    });
  },
  methods: {
    // getData() {
    //   this.$api.mer_admin
    //     .storeList({ marketId: this.formInline.marketId })
    //     .then((res) => {
    //       this.storeList = res.data.data;
    //       this.formInline.shopId = res.data.data[0].shopId;
    //       this.$nextTick(() => {
    //         this.$refs.oTable.reload();
    //       });
    //     });
    // },
    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.preSale
        .preSaleProducts({
          pageNumber: pageNo,
          pageSize: pageSize,
          ...this.formInline,
          advanceSellStatus: this.advanceSellStatus,
          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);
        });
    },
    Reset() {
      this.formInline = {
        name: "",
        marketId: this.marketId,
        shopId: this.shopId,
      };
      this.$refs.oTable.reload();
    },
    handleClick(e) {
      console.log(e.name);
      if (e.name == "5") {
        this.advanceSellStatus = "";
      } else {
        this.advanceSellStatus = e.name;
      }
      this.$refs.oTable.reload();
    },
    addEarlyWarning() {
      this.$refs.earlyWarning.toggle().add();
    },
  },
  computed: {
    tableCols() {
      return [
        { type: "checkbox", width: "60px", fixed: "left" },
        // { type: "seq", width: "60px", align: "center", title: "序号" },
        {
          title: "商品ID",
          align: "center",
          field: "id",
        },
        {
          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: "startTime",
          type: "jsx",
          render: ({ row }) => {
            return (
              <span>
                {row.startTime}至{row.endTime}
              </span>
            );
          },
        },
        {
          title: "尾款支付时间",
          align: "center",
          field: "minSalePrice",
          type: "jsx",
          render: ({ row }) => {
            return (
              <span>
                {row.balancePaymentStartTime}至{row.balancePaymentEndTime}
              </span>
            );
          },
        },
        {
          title: "预售价",
          align: "center",
          field: "presalePrice",
          type: "jsx",
          render: ({ row }) => {
            if (!row.productSpecificationList) {
              return <span>-</span>
            }
            if (
              Math.min.apply(
                Math,
                row.productSpecificationList.map((item) => item.presalePrice)
              ) ==
              Math.max.apply(
                Math,
                row.productSpecificationList.map((item) => item.presalePrice)
              )
            ) {
              return (
                <span>
                  {Math.min.apply(
                    Math,
                    row.productSpecificationList.map(
                      (item) => item.presalePrice
                    )
                  )}
                  元
                </span>
              );
            } else {
              return (
                <span>
                  {Math.min.apply(
                    Math,
                    row.productSpecificationList.map(
                      (item) => item.presalePrice
                    )
                  )}
                  元 ~
                  {Math.max.apply(
                    Math,
                    row.productSpecificationList.map(
                      (item) => item.presalePrice
                    )
                  )}{" "}
                  元
                </span>
              );
            }
          },
        },
        {
          title: "定金",
          align: "center",
          field: "earnestMoney",
          type: "jsx",
          render: ({ row }) => {
            if (!row.productSpecificationList) {
              return <span>-</span>
            }
            if (
              Math.min.apply(
                Math,
                row.productSpecificationList.map((item) => item.earnestMoney)
              ) ==
              Math.max.apply(
                Math,
                row.productSpecificationList.map((item) => item.earnestMoney)
              )
            ) {
              return (
                <span>
                  {Math.min.apply(
                    Math,
                    row.productSpecificationList.map(
                      (item) => item.earnestMoney
                    )
                  )}
                  元
                </span>
              );
            } else {
              return (
                <span>
                  {Math.min.apply(
                    Math,
                    row.productSpecificationList.map(
                      (item) => item.earnestMoney
                    )
                  )}{" "}
                  元 ~
                  {Math.max.apply(
                    Math,
                    row.productSpecificationList.map(
                      (item) => item.earnestMoney
                    )
                  )}{" "}
                  元
                </span>
              );
            }
          },
        },
        {
          title: "尾款",
          align: "center",
          field: "balancePayment",
          type: "jsx",
          render: ({ row }) => {
            if (!row.productSpecificationList) {
              return <span>-</span>
            }
            if (
              Math.min.apply(
                Math,
                row.productSpecificationList.map((item) => item.balancePayment)
              ) ==
              Math.max.apply(
                Math,
                row.productSpecificationList.map((item) => item.balancePayment)
              )
            ) {
              return (
                <span>
                  {Math.min.apply(
                    Math,
                    row.productSpecificationList.map(
                      (item) => item.balancePayment
                    )
                  )}
                  元
                </span>
              );
            } else {
              return (
                <span>
                  {Math.min.apply(
                    Math,
                    row.productSpecificationList.map(
                      (item) => item.balancePayment
                    )
                  )}
                  元 ~
                  {Math.max.apply(
                    Math,
                    row.productSpecificationList.map(
                      (item) => item.balancePayment
                    )
                  )}
                  元
                </span>
              );
            }
          },
        },
        {
          title: "状态",
          align: "center",
          field: "status",
          type: "jsx",
          render: ({ row }) => {
            if (row.advanceSellStatus == "0") {
              return <span>未开始</span>;
            } else if (row.advanceSellStatus == "1") {
              return <span>进行中</span>;
            } else if (row.advanceSellStatus == "2") {
              return <span>已结束</span>;
            } else if (row.advanceSellStatus == "3") {
              return <span>已关闭</span>;
            }
          },
        },
        {
          title: "操作",
          fixed: "right",
          type: "jsx",
          align: "center",
          width: "300px",
          render: ({ row }) => {
            let edit = () => {
              console.log(row);
              this.$refs.addOrUpdate.toggle(row).update();
            };
            let close = () => {
              this.$api.preSale
                .closePreSaleProducts({
                  productIds: [row.id],
                  advanceSellStatus: 3,
                })
                .then((res) => {
                  this.$refs.oTable.reload();
                });
            };
            let view = () => {
              this.$refs.viewProducts.toggle(row).update();
            };
            return (
              <div>
                <el-button size="mini" type="primary" onClick={view}>
                  查看
                </el-button>
                <el-button
                  v-show={
                    row.advanceSellStatus == "0" || row.advanceSellStatus == "1"
                  }
                  size="mini"
                  type="primary"
                  onClick={edit}
                >
                  编辑
                </el-button>
                <el-button
                  v-show={row.advanceSellStatus == "1"}
                  size="mini"
                  type="primary"
                  onClick={close}
                >
                  关闭
                </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></style>
