<style lang="less">
@import "@/styles/tree&table-common.less";
</style>

<template>
  <div class="search">
    <Card>
      <Row type="flex" justify="space-between">
        <Col v-show="expand" span="5">
          <Alert show-icon>
            当前商家：
            <span class="select-title">{{ editTitle }}</span>
            <a class="select-clear" v-if="editTitle" @click="cancelEdit">取消选择</a>
          </Alert>
          <Input v-model="searchKey" suffix="ios-search" @on-change="search" placeholder="输入搜索商家" clearable />
          <div style="position: relative">
            <div class="tree-bar" :style="{ maxHeight: maxHeight }">
              <Tree ref="tree" :data="treeData" @on-select-change="selectTree"></Tree>
            </div>
            <Spin size="large" fix v-if="treeLoading"></Spin>
          </div>
        </Col>
        <div class="expand">
          <Icon :type="expandIcon" size="16" class="icon" @click="changeExpand" />
        </div>
        <Col :span="span">
          <Row v-show="openSearch">
            <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>
        </Col>
      </Row>
    </Card>

    <Modal title="添加到秒杀团" v-model="addVisible" :mask-closable="false" :width="560">
      <Form ref="addForm" :model="addForm" :label-width="110">
        <FormItem label="商品名称">
          <Input v-model="addForm.productName" disabled />
        </FormItem>
        <FormItem label="原价">
          <Input v-model="addForm.originalPrice" disabled />
        </FormItem>
        <FormItem label="秒杀价格">
          <Input v-model="addForm.seckillPrice" placeholder="请输入秒杀价格，如 0.01" />
        </FormItem>
        <FormItem label="秒杀库存">
          <InputNumber v-model="addForm.totalStock" :min="1" style="width: 100%" />
        </FormItem>
        <FormItem label="限购数量">
          <InputNumber v-model="addForm.limitNum" :min="0" style="width: 100%" />
        </FormItem>
        <FormItem label="排序">
          <InputNumber v-model="addForm.orderFiled" :min="0" style="width: 100%" />
        </FormItem>
        <FormItem label="状态">
          <RadioGroup v-model="addForm.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="dateRange" @on-change="changeDate" style="width: 100%" placeholder="不选表示长期有效" />
        </FormItem>
        <FormItem label="备注">
          <Input v-model="addForm.remark" type="textarea" :rows="3" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="addVisible = false">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="submitAdd">保存</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { getShopData, getShareList, addSeckillProduct } from "@/api/app";

