<template>
  <div class="search">
    <Row align="middle" justify="space-between" class="operation">
      <div>
        <Button @click="findAllRecords" type="primary" icon="md-add">新增商品</Button>
      </div>
    </Row>
    <Card>
      <Row v-show="openSearch" @keydown.enter.native="handleSearch">
        <Form ref="searchForm" :model="searchForm" inline :label-width="80">
          <FormItem label="商品名称" prop="keywords">
            <Input type="text" v-model="searchForm.keywords" clearable placeholder="请输入商品名称" style="width: 220px" />
          </FormItem>
          <FormItem class="br">
            <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
            <Button @click="handleReset">重置</Button>
          </FormItem>
        </Form>
      </Row>
      <Table :loading="loading" border :columns="columns" :data="data" :size="tableSize" ref="table"></Table>
      <Row type="flex" justify="end" class="page">
        <Page :current="searchForm.pageNum" :total="total" :page-size="searchForm.pageSize"
          @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10, 20, 50]"
          size="small" show-total show-elevator show-sizer></Page>
      </Row>
    </Card>

    <Modal title="新增秒杀团商品" v-model="tranVisible" :mask-closable="false" :width="1100">
      <transfer-station v-if="tranVisible" ref="dialog" @on-submit="handleProductAdded"></transfer-station>
      <div slot="footer">
        <Button type="text" @click="tranVisible = false">关闭</Button>
      </div>
    </Modal>

    <Modal title="编辑秒杀团商品" v-model="editVisible" :mask-closable="false" :width="560">
      <Form ref="editForm" :model="editForm" :label-width="110">
        <FormItem label="商品名称">
          <Input v-model="editForm.productName" disabled />
        </FormItem>
        <FormItem label="秒杀价格">
          <InputNumber v-model="editForm.seckillPrice" :min="0.01" style="width: 100%" />
        </FormItem>
        <FormItem label="秒杀库存">
          <InputNumber v-model="editForm.totalStock" :min="0" style="width: 100%" />
        </FormItem>
        <FormItem label="限购数量">
          <InputNumber v-model="editForm.limitNum" :min="0" style="width: 100%" />
        </FormItem>
        <FormItem label="排序">
          <InputNumber v-model="editForm.orderFiled" :min="0" style="width: 100%" />
        </FormItem>
        <FormItem label="状态">
          <RadioGroup v-model="editForm.status">
            <Radio :label="1">上架</Radio>
            <Radio :label="0">下架</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="活动时间">
          <DatePicker type="datetimerange" format="yyyy-MM-dd HH:mm:ss" transfer
            :value="editDateRange" @on-change="changeEditDate" style="width: 100%" placeholder="不选表示长期有效" />
        </FormItem>
        <FormItem label="备注">
          <Input v-model="editForm.remark" type="textarea" :rows="3" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="editVisible = false">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="submitEdit">保存</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  seckillProductList,
  editSeckillProduct,
  delSeckillProduct,
  upSeckillProduct,
  downSeckillProduct,
} from "@/api/app";
import transferStation from "./transferStation.vue";

