<template>
    <div class="para-select para-item" :class="{'is-disabled':disabled}">
        <template v-if="disabled">
            <div class="para-select-list">
                <div class="para-select-content">
                    <div class="para-select-item" v-for="(k,v) in checkedData" :key="v"
                         :title="k.labels?(k.labels[language]||k[showName]||k) : k[showName]?k[showName]:k">
                        <span class="label">{{k.labels?(k.labels[language]||k[showName]||k) : k[showName]?k[showName]:k}}</span>
                    </div>
                </div>
            </div>
        </template>
        <template v-else>
            <div class="para-select-list">
                <div class="para-select-content"
                     :style="{height: (buttonH*(checkedData.length?checkedData.length:1))+'px','overflow-y': buttonH*(checkedData.length?checkedData.length:1) > 200 ? 'auto' : 'hidden'}">
                    <spin size="small" :spinning="spinning" :indicator="indicator">
                        <div class="para-select-item" v-if="checkedData.length === 0 && !disabled">
                            <!--请选择-->
                            <span class="tips">{{official.select[language]}}</span>
                        </div>

                        <div class="para-select-item"
                             :class="{'row-disabled':disabledList.includes(k.key) || overdueList.includes(k.key)}"
                             v-else-if="checkedData.length > 0" v-for="(k,v) in checkedData"
                             :key="v"
                             :title="k.labels?(k.labels[language]||k[showName]||k) : k[showName]?k[showName]:k">
                            <!--继承/过期 显示-->
                            <icon type="close" class="del" v-if="!disabled && !disabledList.includes(k.key)"
                                  @click="delItem(v)"/>
                            <span class="label">{{k.labels?(k.labels[language]||k[showName]||k) : k[showName]?k[showName]:k}}{{extendList.includes(k.key)?'（'+extendLable[language]+'）':''}}{{pastdueList.includes(k.key)?'（'+pastdueLable[language]+'）':''}}</span>
                        </div>
                    </spin>
                </div>
            </div>
            <popover v-model="popoverDisplay" :overlayStyle="{height:'400px'}" :placement="placement" trigger="click">
                <template slot="content">
                    <div v-if="data.type ==='table' && data.config.options.length"
                         style="margin-bottom: 5px;display: flex;justify-content: space-between">
                        <a-select size="small" style="width: 40%"
                                  v-model="initSelect"
                                  :options="data.config.options" @select="searchSelect"></a-select>
                        <a-input-search v-model="searchValue" style="width: 50%" size="small" @search="searchBtn"/>
                    </div>
                    <div class="para-select-popover">
                        <!--表格并且options存在数据-->
                        <template v-if="data.type ==='table'">
                            <para-table
                                    ref="paraTable"
                                    :bordered="data.config.bordered"
                                    :data="data.config.data"
                                    :scroll="data.config.scroll"
                                    :pagination="data.config.pagination"
                                    :showTitle="data.config.showTitle"
                                    :show-refresh="data.config.showRefresh"
                                    :radio="data.config.radio"
                                    v-model="checkListKey"
                                    :columns="data.config.columns"
                                    :row-key="data.config.rowKey"
                                    :project="data.config.project"
                                    :select-row="data.config.selectRow"
                                    :search="search"
                                    :requestCallback="data.config.requestCallback"
                                    :request="data.config.request"
                                    :getCheckboxProps="getCheckboxProps"
                                    @checkdata="getcheckData"
                            >
                            </para-table>
                        </template>
                        <template v-else>
                            <para-tree2
                                    :request="data.config.request"
                                    :title="data.config.title"
                                    :custom="data.config.custom"
                                    :custom-callback="data.config.customCallback"
                                    @change="data.config.change || getItemsChange"
                                    @click="data.config.click || getItemsClick"
                                    v-model="checkedKeys"
                                    :config="data.config"
                                    :no-array="noArray"
                                    :is-object="isObject"
                                    :back-field="backField"
                                    :search="data.config.search"
                                    :placeholder="placeholder"
                            >
                                <template #header>
                                    <icon type="notification"/>
                                </template>
                            </para-tree2>
                        </template>
                    </div>
                </template>
                <Button class="para-select-button" v-show="!disabled"
                        :class="{'is-disabled': false}"
                        :style="{height: (buttonH*(checkedData.length?checkedData.length:1))+'px'}">
                    <!--关闭-->
                    <Icon type="close" v-if="popoverDisplay" :title="official.close[language]"/>
                    <!--请选择-->
                    <Icon type="plus-circle" v-else :title="official.select[language]"/>
                </Button>
            </popover>
        </template>
    </div>
</template>

