<template>
  <a-modal
    :width="columnW"
    v-model="visible"
    @cancel="closeModal"
    class="dec-table-modal"
    :class="className"
  >
    <!-- 中台可选多个业态下的商品 -->
    <div slot="title">
      <template v-if="appCode == 'TC00'">
        <a-tabs v-model:activeKey="tabActive" @change="handleSearch">
          <a-tab-pane
            v-for="item in tab"
            :key="item.productType"
            :tab="item.text"
          />
        </a-tabs>
      </template>
      <template v-else>
        <span style="font-size: 18px">选择商品</span>
      </template>
    </div>
    <div class="dec-flex-list middle" style="margin: 12px 0">
      <span>筛选：</span>
      <a-input
        style="width: 200px"
        v-model="search"
        placeholder="商品名称/店铺名称"
        class="m-search"
      />
      <a-input
        style="width: 230px"
        v-model="productCode"
        @blur="importBlur"
        placeholder="支持多个编码查询,用逗号隔开"
        class="m-search"
      />
      <a-button type="primary" @click="handleSearch">搜索</a-button>
    </div>
    <a-spin :spinning="loading">
      <!-- 数据展示 -->
      <a-table
        :pagination="ipagination"
        @change="handleTableChange"
        :row-selection="selection"
        :columns="columns"
        :data-source="dataArr"
        :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 size="small" :total="total" :pageSize="pageSize" :current="current" :showSizeChanger="true" @change="pageChange" show-size-changer show-quick-jumper >
          <template slot="buildOptionText" slot-scope="props">
              <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
              <span v-if="props.value === '50'">全部</span>
            </template>
        </a-pagination>
      </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>
