<template>
  <a-modal
    :width="columnW"
    v-model="visible"
    @cancel="closeModal"
    class="dec-table-modal"
  >
    <div slot="title">
      <span style="font-size: 18px">
        {{ options.title || "链接子项选择" }}</span
      >
    </div>
    <div
      v-if="!options.noSearch"
      class="dec-flex-list middle"
      style="margin: 12px 0"
    >
      <template v-if="down.options && down.options.length > 0">
        <span>门店选择：</span>
        <a-select
          @change="handleSearch"
          v-model="down.select"
          :options="down.options"
          style="width: 200px; margin-right: 10px"
        />
      </template>
      <span>筛选：</span>
      <a-input
        style="width: 200px"
        v-model="search"
        placeholder="通过关键字筛选"
        class="m-search"
      />
      <a-button type="primary" @click="handleSearch">搜索</a-button>
    </div>

    <a-spin :spinning="loading">
      <!-- 数据展示 -->
      <a-table
        :row-selection="selection"
        :columns="columns"
        :data-source="dataArr"
        :pagination="false"
        :rowKey="getRowkey"
        :class="rowKey.img ? 'hasImg' : ''"
      >
        <template slot="titleRender">
          <span style="padding-left: 70px">{{ rowKey.imgName || "商品" }}</span>
        </template>
        <template slot="imgRender" slot-scope="name, record">
          <div class="dec-flex-list middle" style="max-width: 420px">
            <span class="img-wrap">
              <img :src="decAxios.decImgDomain(record[rowKey.img])" alt="img" />
            </span>
            <span class="dec-truncate2">{{ name }}</span>
          </div>
        </template>
        <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 v-if="!!selection">
          已选择{{ selection && selection.selectedRowKeys.length }}个
        </div>
        <a-pagination
          v-if="total != -1"
          size="small"
          :total="total"
          :pageSize="pageSize"
          :current="current"
          :showSizeChanger="false"
          @change="pageChange"
          show-size-changer
          show-quick-jumper
        />
      </div>
    </a-spin>
    <template slot="footer">
      <div v-if="!!selection" class="dec-flex-list side" style="margin: 0">
        <div style="color: #f44444">提示：全选只会选中当前页面数据</div>
        <a-button
          class="btn-right"
          key="submit"
          type="primary"
          @click="handleOk"
          >确定</a-button
        >
      </div>
      <div v-else></div>
    </template>
  </a-modal>
