<template>
  <div class="good-list-con">
    <Card>
      <div class="search-con">
        <Input
          placeholder="请输入商品编号"
          class="search-input"
          v-model="searchContent.goodsId"
          style="width: 180px"
          clearable
        />
        <!-- .trim -->
        <Input
          placeholder="请输入商品名称"
          class="search-input"
          v-model="searchContent.goodsName"
          style="width: 180px"
          clearable
        />
        <Select
          placeholder="请选择商品类型"
          class="search-input"
          v-model="searchContent.goodsType"
          v-if="isBrand"
          style="width: 180px"
        >
          <Option value>全部</Option>
          <Option
            v-for="(item, index) of ShopType"
            :value="item"
            :key="'series-option-' + index"
            >{{ ShopTypeObj[item].label }}</Option
          >
        </Select>
        <Select
          placeholder="请选择状态"
          class="search-input"
          v-model="searchContent.status"
          v-if="isBrand"
          style="width: 180px"
        >
          <Option value>全部</Option>
          <Option
            v-for="(item, index) of seriesList"
            :value="item.series_id"
            :key="'series-option-' + index"
            >{{ item.series_name }}</Option
          >
        </Select>
        <DatePicker
          placeholder="开始时间至结束时间"
          v-model="createTime"
          type="daterange"
          placement="bottom-start"
          class="search-date"
          @on-change="handleDateChange(createTime)"
          :editable="false"
          separator=" ~ "
        ></DatePicker>
        <ButtonGroup class="search-btngroup">
          <Button @click="handleSearch" type="primary">搜索</Button>
          <Button type="primary" @click="handleRefresh">
            <Icon type="md-refresh" />
          </Button>
        </ButtonGroup>
        <Button type="info" @click="handleAdd" v-if="!platform"
          >+ 添加商品</Button
        >
        <Button
          type="error"
          v-if="!platform"
          @click="batchDel"
          style="margin-left: 10px"
        >
          批量删除
        </Button>
      </div>
      <tables
        ref="tables"
        editable
        pagable
        v-model="tableData"
        :columns="newColumns"
        :currentPage="searchContent.pageNum"
        :pageSize="searchContent.pageSize"
        :totalSize="totalSize"
        :loading="loading"
        @on-change="handleCurrentChange"
        @on-selection-change="changeSelect"
      />
    </Card>
    <Modal
      v-model="detailModal"
      :width="400"
      @on-ok="OffShelfModalOk"
      @on-cancel="detailModal = false"
      :title="formData.title"
    >
      <div class="OffShelfModal">
        <div class="content">
          <p v-if="formData.type === 2">
            商品 {{ formData.name }} 上架{{
              formData.date ? "预热" : ""
            }}中，确定要下架吗？
          </p>
          <p v-else>请为商品 {{ formData.name }} 选择上架方式</p>
        </div>
        <div class="form-content">
          <div class="flex-between">
            <template v-if="formData.type === 2">
              <p v-if="formData.preheatEndTime">
                开售时间 : {{ formData.preheatEndTime }}
              </p>
            </template>
            <template v-else>
              <Form ref="loginForm" :model="formData">
                <FormItem prop="account">
                  <RadioGroup v-model="formData.type">
                    <Radio :label="1">立即上架开售</Radio>
                  </RadioGroup>
                </FormItem>
                <FormItem prop="password">
                  <RadioGroup v-model="formData.type">
                    <Radio :label="10"
                      >上架预热<span
                        style="display: inline-block; width: 10px"
                      ></span>
                     
                    </Radio>
                  </RadioGroup>
                   <DatePicker
                        type="datetime"
                        format="yyyy-MM-dd HH:mm"
                        :options="optionsDate"
                        @on-change="changeFormDataDate"
                        v-model="formData.date"
                        placeholder="请选择日期"
                        style="width: 200px"
                      ></DatePicker>
                </FormItem>
              </Form>
            </template>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
