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

export default {
  name: "PopoverTreeSelect",
  props: {
    // v-model
    value: {
      type: [Array, String],
      require: true,
    },
    // 参照类型 ，对应后端
    referName: {
      type: String,
      require: true,
    },
    // 作为 value 唯一标识的键名，绑定值
    valueKey: {
      type: String,
      dafault: () => {
        return "code";
      },
    },
    // 默认查询参数
    queryParams: {
      type: Function,
      default: () => {},
    },
    // 需映射源数据
    source: {
      type: Object,
      default: () => ({}),
    },
    // 参照内外映射
    dataMapping: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {},
  data() {
    return {
      size: "mini",
      width: "50%",
      visible: false,
      loading: false,
      model: {
        search: "",
        isPage: false,
      },
      data: [],
      selectData: [],
      lastSelectData: [],
      defaultProps: {
        label: "name",
        children: "children",
      },
    };
  },
  computed: {
    innerValue: {
      get() {
        return this.value;
      },
      set(value) {
        this.$emit("input", value);
      },
    },
  },
  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) {
      try {
        this.loading = true;
        const { referName: type, source, queryParams } = this.$props;
        const { code, rows } = await REFER({
          ...prop,
          ...queryParams(source),
          type: type,
        });
        if (code === 200) {
          this.data = rows;
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    // reset list
    async useReset() {
      this.data = [];
      this.model.search = null;
      await this.fetchList(this.model);
    },
    // query list
    async useQuery() {
      await this.fetchList(this.model);
    },
    // auto
    async useAutocomplete(prop, cb) {
      if (prop) {
        this.model.search = prop;
        await this.fetchList(this.model);
        await cb(this.data);
      } else {
        cb([]);
      }
    },
    // 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);
    },
  },
  created() {},
  mounted() {},
  destroyed() {},
};
</script>
<template>
  <div class="popover-tree-select popover-tree-select--multiple">
    <el-input v-bind="$attrs" @focus="open">
      <i class="el-icon-search" slot="suffix" @click="open"> </i>
      <template slot-scope="{ item }">
        <p
          style="
            text-overflow: ellipsis;
            overflow: hidden;
            line-height: 15px;
            margin: 5px 0;
          "
        >
          {{ item.name }}
        </p>
        <p
          style="
            font-size: 12px;
            color: #b4b4b4;
            line-height: 15px;
            margin: 5px 0;
          "
        >
          {{ item.code }}
        </p>
      </template>
    </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
    >
      <div slot="footer">
        <el-button
          type="primary"
          :size="$attrs.size"
          :loading="loading"
          @click="useConfirm(selectData)"
          >确 认</el-button
        >
        <el-button :size="$attrs.size" :loading="loading" @click="hide"
          >取 消</el-button
        >
        
      </div>
      <el-form
        v-loading="loading"
        :size="size"
        :inline="true"
        :model="model"
        @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-tree
          v-loading="loading"
          :data="data"
          :props="defaultProps"
          accordion
          show-checkbox
          check-strictly
          highlight-current
          ref="tree"
          node-key="id"
          @check="useSelect($refs.tree.getCheckedNodes())"
        >
        </el-tree>
      </el-form>
    </el-dialog>
    <el-scrollbar
      v-if="lastSelectData.length"
      :viewStyle="{
        display: 'flex',
        alignItems: 'center',
        padding: '5px 0 0 5px',
      }"
      class="popover-tree-select_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-tree-select .el-input {
  width: inherit;
}
.popover-tree-select .el-input .el-icon-search {
  cursor: pointer;
}
.popover-tree-select .popover-tree-select_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>