</template>
<script>
export default {
  inject: ["decAxios"],
  props: {
    multiple: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      columnW: 800,
      visible: false, //可见控制
      loading: true, //加载控制
      options: {}, //页面显示配置
      dataArr: [], //table数据
      search: "", //关键子搜索
      down: {}, //下拉筛选
      rowKey: {},
      columns: [],
      pageSize: 5,
      total: 0,
      current: 1,
      selectedRows: [], //选中的具体数据信息
      selection: null,
    };
  },
  methods: {
    show(obj) {
      const { moulder } = obj;
      let config = {
        goodDiscount: {
          title: "选择限时抢购活动",
          moulder: "getGoodDiscountTable",
          columns:
            "activityName:活动商品,activityStartTime:开始时间,activityEndTime:结束时间",
        },
        goodSpecial: {
          title: "选择专区商品",
          moulder: "getGoodSpecialTable",
          columns: "zoneName:活动名称,shopName:所属店铺",
        },
        groupBuying: {
          title: "选择拼团抢购活动",
          moulder: "getShoppingTable",
          columns:
            "grouponName:活动名称,storeId_dictText:所属店铺,startTime:开始时间,endTime:结束时间",
        },
        goodFine: {
          title: "选择优惠限购活动",
          moulder: "getGoodFineTable",
          columns:
            "activityName:活动名称,shopName:所属店铺,startTime:开始时间,endTime:结束时间",
        },
      };
      let options = config[moulder];
      this.reset();
      if (moulder == "getLinkParams") {
        this.selection = null;
        options = {
          title: "链接子项选择",
          moulder: "getLinkParams",
          columns: obj.column || options.columns,
          url: obj.url,
          type: obj.type,
        };
      } else {
        this.selection = {
          type: this.multiple ? "checkbox" : "radio",
          selectedRowKeys: [],
          onChange: this.onSelectChange,
        };
      }
      this.options = options;
      this.getData("init");
      this.visible = true;
    },
    reset() {
      this.loading = true;
      this.options = {};
      this.dataArr = [];
      this.search = "";
      this.down = {};
      this.rowKey = {};
      this.columns = [];
      this.pageSize = 5;
      this.total = 0;
      this.current = 1;
      this.selectedRows = [];
    },
    closeModal() {
      this.visible = false;
      this.$emit("promise", { success: false });
    },
    getRowkey(record, index) {
      return record._id || record.id || "id-" + index;
    },
    getData(flag) {
      const { moulder, url, type } = this.options;
      this.loading = true;
      if (moulder) {
        const params = {
          pageNo: this.current,
          pageSize: this.pageSize,
          keyword: this.search,
        };
        if (this.down.select) params[this.down.key] = this.down.select;
        let api = [];
        console.log(url, "url");
        if (moulder == "getLinkParams")
          api = [this.decAxios[moulder](url, { ...params, linkType: type })];
        else api = [this.decAxios[moulder](params)];
        console.log(moulder);
        const that = this;
        console.log(params, "获取请求参数");
        Promise.all(api)
          .then((ress) => {
            const res = ress[0];
            that.loading = false;
            if (res.code == "200") {
              let result = res.result.records || res.result;
              that.dataArr = result;
              if (res.result && res.result.total) {
                that.total = res.result.total;
              } else {
                that.total = -1;
              }
            } else {
              that.dataArr = [];
              that.total = 0;
            }
            //首次加载需要取出搜索条件+需显示的字段
            if (flag == "init") {
              that.columnW = res.columnsWidth || 800;
              that.initColumns(res.columns || this.options.columns);
              that.initSearch(res.search || {});
            }
          })
          .catch((e) => {
            that.$message.error("接口报错");
            that.loading = false;
          });
      } else {
        this.loading = false;
        this.$message.error("弹窗moulder参数没有获取到");
      }
    },
    initColumns(val) {
      //显示字段处理
      let columnArr = val.split(",");
      columnArr.forEach((item) => {
        let arr = item.split(":");
        if (arr.length > 1) {
          //$id-链接的关键子，$name-链接名称对应的字段，$params-链接需要保存的字段,$img-需展示图片的渲染字段
          if (["$id", "id", "$name", "$params", "$img"].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 if (arr[0] == "$img") {
              //图片名称复合字段：'$img:img|name'
              const rr = arr[1].split("|");
              this.rowKey.img = rr[0];
              this.rowKey.imgJoin = rr[1] || "";
            } 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],
            });
          }
        }
      });
      //链接需要额外个操作行
      if (!this.selection)
        this.columns.push({
          dataIndex: this.rowKey.dataIndex || "id",
          scopedSlots: { title: "optTitle", customRender: "optRender" },
          width: 80,
        });
      //处理图片名称复合字段显示
      if (this.rowKey.img) {
        let rr = this.columns.filter(
            (item) => item.dataIndex == this.rowKey.imgJoin
          ),
          column = rr[0] || this.columns[0];
        if (column.dataIndex) {
          this.rowKey.imgName = column.title;
          column.scopedSlots = {
            title: "titleRender",
            customRender: "imgRender",
          };
        }
      }
    },
    initSearch(val) {
      //搜索条件处理
      const { down } = val;
      if (down) {
        this.down = down;
        this.down.select = down.options[0].value;
      }
    },
    handleSearch() {
      this.current = 1;
      if (this.selection) this.selection.selectedRowKeys = [];
      this.selectedRows = [];
      this.getData();
    },
    handleOk() {
      // 处理数据
      if (this.selection.selectedRowKeys.length > 0) {
        const res = {
          success: true,
          ids: this.selection.selectedRowKeys,
          rows: this.selectedRows,
        };
        this.$emit("promise", res);
        this.visible = false;
      } else {
        this.$message.warning("没有选择数据");
      }
    },
    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
        );
      }
    },
    onSelectChange(keys, rows) {
      this.selection.selectedRowKeys = keys;
      this.selectedRows = rows;
    },
    pageChange(obj) {
      obj && (this.current = obj) && this.getData(obj);
    },
  },
};
</script>