<script>
  import {
    Icon, Spin, Button, Popover, Select, Input
  } from 'ant-design-vue';
  import paraTree2 from '../para-tree2/para-tree2.vue';
  import paraTable from '../para-table/para-table.vue';
  import {isArray, isEmpty} from 'lodash';
  // import {$getSettingKey} from '@chenxihub/sweet';

  const placeholdertext = {
    zh_CN: '请输入名称',
    en_GB: 'Please enter name'
  };
  export default {
    name: 'para-select',
    components: {
      paraTree2,
      Icon,
      Spin,
      Button,
      Popover,
      aSelect: Select,
      aInputSearch: Input.Search,
      paraTable
    },
    props: {
      type: {
        type: String,
        default: ''
      },
      placement: {
        type: String,
        default: 'bottom'
      },
      disabled: {
        type: Boolean,
        default: false
      },
      value: {
        type: [Array, Object, String]
      },
      showName: {
        type: String,
        default: 'key'
      },
      // table 和 tree 组件数据
      data: {
        type: Object,
        default: () => ({
          type: '',
          config: {}
        })
      },
      noArray: {
        type: Boolean,
        default: false
      },
      isObject: {
        type: Boolean,
        default: false
      },
      backField: {
        type: Array,
        default: () => []
      },
      // 选择disabled
      disabledList: {
        type: Array,
        default: () => []
      },
      // 过期的row
      overdueList: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        buttonH: 30,
        spinning: false,
        indicator: this.$createElement('Icon', {
          attrs: {
            type: 'loading',
            spin: true
          },
          style: {
            fontSize: '16px'
          }
        }),
        treeVal: ['1'],
        popoverDisplay: false,
        checkedData: [],
        checkListKey: [],
        // table 默认配置
        tableDefaultConfig: {
          type: 'table',
          title: '表格',
          bordered: true,
          data: null,
          scroll: {y: '300px'},
          pagination: false,
          showTitle: false,
          showRefresh: false,
          radio: false,
          columns: [],
          rowKey: this.rowKey,
          project: 'cic-console',
          selectRow: true,
          request: {},
          options: [],
          search: {}
        },
        // tree 默认配置
        treeDefaultConfig: {
          title: 'title',
          multiple: true,
          radio: true,
          search: false
        },
        /* tree v-model */
        checkedKeys: null,
        official: {
          select: {
            zh_CN: '请选择',
            en_GB: 'Please Select'
          },
          close: {
            zh_CN: '关闭',
            en_GB: 'Close'
          }
        },
        searchLabel: '',
        searchValue: '',
        search: '',
        initSelect: '',
        // 继承的属性key
        extendList: [],
        // 过期的key
        pastdueList: [],
        extendLable: {
          zh_CN: '动态',
          en_GB: 'Dynamic'
        },
        pastdueLable: {
          zh_CN: '过期',
          en_GB: 'Overdue'
        }
      };
    },
    watch: {
      checkedKeys(n, v) {
        // console.log(n,v)
        if (this.checkedKeys) {
          // console.log('v-model:', this.checkedKeys);
          if (this.data.config.radio) {
            if (typeof this.checkedKeys === 'object') {
              if (!Object.keys(this.checkedKeys).length) {
                this.checkedData = [];
              } else {
                this.checkedData = [this.checkedKeys];
              }
              this.vModelData(this.checkedData, 'object');
            }
            if (isArray(this.checkedKeys)) {
              if (this.checkedKeys.length > 0) {
                this.checkedData = [...this.checkedKeys];
              } else {
                this.checkedData = [];
              }
              this.vModelData(this.checkedData, 'array');
            }
          } else {
            this.checkedData = this.checkedKeys;
            this.vModelData(this.checkedData, 'multi');
          }
        }
      },
      'data.config.request': {
        immediate: true,
        deep: true,
        handler(value) {
          return value;
        }
      }
    },
    created() {
      this.init();
      const {type} = this.data;
      if (type === 'table') {
        this.data.config = Object.assign({}, ...this.tableDefaultConfig, ...this.data.config);
        if (this.data.config.options && this.data.config.options.length) {
          this.initSelect = this.data.config.options[0].value;
          this.search = this.data.config.search;
          // console.log('this.data.config',this.data.config.search)
        }
        if (this.data.config.radio) {
          if (!this.value || !Object.keys(this.value).length) return this.checkedData = [];
          // 单选
          if (this.noArray) {
            this.checkedData = [this.value];
          } else {
            this.checkedData = this.value;
          }
          this.getCheckDataKey(this.checkedData);
        } else {
          this.checkedData = this.value || [];
          // 获取或者设置table的选择key
          this.getCheckDataKey(this.checkedData);
        }
      } else if (type === 'tree') {
        // 树选择
        this.data.config = Object.assign({}, ...this.treeDefaultConfig, ...this.data.config);
        if (this.data.config.radio) {
          /* 单选 */
          if (isEmpty(this.value)) {
            this.checkedKeys = [];
          } else {
            this.checkedKeys = this.value;
          }
        } else {
          /* 多选 */
          this.checkedKeys = this.value;
        }
      } else {
        console.warn('type类型报错');
        return false;
      }
    },
    methods: {
      vModelData(data, type) {
        // console.log('data=======>', data, type);
        this.$emit('selectChange', data);
        if (this.data.config.radio) {
          if (this.noArray) {
            if (this.isObject) {
              if (this.checkedData.length) {
                typeof this.checkedData[0] === 'object' ? this.$emit('input', this.checkedData[0]) : this.$emit('input', Object.assign({}, ...this.checkedData[0]));
              } else {
                this.$emit('input', {});
              }
            }
          } else {
            this.$emit('input', this.checkedData);
          }
        } else {
          this.$emit('input', this.checkedData);
        }
      },
      init() {
        // 获取全局type
        if (this.type) {
          if (this.type === 'app') {
            this.extendList = this.disabledList;
            this.pastdueList = this.overdueList;
          }
          this.data.type = this.$paraSelectType[this.type].type;
          this.data.config = Object.assign({}, ...this.$paraSelectType[this.type].config);
        } else {
          console.warn('请传递type类型');
        }
      },
      delItem(v) {
        this.checkedData.splice(v, 1);
        this.checkListKey.splice(v, 1);
        this.checkedKeys = this.checkedData; // 树的双向绑定数据
        // this.getCheckDataKey(this.checkedData);
        if (this.data.config.radio) {
          this.$emit('input', null);
        }
        this.$forceUpdate();
      },
      // table选项改变
      getcheckData(checkeddata) {
        this.$emit('selectChange', checkeddata);
        if (!this.isObject) {
          // 返回指定的字段信息
          if (this.backField.length) {
            this.cancelRepeat(checkeddata);
            const temparr = [];
            for (const i of this.checkedData) {
              temparr.push(i[this.backField[0]] ? i[this.backField[0]] : i);
            }
            this.checkedData = temparr;
          } else {
            this.checkedData = this.checkListKey;
          }
        } else {
          this.cancelRepeat(checkeddata);
          const temparr = [];
          for (let i = 0; i < this.checkedData.length; i++) {
            temparr[i] = {};
            for (let j = 0; j < this.backField.length; j++) {
              temparr[i][this.backField[j]] = this.checkedData[i][this.backField[j]];
            }
          }
          this.checkedData = temparr;
        }
        if (this.data.config.radio) {
          if (!this.noArray) {
            this.$emit('input', this.checkedData);
          } else {
            this.$emit('input', this.checkedData[0]);
          }
        } else {
          this.$emit('input', this.checkedData);
        }
      },
      rowKey(record) {
        return record.key || record.id;
      },
      dataCallback(data, callback) {
        callback(data);
      },
      getCheckDataKey(data) {
        const arr = [];
        data.forEach((item) => {
          if (!this.isObject) {
            arr.push(item);
          } else {
            arr.push(item.key || item.id);
          }
        });
        this.checkListKey = arr;
      },
      // table 选项存储去重
      cancelRepeat(checkeddata) {
        const arr = [...this.checkedData, ...checkeddata];
        const result = [];
        const obj = {};
        for (const i of arr) {
          if (!obj[i.key || i.id]) {
            result.push(i);
            obj[i.key || i.id] = 1;
          }
        }
        this.checkedData = result;
        if (this.isObject) {
          this.checkedData = this.checkedData.filter((item) => this.checkListKey.includes(item.key || item.id));
        } else {
          this.checkedData = this.checkedData.filter((item) => this.checkListKey.includes(item.key || item.id || item));
        }
      },
      /* tree methods */
      getItemsChange({info}) {
        this.$emit('change', info);
      },
      getItemsClick({info}) {
        this.$emit('click', info);
      },
      // 筛选切换
      searchSelect(value) {
        this.searchValue = '';
      },
      searchBtn() {
        if ((!this.initSelect) || (!this.searchValue)) {
          this.search = this.data.config.search;
        } else {
          if (this.data.config.search.fiql) {
            this.search = {fiql: `(${this.data.config.search.fiql};${this.initSelect}==*${this.searchValue}*)`};
          } else {
            this.search = {fiql: `(${this.initSelect}==*${this.searchValue}*)`};
          }
        }
      },
      // 禁用对用key
      getCheckboxProps(record) {
        return {
          props: {
            disabled: this.disabledList.includes(record.key)
          }
        };
      }
    },
    computed: {
      placeholder() {
        return placeholdertext[this.language || 'zh_CN'];
      },
      language() {
        return JSON.parse(window.localStorage[window.$project]).setting.language || 'zh_CN';
      }
    }
  };
</script>

