<script>
import { REFER } from "../popover-select/api/index";
import deepCopy from "@gby/deep-copy";

export default {
  name: "PopoverSelectV2",
  props: {
    // v-model
    value: {
      type: [Array, String],
      require: true,
    },
    // 参照类型 ，对应后端
    referName: {
      type: String,
      require: true,
    },
    // 作为 value 唯一标识的键名，绑定值
    valueKey: {
      type: [String, null, undefined],
    },
    // 默认查询参数
    queryParams: {
      type: Function,
      default: () => {},
    },
    // 需映射源数据
    source: {
      type: Object,
      default: () => ({}),
    },
    // 参照内外映射
    dataMapping: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {},
  data() {
    return {
      size: "mini",
      width: "50%",
      page: { pageNum: 1, pageSize: 10, total: 0 },
      visible: false,
      loading: false,
      scroll: false,
      model: {
        search: "",
        isPage: true,
      },
      data: [],
      selectData: [],
      lastSelectData: [],
    };
  },
  computed: {
    innerValue: {
      get() {
        return this.value;
      },
      set(value) {
        this.$emit("input", value);
      },
    },
    tableColumns: {
      get() {
        const { referName } = this.$props;
        const {
          default: d,
        } = require(`../popover-select/components/${referName}`);
        return d.filter(({ key }) => key);
      },
    },
  },
  watch: {
    innerValue: {
      handler: function (newValue) {
        if (!newValue) this.lastSelectData = [];
      },
    },
  },
  methods: {
    // open dialog
    async open() {
      this.visible = true;
      await this.useReset();
    },
    // hide dialog
    async hide() {
      this.visible = false;
    },
    // fetch list
    async fetchList(prop, page) {
      try {
        // try
        this.loading = true;
        const { pageNum, pageSize } = page;
        const { referName: type, source, queryParams } = this.$props;
        const { code, rows, total } = await REFER(
          {
            ...prop,
            ...queryParams(source),
            type: type,
          },
          {
            pageNum,
            pageSize,
          }
        );
        if (code === 200) {
          this.data = rows;
          this.page.total = total;
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    // reset
    async useReset() {
      this.data = [];
      this.model.search = null;
      await this.fetchList(this.model, this.page);
    },
    // query
    async useQuery() {
      await this.fetchList(this.model, this.page);
    },
    // select
    useSelect(prop) {
      this.selectData = prop;
    },
    // delete
    useDelete(prop) {
      this.selectData.splice(prop, 1);
      this.useConfirm(this.selectData);
    },
    // confirm
    useConfirm(prop) {
      const {
        $props: { valueKey },
      } = this;
      // string
      if (typeof valueKey === "string") {
        this.innerValue = prop.map((item) => item[valueKey]);
      }
      // null
      else {
        this.innerValue = prop;
      }
      //
      this.hide();
      this.lastSelectData = deepCopy(prop);
      this.$emit("change", prop, this.$props);
    },
    // cancel
    useCancel() {
      this.hide();
    },
  },
  created() {},
  mounted() {},
  destroyed() {},
};
</script>
<template>
  <div class="popover-select-v2 popover-select-v2--multiple">
    <el-input v-bind="$attrs" @focus="open">
      <i class="el-icon-search" slot="suffix" @click="open"> </i>
    </el-input>
    <el-dialog
      :width="width"
      :show-close="false"
      :visible.sync="visible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <template slot="title">
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <span>选 择</span>
          <span>
            <el-button
              :size="size"
              circle
              icon="el-icon-check"
              @click="useConfirm(selectData)"
            >
            </el-button>
            <el-button
              :size="size"
              circle
              type="danger"
              icon="el-icon-close"
              @click="useCancel"
            ></el-button>
          </span>
        </div>
      </template>
      <el-form
        v-loading="loading"
        :inline="true"
        :model="model"
        :size="size"
        @submit.native.prevent
      >
        <el-form-item prop="search">
          <el-input
            v-model="model.search"
            @change="useQuery"
            @keydown.enter="useQuery"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" @click="useReset"></el-button>
        </el-form-item>
        <el-table
          ref="multipleTable"
          :data="data"
          :size="size"
          height="45vh"
          @selection-change="useSelect"
        >
          <el-table-column width="55" type="selection" align="center">
          </el-table-column>
          <el-table-column
            v-for="(column, index) in tableColumns"
            :key="index"
            :prop="column.key"
            :label="column.title"
            :width="column.width || 'auto'"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <dr-computed-input
                v-if="column.type === 'ComputedInput'"
                v-model="scope.row[column.key]"
                :source="scope.row"
                :computed="column.computed"
                :placeholder="column.placeholder"
                style="width: 100%"
              ></dr-computed-input>
              <span v-else> {{ scope.row[column.key] }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="!loading"
          :total="page.total"
          :page.sync="page.pageNum"
          :limit.sync="page.pageSize"
          @pagination="useQuery"
        />
      </el-form>
    </el-dialog>
    <el-scrollbar
      v-if="lastSelectData.length"
      :viewStyle="{
        display: 'flex',
        alignItems: 'center',
        padding: '5px 0 0 5px',
      }"
      class="popover-select-v2_tags"
    >
      <el-tag
        v-for="(tag, index) in lastSelectData"
        :size="size"
        hit
        closable
        @close="useDelete(index)"
        style="margin-right: 5px"
      >
        {{ tag.name || tag[valueKey] }}
      </el-tag>
    </el-scrollbar>
  </div>
</template>
<style scoped>
.popover-select-v2 .el-input {
  width: inherit;
}
.popover-select-v2 .el-input .el-icon-search {
  cursor: pointer;
}
.popover-select-v2 .popover-select-v2_tags {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: calc(100% - 40px);
  height: 100%;
}
::v-deep .el-table--mini .el-table__cell {
  height: 50px;
}
</style>
