<template>
  <a-modal
    :width="800"
    v-model="visible"
    @cancel="cancelLink"
    :footer="false"
    class="dec-table-modal"
    :class="className"
    :maskClosable="false"
  >
    <!-- 支持门店选择、名称筛选｜商品类别 -->
    <div slot="title">
      <template v-if="tab.options && tab.options.length > 0">
        <a-tabs v-model:activeKey="tab.select" @change="handleSearch">
          <a-tab-pane
            v-for="item in tab.options"
            :key="item.value"
            :tab="item.label"
          />
        </a-tabs>
      </template>
      <template v-else>
        <span style="font-size: 18px">链接子项选择</span>
      </template>
    </div>
    <div class="dec-flex-list middle" style="margin: 12px 0">
      <template v-if="down.options && down.options.length > 0">
        <span>{{ down.name }}：</span>
        <a-select
          @change="handleSearch"
          v-model:value="down.select"
          :options="down.options"
          style="width: 200px; margin-right: 10px"
        />
      </template>
      <span>筛选：</span>
      <a-input
        style="width: 200px"
        v-model="keyword"
        placeholder="通过关键字筛选"
        class="m-search"
      />
      <a-button type="primary" @click="handleSearch">搜索</a-button>
    </div>
    <a-spin :spinning="spinning">
      <a-table
        :columns="columns"
        :data-source="linkArr"
        :pagination="false"
        :rowKey="getRowkey"
      >
        <template slot="optTitle">操作</template>
        <template slot="optRender" slot-scope="id, record">
          <a-button
            type="primary"
            class="bnt-choice"
            @click="choiceLink(record)"
            >选取</a-button
          >
        </template>
      </a-table>
      <div class="dec-flex-list side" style="margin: 12px 0">
        <div></div>
        <a-pagination
          size="small"
          :total="total"
          :pageSize="pageSize"
          :current="current"
          :showSizeChanger="false"
          @change="pageChange"
          show-size-changer
          show-quick-jumper
        />
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
export default {
  inject: ["decAxios"],
  data() {
    return {
      spinning: false, //数据加载中
      visible: false, //表格可见变量
      tab: {}, //tab数据筛选
      down: {}, //下拉筛选
      argPath: "", //获取表格的接口路径
      keyword: "", //关键字
      linkArr: [], //表格的数据源
      linkType: "",
      rowKey: {}, // 表格的行key
      columns: [], //表格的栏位
      pageSize: 10,
      current: 1,
      total: 0,
    };
  },
  computed: {
    className() {
      const options = (this.tab && this.tab.options) || [];
      return options.length > 0 ? "hasTab" : "";
    },
  },
  methods: {
    show(obj) {
      //清理旧数据
      this.reset();
      //初始化显示字段
      this.initColumns(obj.column);
      //显示弹框
      this.visible = true;
      this.argPath = obj.url;
      this.linkType = obj.type;
      this.getLinkData("init");
    },
    reset() {
      this.spinning = false;
      this.tab = {};
      this.down = {};
      this.argPath = "";
      this.keyword = "";
      this.linkArr = [];
      this.rowKey = {};
      this.columns = [];
      this.current = 1;
      this.total = 0;
    },
    initColumns(val) {
      let columnArr = val.split(",");
      columnArr.forEach((item) => {
        let arr = item.split(":");
        if (arr.length > 1) {
          if (["$id", "id", "$name", "$params"].includes(arr[0])) {
            if (arr[0] == "$name") {
              //链接名称字段：'$name:shopName'
              this.rowKey.name = arr[1];
            } else if (arr[0] == "$params") {
              //需要获取的额外参数
              const rr = (arr[1] || "").split("&") || [];
              this.rowKey.params = rr;
            } else {
              //行key:'$id:id|shopId'
              const rr = arr[1].split("|");
              this.rowKey.title = rr[1] || rr[0];
              this.rowKey.dataIndex = rr[0];
            }
          } else {
            this.columns.push({
              title: arr[1],
              dataIndex: arr[0],
            });
          }
        }
      });
      this.columns.push({
        dataIndex: this.rowKey.dataIndex || "id",
        scopedSlots: { title: "optTitle", customRender: "optRender" },
        width: 80,
      });
    },
    //获取弹窗中的总数据: 根据链接模块选择具体的链接地址
    getLinkData(flag) {
      this.spinning = true;
      let params = {
        pageNo: this.current,
        pageSize: this.pageSize,
        linkType: this.linkType,
        keyword: this.keyword,
      };
      if (this.tab.select) params[this.tab.key] = this.tab.select;
      if (this.down.select) params[this.down.key] = this.down.select;
      this.argPath &&
        this.decAxios.getLinkParams(this.argPath, params).then((res) => {
          if (res.code == "200") {
            this.spinning = false;
            this.linkArr = res.result.records || res.result;
            if (res.result && res.result.total) {
              this.total = res.result.total;
            }
          }
          if (flag == "init") this.initSearch(res.search || {});
        });
    },
    initSearch(val) {
      //搜索条件处理
      const { tab, down } = val;
      if (tab) {
        this.tab = tab;
        this.tab.select = tab.options[0].value;
      }
      if (down) {
        this.down = down;
        this.down.select = down.options[0].value;
      }
    },
    getRowkey(row) {
      return row[this.rowKey.dataIndex || "id"];
    },
    handleSearch() {
      this.current = 1;
      this.getLinkData();
    },
    pageChange(val) {
      this.current = val;
      this.getLinkData();
    },
    choiceLink(row) {
      // 关闭弹窗后把数据传回去
      console.log(row, "关闭弹窗后获取的数据");
      this.visible = false;
      let argKey = this.rowKey.title || "id",
        argValue = row[this.rowKey.dataIndex || "id"],
        argName = row[this.rowKey.name || getPageName(this.columns)];

      let argParams = [`${argKey}=${argValue}`];
      const arr = this.rowKey.params || [];
      arr.forEach((key) => {
        if (key && row[key]) argParams.push(`${key}=${row[key]}`);
      });

      this.$emit("promise", {
        success: true,
        argKey: argKey,
        argValue: argValue,
        argParams: argParams.join("&"),
        argName: argName,
      });
      function getPageName(arr) {
        return (
          arr.find((item) => item.dataIndex.includes("Name")).dataIndex ||
          arr[0].dataIndex
        );
      }
    },
    cancelLink() {
      this.visible = false;
      this.$emit("promise", {
        success: false,
        argKey: "",
        argValue: "",
        argName: "",
      });
    },
  },
};
</script>