export default {
  name: "seckill-product-manage",
  components: {
    transferStation,
  },
  data() {
    return {
      category: {},
      tableSize: "default",
      tranVisible: false,
      editVisible: false,
      openSearch: true,
      loading: false,
      submitLoading: false,
      total: 0,
      data: [],
      searchForm: {
        categoryId: "",
        pageNum: 1,
        pageSize: 10,
        keywords: "",
      },
      editForm: {},
      editDateRange: [],
      columns: [
        {
          type: "index",
          width: 60,
          align: "center",
          fixed: "left",
        },
        {
          title: "图片",
          key: "productPicture",
          width: 100,
          render: (h, params) => {
            return h("img", {
              attrs: { src: params.row.productPicture },
              style: {
                width: "70px",
                height: "55px",
                objectFit: "contain",
              },
            });
          },
        },
        {
          title: "商品名称",
          key: "productName",
          minWidth: 180,
        },
        {
          title: "商家",
          key: "shopName",
          minWidth: 150,
        },
        {
          title: "原价",
          key: "originalPrice",
          width: 100,
        },
        {
          title: "秒杀价",
          key: "seckillPrice",
          width: 100,
        },
        {
          title: "库存",
          minWidth: 150,
          render: (h, params) => {
            return h("span", `${params.row.soldStock || 0}/${params.row.totalStock || 0}`);
          },
        },
        {
          title: "状态",
          width: 90,
          render: (h, params) => h("span", params.row.status == 1 ? "上架" : "下架"),
        },
        {
          title: "排序",
          key: "orderFiled",
          width: 90,
        },
        {
          title: "操作",
          key: "action",
          width: 210,
          align: "center",
          fixed: "right",
          render: (h, params) => {
            return h("div", [
              h("a", { on: { click: () => this.edit(params.row) } }, "编辑"),
              h("Divider", { props: { type: "vertical" } }),
              h("a", { on: { click: () => this.upDown(params.row) } }, params.row.status == 1 ? "下架" : "上架"),
              h("Divider", { props: { type: "vertical" } }),
              h("a", { on: { click: () => this.remove(params.row) } }, "删除"),
            ]);
          },
        },
      ],
    };
  },
  methods: {
    init(category) {
      this.category = category || {};
      this.searchForm.categoryId = this.category.id;
      this.searchForm.pageNum = 1;
      this.getDataList();
    },
    changePage(v) {
      this.searchForm.pageNum = v;
      this.getDataList();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.searchForm.pageNum = 1;
      this.getDataList();
    },
    handleSearch() {
      this.searchForm.pageNum = 1;
      this.getDataList();
    },
    handleReset() {
      this.searchForm.keywords = "";
      this.searchForm.pageNum = 1;
      this.getDataList();
    },
    getDataList() {
      this.loading = true;
      seckillProductList(this.searchForm).then((res) => {
        this.loading = false;
        if (res.success) {
          this.data = res.result.records || [];
          this.total = res.result.total || 0;
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    findAllRecords() {
      this.tranVisible = true;
      this.$nextTick(() => {
        this.$refs.dialog.init(this.category);
      });
    },
    handleProductAdded() {
      this.tranVisible = false;
      this.getDataList();
    },
    changeEditDate(v) {
      this.editDateRange = v;
      this.editForm.startTime = v && v[0] ? v[0] : null;
      this.editForm.endTime = v && v[1] ? v[1] : null;
    },
    edit(v) {
      this.editForm = {
        id: v.id,
        productId: v.productId,
        categoryId: v.categoryId,
        productName: v.productName,
        seckillPrice: Number(v.seckillPrice || 0),
        totalStock: Number(v.totalStock || 0),
        limitNum: v.limitNum == null ? 0 : Number(v.limitNum),
        orderFiled: Number(v.orderFiled || 0),
        status: v.status,
        startTime: v.startTime,
        endTime: v.endTime,
        remark: v.remark || "",
      };
      this.editDateRange = v.startTime && v.endTime ? [v.startTime, v.endTime] : [];
      this.editVisible = true;
    },
    submitEdit() {
      if (!this.editForm.seckillPrice || this.editForm.seckillPrice <= 0) {
        this.$Message.warning("秒杀价格必须大于0");
        return;
      }
      this.submitLoading = true;
      editSeckillProduct(this.editForm).then((res) => {
        this.submitLoading = false;
        if (res.success) {
          this.$Message.success("保存成功");
          this.editVisible = false;
          this.getDataList();
        }
      }).catch(() => {
        this.submitLoading = false;
      });
    },
    upDown(v) {
      const request = v.status == 1 ? downSeckillProduct : upSeckillProduct;
      request({ id: v.id }).then((res) => {
        if (res.success) {
          this.$Message.success("操作成功");
          this.getDataList();
        }
      });
    },
    remove(v) {
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除 " + v.productName + " ?",
        loading: true,
        onOk: () => {
          delSeckillProduct({ id: v.id }).then((res) => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("删除成功");
              this.getDataList();
            }
          });
        },
      });
    },
  },
};
</script>