import Tables from "_c/tables";
import { formatTime } from "@/libs/tools";
import {
  OffShelfType,
  OffShelfTypeObj,
  ShopType,
  ShopTypeObj,
  SalesTypeObj,
  SalesType,
} from "@/enums";
export default {
  inject: ["reload"],
  components: {
    Tables,
  },
  computed: {
    isBrand() {
      return this.$store.getters.isBrand;
    },
    platform() {
      return (
        this.$store.state.admin.type == 1 || this.$store.state.admin.type == 4
      );
    },
    newColumns() {
      if (!this.platform) {
        return this.columns.filter((item) => {
          return item.key !== "enterpriseName";
        });
      } else {
        return this.columns;
      }
    },
  },
  data() {
    return {
      OffShelfType,
      OffShelfTypeObj,
      ShopType,
      ShopTypeObj,
      SalesType,
      SalesTypeObj,
      searchContent: {
        goodsId: "",
        goodsName: "",
        goodsType: "",
        status: "",
        addTimeHead: "",
        addTimeTail: "",
        pageNum: 1,
        pageSize: 10,
      },
      createTime: [],
      seriesList: [
        {
          series_id: 1,
          series_name: "已上架",
        },
        {
          series_id: 2,
          series_name: "已下架",
        },
        {
          series_id: 3,
          series_name: "发行中",
        },
        {
          series_id: 4,
          series_name: "失败",
        },
        {
          series_id: 5,
          series_name: "待审核",
        },
        {
          series_id: 6,
          series_name: "已驳回",
        },
        {
          series_id: 7,
          series_name: "待上架",
        },
        {
          series_id: 8,
          series_name: "已取消",
        },
        {
          series_id: 9,
          series_name: "草稿",
        },
      ],
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        { title: "编号", key: "goodsId", minWidth: 180, align: "left" },
        { title: "名称", key: "name", width: 180, align: "center" },
        {
          title: "商品类型",
          align: "center",
          width: 100,
          render: (h, params) => {
            let obj = ShopTypeObj[params.row.type];
            return h("span", obj.label);
          },
        },
        // {
        //   title: '应用NFT',
        //   align: 'center',
        //   width: 100,
        //   render: (h, params) => {
        //     // let obj = SalesTypeObj[params.row.useNft]
        //     return h(
        //       'span',
        //       (params.row.useNft == 0 ? '否' : (params.row.useNft == 1 ? '是' : '--'))
        //     )
        //   }
        // },
        {
          title: "销售模式",
          align: "center",
          width: 100,
          render: (h, params) => {
            let obj = SalesTypeObj[params.row.salesType];
            return h("span", obj ? obj.label : "--");
          },
        },
        {
          title: "展示图",
          key: "thumb",
          width: 100,
          align: "center",
          render: (h, params) => {
            return h(
              "div",
              {
                style: {
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  height: "70px",
                  // display: params.row.thumb != '' ? 'inline-block' : 'none'
                },
              },
              [
                h("img", {
                  attrs: {
                    src: params.row.thumb,
                  },
                  style: {
                    width: "70px",
                    height: "50px",
                    objectFit: "fill",
                    display: params.row.thumb != "" ? "inline-block" : "none",
                  },
                }),
              ]
            );
          },
        },
        {
          title: "价格",
          key: "price",
          width: 130,
          align: "center",
          render: (h, params) => {
            // let minPrice = params.row.defaultPrice
            // let maxPrice = params.row.maxPrice
            return h(
              "div",
              params.row.section
              // minPrice + ' -- ' + maxPrice
            );
          },
        },
        // { title: '库存量',
        //   key: 'stock',
        //   width: 100,
        //   align: 'center',
        //   render: (h, params) => {
        //     return h(
        //       'div',
        //       params.row.stock ? params.row.stock : '--'
        //     )
        //   }
        // },
        { title: "库存量", key: "stock", width: 100, align: "center" },
        { title: "销售量", key: "sales", width: 100, align: "center" },
        // { title: '销售量',
        //   key: 'sales',
        //   width: 100,
        //   align: 'center',
        //   render: (h, params) => {
        //     return h(
        //       'div',
        //       params.row.sales ? params.row.sales : '--'
        //     )
        //   } },
        {
          title: "商家",
          key: "enterpriseName",
          width: 150,
          align: "center",
          render: (h, params) => {
            return h(
              "div",
              {
                style: {
                  color: "#5296ee",
                },
              },
              [
                h(
                  "Poptip",
                  {
                    props: {
                      trigger: "hover",
                      title: `联系人:${params.row.linkName}  联系方式:${params.row.linkPhone}`,
                      size: "small",
                    },
                  },
                  params.row.enterpriseName
                ),
              ]
            );
          },
        },

        {
          title: "状态",
          key: "status",
          align: "center",
          width: 100,
          render: (h, params) => {
            let obj = OffShelfTypeObj[params.row.status] || {};
            return h(
              "Tag",
              {
                props: {
                  color: obj.color,
                },
              },
              obj.label
            );
          },
        },
        {
          title: "失败理由",
          width: 130,
          align: "center",
          render: (h, params) => {
            return h(
              "div",
              params.row.checkFailReason ? params.row.checkFailReason : "--"
            );
          },
        },
        {
          title: "入库时间",
          align: "center",
          width: 180,
          render: (h, params) => {
            return h("span", formatTime(params.row.createTime));
          },
        },
        {
          title: "操作",
          key: "name",
          align: "left",
          minWidth: 180,
          maxWidth: 300,
          fixed: "right",
          render: (h, params) => {
            let status = params.row.status;
            let platform = this.platform;
            let detailBtn = h(
              "Button",
              {
                props: {
                  type: "primary",
                  size: "small",
                },
                style: {
                  margin: "5px",
                },
                on: {
                  click: this.handleDetail(params.row),
                },
              },
              "详 情"
            );
            let editBtn = h(
              "Button",
              {
                props: {
                  type: "primary",
                  size: "small",
                },
                on: {
                  click: this.handleUpdate(params.row),
                },
                style: {
                  margin: "5px",
                  //   display: this.isBrand ? 'inline-block' : 'none'
                  display:
                    status == OffShelfType.SHELVES ? "inline-block" : "none",
                },
              },
              "编 辑"
            );
            let draftBtn = h(
              "Button",
              {
                props: {
                  type: "primary",
                  size: "small",
                },
                on: {
                  click: this.handleDraft(params.row),
                },
                style: {
                  margin: "5px",
                  //   display: this.isBrand ? 'inline-block' : 'none'
                  display:
                    status == OffShelfType.DRAFT ||
                    status == OffShelfType.OFFERING ||
                    status == OffShelfType.CHECK_FAIL ||
                    status == OffShelfType.FAIL
                      ? "inline-block"
                      : "none",
                },
              },
              "编 辑"
            );
            let offShelfBtn = h(
              "Button",
              {
                props: {
                  type: status == OffShelfType.SHELVES ? "primary" : "primary",
                  size: "small",
                },
                on: {
                  click: this.handleOffShelf(params.row),
                },
                style: {
                  margin: "5px",
                  display:
                    ((status == OffShelfType.OFFERING ||
                      status == OffShelfType.SHELVES ||
                      status == OffShelfType.PREHEAT) &&
                      !platform) ||
                    status == OffShelfType.GROUNDING
                      ? "inline-block"
                      : "none",
                },
              },
              status == OffShelfType.OFFERING || status == OffShelfType.SHELVES
                ? "上 架"
                : "下 架"
            );
            let delBtn = h(
              "Button",
              {
                props: {
                  type: "error",
                  size: "small",
                },
                on: {
                  click: this.handleDel(params.row),
                },
                style: {
                  margin: "5px",
                  display:
                    status == OffShelfType.SHELVES ||
                    status == OffShelfType.CANCELED
                      ? "inline-block"
                      : "none",
                },
              },
              "删 除"
            );
            let cancelBtn = h(
              "Button",
              {
                props: {
                  type: "primary",
                  size: "small",
                },
                on: {
                  click: this.handleCancel(params.row),
                },
                style: {
                  margin: "5px",
                  display:
                    status == OffShelfType.AUDIT ? "inline-block" : "none",
                },
              },
              "取 消"
            );
            let withdrawBtn = h(
              "Button",
              {
                props: {
                  type: "primary",
                  size: "small",
                },
                on: {
                  click: this.handleWithdraw(params.row),
                },
                style: {
                  margin: "5px",
                  display:
                    status == OffShelfType.AUDIT ? "inline-block" : "none",
                },
              },
              "撤 回"
            );
            return h("div", [
              detailBtn,
              !this.platform && editBtn,
              offShelfBtn,
              !this.platform && cancelBtn,
              !this.platform && delBtn,
              !this.platform && draftBtn,
              !this.platform && withdrawBtn,
            ]);
          },
        },
      ],
      tableData: [],
      totalSize: 0,
      loading: false,
      selectList: [],
      selectCount: 0,
      detailModal: false,
      formData: {
        goodsId: "",
        preheatEndTime: "",
        date: "",
        tiem: "",
        type: 1,
        title: "",
        name: "",
        date: "",
      },
      optionsDate: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        },
      },
    };
  },
  methods: {
    requestData() {
      this.loading = true;
      this.searchContent.goodsId = this.searchContent.goodsId.replace(
        /\s+/g,
        ""
      );
      this.searchContent.goodsName = this.searchContent.goodsName.replace(
        /\s+/g,
        ""
      );
      this.api({
        apiName: "getGoodList",
        postdata: this.searchContent,
        complete: () => {
          this.loading = false;
        },
        success: (res) => {
          this.tableData = res.data.records;
          this.totalSize = res.data.total;
          this.tableData.forEach((item) => {
            if (item.status != 2 && item.status != 8) {
              item._disabled = true;
            }
          });
        },
      });
    },
    requestSeries() {
      //   this.api({
      //     apiName: 'getSeriesList',
      //     success: (res) => {
      //       this.seriesList = res.data
      //     }
      //   })
    },
    handleSearch() {
      this.searchContent.pageNum = 1;
      this.requestData();
    },
    handleRefresh() {
      this.reload();
    },
    handleDel(row) {
      return () => {
        this.$Modal.confirm({
          title: "删除",
          content: `您确认要删除名称为${row.name} 的商品？`,
          onOk: () => {
            this.api({
              apiName: "deleteGood",
              postdata: [row.goodsId],
              success: () => {
                this.requestData();
                this.$Notice.success({ title: `操作成功！` });
              },
            });
          },
        });
      };
    },
    batchDel() {
      if (this.selectCount <= 0) {
        this.$Message.warning("您还未选择要删除的数据");
        return false;
      }
      let goodsIds = this.selectList;
      this.$Modal.confirm({
        title: "删除",
        content: `您确认要删除所选的 ${this.selectCount}条数据？`,
        onOk: () => {
          this.api({
            apiName: "deleteGood",
            postdata: goodsIds,
            success: () => {
              this.requestData();
              this.$Notice.success({ title: `操作成功！` });
            },
          });
        },
      });
    },
    handleCurrentChange(pageNum) {
      this.searchContent.pageNum = pageNum;
      this.requestData();
    },
    changeSelect(e) {
      this.selectList = e.map((item) => {
        return item.goodsId;
      });
      this.selectCount = e.length;
    },
    handleDateChange(createTime) {
      if (
        createTime &&
        createTime.length == 2 &&
        createTime[0] &&
        createTime[1]
      ) {
        this.searchContent.addTimeHead = new Date(createTime[0]).getTime();
        this.searchContent.addTimeTail =
          new Date(createTime[1]).getTime() + 24 * 60 * 60 * 1000 - 1;
      } else {
        this.searchContent.addTimeHead = "";
        this.searchContent.addTimeTail = "";
      }
    },

    handleAdd() {
      this.$router.push({ name: "add_good" });
    },
    handleUpdate(row) {
      return () => {
        let query = { goodsId: row.goodsId };
        this.$router.push({
          name:
            row.commodityPass == 3 ? "commodity_update_good" : "update_good",
          query,
        });
      };
    },
    handleDraft(row) {
      return () => {
        let query = { goodsId: row.goodsId };
        this.$router.push({
          name: row.commodityPass == 3 ? "commodity_draft_good" : "draft_good",
          query,
        });
      };
    },
    handleWithdraw(row) {
      return () => {
        let goodsId = row.goodsId;
        this.$Modal.confirm({
          content: `确认要撤回审核名称为 ${row.name} 的商品 ？`,
          onOk: () => {
            this.api({
              apiName: "withdrawGood",
              postdata: goodsId,
              success: () => {
                this.requestData();
                this.$Notice.success({ title: `撤回成功！` });
              },
            });
          },
        });
      };
    },
    handleDetail(row) {
      return () => {
        let query = { goodsId: row.goodsId };
        this.$router.push({
          name:
            row.commodityPass == 3 ? "commodity_good_detail" : "good_detail",
          query,
        });
      };
    },
    handleOffShelf(row) {
      return () => {
        let goodsId = row.goodsId;
        let type =
          row.status == OffShelfType.OFFERING ||
          row.status == OffShelfType.SHELVES
            ? OffShelfType.GROUNDING
            : OffShelfType.SHELVES;
        let title =
          row.status == OffShelfType.OFFERING ||
          row.status == OffShelfType.SHELVES
            ? "上架"
            : "下架";
        let salesType = row.salesType;
        if (salesType === 1|| salesType === 4) {
          this.OffShelfModal(
            goodsId,
            type,
            title,
            row.name,
            row.preheatEndTime,
            row.status
          );
        } else {
          this.$Modal.confirm({
            title,
            content: `确认要${title}名称为 ${row.name} 的商品 ？`,
            onOk: () => {
              this.api({
                apiName: "onOffSeries",
                postdata: { goodsId, type, title },
                success: () => {
                  this.requestData();
                  this.$Notice.success({ title: `操作成功！` });
                },
              });
            },
          });
        }
      };
    },
    OffShelfModal(goodsId, type, title, name, preheatEndTime = 0, status) {
      this.formData = {
        title,
        goodsId,
        type,
        preheatEndTime: "",
        name,
      };
      if (preheatEndTime && status === 10) {
        let date = formatTime(preheatEndTime, "yyyy-MM-dd hh:mm");
        this.formData.preheatEndTime = date;
        this.formData.date = new Date(preheatEndTime);
      }
      this.detailModal = true;
    },
    OffShelfModalOk() {
      if (this.formData.type === 10) {
        let date = new Date().getTime();
        let flag = true;
        if (!this.formData.preheatEndTime) {
          this.$Notice.error({ title: `请选择日期` });
          flag = false;
        }
        if (flag) {
          let preheatEndTime = new Date(this.formData.preheatEndTime).getTime();
          if (preheatEndTime <= date) {
            this.$Notice.error({ title: `预热时间不能小于当前时间！` });
            flag = false;
          }
        }
        if (flag) {
          
          let { goodsId, type, preheatEndTime } = this.formData;
          preheatEndTime = new Date(preheatEndTime).getTime();
          this.api({
            apiName: "onOffSeries",
            postdata: { goodsId, type,preheatEndTime },
            success: () => {
              this.requestData();
              this.$Notice.success({ title: `操作成功！` });
            },
          });
        } else {
          setTimeout(() => {
            this.detailModal = true;
          }, 200);
          return;
        }
      } else {
        let { goodsId, type } = this.formData;
        this.api({
          apiName: "onOffSeries",
          postdata: { goodsId, type },
          success: () => {
            this.requestData();
            this.$Notice.success({ title: `操作成功！` });
          },
        });
      }
    },
    handleCancel(row) {
      return () => {
        let goodsId = row.goodsId;
        this.$Modal.confirm({
          content: `确认要取消审核名称为 ${row.name} 的商品 ？`,
          onOk: () => {
            this.api({
              apiName: "cancelCheckGood",
              postdata: goodsId,
              success: () => {
                this.requestData();
                this.$Notice.success({ title: `取消成功！` });
              },
            });
          },
        });
      };
    },
    changeFormDataDate(val) {
      console.log(val);
      this.formData.preheatEndTime = val;
      console.log(this.formData);
      // this.formData.date = val;
    },
    handleRecommend(row) {
      //   return () => {}
    },
  },
  created() {
    console.log(this.type);
    //     if (!this.isBrand) {
    //       this.columns.splice(2, 0, { title: '品牌方', key: 'brandName', width: 150, align: 'center' })
    //     }
    this.requestData();
    //     this.requestSeries()
  },
};
</script>

<style lang="less">
.good-list-con .search-con {
  padding: 10px 0;
  .search {
    &-col {
      display: inline-block;
      width: 150px;
      margin-right: 5px;
    }
    &-input {
      display: inline-block;
      width: 150px;
      margin-right: 5px;
    }
    &-date {
      margin-right: 5px;
    }
    &-btngroup {
      margin-right: 5px;
    }
  }
}
.OffShelfModal {
  .form-content {
    .flex-between {
      display: flex;
      justify-content: center;
      padding-top: 20px;
      .ivu-form {
        .ivu-form-item {
          margin-bottom: 0;
        }
      }
    }
  }
}
</style>