export default {
  name: "seckill-product-selector",
  data() {
    return {
      category: {},
      regionId: "",
      tableSize: "default",
      openSearch: true,
      loading: false,
      treeLoading: false,
      submitLoading: false,
      maxHeight: "500px",
      editTitle: "",
      searchKey: "",
      expand: true,
      span: 18,
      expandIcon: "ios-arrow-back",
      treeData: [],
      selectNode: {},
      data: [],
      total: 0,
      addVisible: false,
      dateRange: [],
      searchForm: {
        shopId: "",
        keywords: "",
        pageNum: 1,
        pageSize: 10,
        delFlag: 1,
      },
      addForm: {},
      columns: [
        {
          type: "index",
          width: 60,
          align: "center",
        },
        {
          title: "图片",
          key: "productPicture",
          width: 100,
          render: (h, params) => h("img", {
            attrs: { src: params.row.productPicture },
            style: {
              width: "70px",
              height: "55px",
              objectFit: "contain",
            },
          }),
        },
        {
          title: "商品名称",
          key: "productName",
          minWidth: 180,
        },
        {
          title: "原价",
          width: 100,
          render: (h, params) => h("span", this.getOriginalPrice(params.row)),
        },
        {
          title: "库存",
          key: "stockCount",
          width: 100,
        },
        {
          title: "操作",
          key: "action",
          width: 130,
          align: "center",
          fixed: "right",
          render: (h, params) => h("a", { on: { click: () => this.openAdd(params.row) } }, "添加"),
        },
      ],
    };
  },
  methods: {
    init(category) {
      this.category = category || {};
      this.regionId = this.category.regionId || JSON.parse(this.getStore("user")).departmentId;
      this.searchKey = "";
      this.treeData = [];
      this.cancelEdit();
    },
    changeExpand() {
      this.expand = !this.expand;
      this.expandIcon = this.expand ? "ios-arrow-back" : "ios-arrow-forward";
      this.span = this.expand ? 18 : 23;
    },
    search() {
      if (!this.searchKey) {
        this.treeData = [];
        this.cancelEdit();
        return;
      }
      this.getShopList();
    },
    getShopList() {
      this.treeLoading = true;
      getShopData({
        regionId: this.regionId,
        keyWord: this.searchKey,
        pageNumber: 1,
        pageSize: 1000,
      }).then((res) => {
        this.treeLoading = false;
        if (res.success) {
          const content = res.result && (res.result.content || res.result.records || res.result);
          const list = Array.isArray(content) ? content : [];
          this.treeData = list.map((item) => ({
            id: item.id,
            title: item.shopName,
            shopName: item.shopName,
            shopAddress: item.shopAddress,
            contactPhone: item.contactPhone,
            regionId: item.regionId,
          }));
        }
      }).catch(() => {
        this.treeLoading = false;
      });
    },
    selectTree(v) {
      if (v.length > 0) {
        this.selectNode = JSON.parse(JSON.stringify(v[0]));
        this.editTitle = this.selectNode.title;
        this.searchForm.shopId = this.selectNode.id;
        this.searchForm.pageNum = 1;
        this.getDataList();
      } else {
        this.cancelEdit();
      }
    },
    cancelEdit() {
      const data = this.$refs.tree.getSelectedNodes()[0];
      if (data) data.selected = false;
      this.selectNode = {};
      this.editTitle = "";
      this.searchForm.shopId = "";
      this.data = [];
      this.total = 0;
    },
    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() {
      if (!this.searchForm.shopId) {
        this.$Message.warning("请先选择商家");
        return;
      }
      this.loading = true;
      getShareList({
        shopId: this.searchForm.shopId,
        keywords: this.searchForm.keywords,
        pageNum: this.searchForm.pageNum,
        pageSize: this.searchForm.pageSize,
        delFlag: 1,
      }).then((res) => {
        this.loading = false;
        if (res.success) {
          this.data = res.result.records || [];
          this.total = res.result.total || 0;
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    getOriginalPrice(row) {
      if (!row || !row.attributeListPrice) return row && row.price ? row.price : "";
      try {
        const specs = typeof row.attributeListPrice === "string" ? JSON.parse(row.attributeListPrice) : row.attributeListPrice;
        if (Array.isArray(specs) && specs.length > 0) return specs[0].specPrice || row.price || "";
        for (const key in specs) {
          return specs[key].specPrice || row.price || "";
        }
      } catch (e) {
        return row.price || "";
      }
      return row.price || "";
    },
    changeDate(v) {
      this.dateRange = v;
      this.addForm.startTime = v && v[0] ? v[0] : null;
      this.addForm.endTime = v && v[1] ? v[1] : null;
    },
    openAdd(row) {
      const originalPrice = Number(this.getOriginalPrice(row) || 0);
      this.addForm = {
        categoryId: this.category.id,
        productId: row.id,
        productName: row.productName,
        originalPrice: originalPrice,
        seckillPrice: originalPrice ? originalPrice.toFixed(2) : "",
        totalStock: 1,
        limitNum: 0,
        orderFiled: 0,
        status: 1,
        getAreaId: this.selectNode.regionId || this.regionId,
        startTime: null,
        endTime: null,
        remark: "",
      };
      this.dateRange = [];
      this.addVisible = true;
    },
    submitAdd() {
      const seckillPrice = Number(this.addForm.seckillPrice);
      if (!seckillPrice || seckillPrice <= 0) {
        this.$Message.warning("秒杀价格必须大于0");
        return;
      }
      if (!this.addForm.totalStock || this.addForm.totalStock <= 0) {
        this.$Message.warning("秒杀库存必须大于0");
        return;
      }
      this.addForm.seckillPrice = seckillPrice;
      this.submitLoading = true;
      addSeckillProduct(this.addForm).then((res) => {
        this.submitLoading = false;
        if (res.success) {
          this.$Message.success("添加成功");
          this.addVisible = false;
          this.$emit("on-submit", true);
        }
      }).catch(() => {
        this.submitLoading = false;
      });
    },
  },
  mounted() {
    const height = document.documentElement.clientHeight;
    this.maxHeight = Number(height - 287) + "px";
  },
};
</script>