//$id:id,$name:productName,productName:商品名称,shopName:所属店铺,salePrice:价格
//$id:id,$name:cateName,$params:pid,cateName:分类名称
export default {
  inject: ["decAxios"],
  props: {
    multiple: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["5", "10", "30", "50", "100", "200"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      appCode: "", //业态标示
      columnW: 1200,
      visible: false, //可见控制
      loading: true, //加载控制
      options: {}, //页面显示配置
      dataArr: [], //table数据
      search: "", //关键子搜索
      productCode: "", //商品编码搜索
      tabActive: "1",
      productTypeObj: {
        TC00: "1", //中台百货
        TC21: "1", //百货商家
        TC11: "", //一件代发
        TC21: "2", //全球购？
        TC30: "2", //全球购
        TC10: "3", //超市
        TC22: "6", //o2o
        TC11: "4", //超市一件代发
        TC23: "5", //全球购商家
      },
      tab: [
        {
          code: "TC00",
          productType: "1",
          text: "百货商品",
        },
        {
          code: "TC21",
          productType: "2",
          text: "全球购商品",
        },
        {
          code: "TC10",
          productType: "3",
          text: "超市商品",
        },
        {
          code: "TC22",
          productType: "6",
          text: "O2O商品",
        },
      ], //tab数据筛选
      rowKey: {},
      columns: [],
      // selectedRows: [], //选中的具体数据信息
      selection: null,
    };
  },
  computed: {
    className() {
      const appCode = "";
      return appCode == "TC00" ? "hasTab" : "";
    },
  },
  methods: {
    handleTableChange(pagination, filters, sorter) {
      this.selectedRowKeys = [];
      this.selectionRows = [];
      this.ipagination = pagination;
      // this.getData('init')
      this.current = this.ipagination.current;
      this.getData("init");
    },
    importBlur() {
      let importValue = this.productCode;
      if (importValue) {
        importValue = importValue.replace(/\r\n/g, ",");
        importValue = importValue.replace(/\n/g, ",");
        importValue = importValue.replace(/\s+/g, " ");
        importValue = importValue.replace(/ /g, ",");
        this.productCode = importValue;
      }
    },
    show(obj) {
      const { moulder } = obj;
      let options = {
        title: "选择商品",
        moulder: "getGoodListTable",
        columns:
          "$img:productImg|productName,productCode:商品编号,productName:商品名称,shopName:所属店铺,salePrice:价格",
        // columns:"$img:productImg|productName,productName:商品,productPrice:价格",
      };
      this.reset();
      if (moulder == "getLinkParams") {
        this.selection = null;
        options = {
          title: "链接子项选择",
          moulder: "getLinkParams",
          columns: obj.column || options.columns,
        };
      } else {
        this.selection = {
          type: this.multiple ? "checkbox" : "radio",
          selectedRowKeys: [],
          selectedRows: [],
          onChange: this.onSelectChange,
          onSelect: this.onSelect,
        };
      }
      this.options = options;
      this.getData("init");
      this.visible = true;
    },
    reset() {
      // this.appCode = this.$store.getters.appCode
      this.loading = true;
      this.options = {};
      this.dataArr = [];
      this.search = "";
      this.productCode = "";
      (this.tabActive = this.appCode == "TC00" ? "1" : ""), (this.rowKey = {});
      this.columns = [];
      this.ipagination.pageSize = 5;
      this.ipagination.current = 1;
      if (this.selection) this.selection.selectedRows = [];
    },
    closeModal() {
      this.visible = false;
      this.$emit("promise", { success: false });
    },
    getRowkey(record, index) {
      return record._id || record.id || "id-" + index;
    },
    getData(flag) {
      this.loading = true;
      const { moulder } = this.options;
      const params = {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        keyword: this.search,
        productCode: this.productCode,
        moulder,
      };
      params.productType = this.tabActive || this.productTypeObj[this.appCode];
      this.decAxios
        .getGoodListTable(params)
        .then((res) => {
          this.loading = false;
          if (res.code == "200") {
            let result = res.result;
            this.dataArr = result.records;
            this.ipagination.total = result.total;
          } else {
            this.dataArr = [];
            this.ipagination.total = 0;
          }
          //首次加载需要取出搜索条件+需显示的字段
          if (flag == "init") {
            this.columnW = res.columnsWidth || 1200;
            this.initColumns(res.columns || this.options.columns);
          }
        })
        .catch((e) => {
          this.$message.error("接口报错");
          this.loading = false;
        });
    },
    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],
              width: 200,
            });
          }
        }
      });
      //链接需要额外个操作行
      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",
          };
        }
      }
    },
    handleSearch() {
      this.current = 1;
      if (this.selection) {
        this.selection.selectedRowKeys = [];
        this.selection.selectedRows = [];
      }
      this.getData();
    },
    handleOk() {
      console.log(this.selection, "数据");
      //关闭弹窗后把商品数据传回去
      if (this.selection && this.selection.selectedRowKeys.length > 0) {
        const res = {
          success: true,
          ids: this.selection.selectedRowKeys,
          rows: this.selection.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,
        tagImg: row.productImg,
        salePrice: row.salePrice,
        argParams: argParams.join("&"),
        argName: argName,
      });
      function getPageName(arr) {
        return (
          arr.find((item) => item.dataIndex.includes("Name")).dataIndex ||
          arr[0].dataIndex
        );
      }
    },
    onSelect(record, selected, selectedRows) {
      console.log(record, selected, selectedRows);
    },
    onSelectChange(keys, rows) {
      if (this.selection) {
        this.selection.selectedRowKeys = keys;
        rows.forEach((item) => {
          if (!this.selection.selectedRowKeys.includes(item.id))
            this.selection.selectedRows.push(item);
        });
        let selectedRows = JSON.parse(
          JSON.stringify(this.selection.selectedRows)
        );
        let rowIds = selectedRows.map((e) => e._id);
        this.selection.selectedRows = this.selection.selectedRowKeys.map(
          (key) => {
            let index = rowIds.indexOf(key);
            return selectedRows[index];
          }
        );
        console.log(
          this.selection.selectedRowKeys,
          this.selection.selectedRows,
          "数据"
        );
      }
    },
    pageChange(obj) {
      obj && (this.current = obj) && this.getData(obj);
    },
  },
};
</script>
