<template>
  <LabelBox
    :label="formItems.attrs?.label"
    :need-star="formItems.attrs?.needStar"
    :width="formItems.attrs?.width"
  >
    <el-select
      ref="selectRef"
      v-model="defaultValue"
      size="mini"
      :placeholder="formItems.attrs?.placeholder || '请选择'"
      :clearable="formItems.clearable || true"
      :filterable="formItems.attrs?.filterable || true"
      collapse-tags
      v-bind="formItems.attrs"
      v-on="formItems.events"
      @visible-change="visibleChange"
      @clear="selectClear"
    >
      <template #empty>
        <div
          class="t-table-select__table"
          :style="{ width: `${tableWidth}px` }"
        >
          <el-table
            ref="el-table"
            v-loading="table.loading"
            :data="table.data"
            class="radioStyle"
            border
            v-bind="$attrs"
            height="400"
            @selection-change="handlesSelectionChange"
            v-on="$listeners"
          >
            <el-table-column
              v-if="formItems.attrs.multiple"
              type="selection"
              width="45"
              fixed
            />
            <el-table-column
              v-else
              type="radio"
              width="50"
              label="选择"
              fixed
              :align="align || 'center'"
            >
              <template slot-scope="scope">
                <el-radio
                  v-model="radioVal"
                  :label="scope.row[formItems.attrs.optionValue]"
                  @click.native.prevent="radioClick(scope.row)"
                />
              </template>
            </el-table-column>
            <template v-for="(item,index) in formItems.attrs.columns">
              <el-table-column
                :key="index+'i'"
                :type="item.type"
                :label="item.label"
                :prop="item.prop"
                :min-width=" item.minWidth || item.width"
                :align="item.align || 'center'"
                :fixed="item.fixed"
                :show-overflow-tooltip="item.showTooltip"
                v-bind="{...item.bind,...$attrs}"
                v-on="$listeners"
              >
                <template slot-scope="scope">
                  <!-- 作用域插槽 -->
                  <template v-if="item.slotName">
                    <slot
                      :name="item.slotName"
                      :scope="scope"
                    />
                  </template>
                  <div v-else>
                    <span>{{ scope.row[item.prop] }}</span>
                  </div>
                </template>
              </el-table-column>
            </template>
            <slot />
          </el-table>
          <div class="t-table-select__page">
            <el-pagination
              v-show="(table.data && table.data.length) "
              :current-page="table.currentPage"
              :page-sizes="[10, 20, 50]"
              :pager-count="5"
              :page-size="table.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="table.total"
              v-bind="$attrs"
              background
              @current-change="handlesCurrentChange"
              @size-change="handleSizeChange"
              v-on="$listeners"
            />
          </div>
        </div>
      </template>
    </el-select>
  </LabelBox>
</template>

<script>
import LabelBox from '../labelBox/index.vue';
export default {
  components: {
    LabelBox,
  },
  props: {
    /**
     * api this.$apis.接口名  接口
     * params {}  传参
     * optionLabel string  下拉展示label
     * optionValue string  下拉选中值
     * multiple boolean 是否多选
     */
    formItems: {
      type: Object,
      default: () => {},
    },
    value: {
      type: [String, Array],
      default: '',
    },
    tableWidth: {
      type: String,
      default: '600',
    },
    defaultSelectVal: { // 默认选中项--keywords.value值
      type: Array,
      default: () => [],
    },
    // 单选--回显不是第一页的label
    radioSelectValLabel: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      radioVal: '',
      defaultValue: this.value,
      defaultSelectValue: this.defaultSelectVal, // 默认选中
      radioDefaultSelectValLabel: this.radioSelectValLabel, // 单选回显label
      selectRow: null,
      table: {
        loading: false,
        params: {},
        data: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  watch: {},
  async mounted() {
    this.table.params = { ...this.formItems.attrs.params };
    await this.getTableData();
    // 设置默认选中项（单选）
    if (this.defaultSelectValue.length > 0) {
      this.defaultSelect(this.defaultSelectValue);
    }
  },
  methods: {
    visibleChange(visible) {
      if (visible) {
        // if (this.defaultSelectValue.length > 0) {
        //   this.defaultSelect(this.defaultSelectValue);
        // }
      } else {
        this.findLabel();
      }
    },
    handlesSelectionChange(val) { // 多选
      this.defaultValue = val.map((item) => item[this.formItems.attrs.optionValue]);
      if (val.length === 0) {
        this.defaultSelectValue = [];
      }
      console.log(val, this.defaultValue, 'vvv');
      this.$emit('outOperation', this.defaultValue, val);
      this.$emit('input', this.defaultValue);
    },
    // 默认选中（且只能默认选中第一页的数据）
    defaultSelect(defaultSelectVal) {
      console.log(defaultSelectVal, 'defaultSelectVal');
      if (this.formItems.attrs?.multiple) {
        const multipleList = [];
        defaultSelectVal.map((val) => {
          this.table.data.forEach((row) => {
            if (val === row[this.formItems.attrs.optionValue]) {
              multipleList.push(row);
            }
          });
        });
        setTimeout(() => {
          this.defaultValue = multipleList.map(
            (item) => item[this.formItems.attrs.optionValue],
          ).join(',');
          multipleList.forEach((row) => {
            const arr = this.table.data.filter(
              (item) => item[this.formItems.attrs.optionValue] === row[this.formItems.attrs.optionValue],
            );
            if (arr.length > 0) {
              this.$refs['el-table'].toggleRowSelection(arr[0], true);
            }
          });
        }, 0);
      } else {
        setTimeout(() => {
          let row;
          this.table.data.map((val, i) => {
            if (val[this.formItems.attrs.optionValue] === defaultSelectVal[0]) {
              row = val;
            }
          });
          console.log(row, 'row');
          if (row) {
            this.selectRow = row;
            this.radioVal = row[this.formItems.attrs.optionValue];
            this.defaultValue = row[this.formItems.attrs.optionValue] || '';
            this.$refs.selectRef.selectedLabel = row && row[this.formItems.attrs.optionLabel];
            this.$emit('outOperation', row[this.formItems.attrs.optionValue], row);
            this.$emit('input', row[this.formItems.attrs.optionValue]);
          } else {
            this.radioVal = this.value;
            this.$refs.selectRef.selectedLabel = this.radioDefaultSelectValLabel;
          }
        }, 0);
      }
    },
    async getTableData() {
      this.table.loading = true;
      const res = await this.formItems.attrs.api(this.table.params);
      this.table.loading = false;
      this.table.data = res.data.result.datals;
      this.table.total = res.data.result.total;
    },
    radioClick(row) {
      console.log(row, '点击');
      this.selectRow = row;
      this.defaultValue = row[this.formItems.attrs.optionValue];
      this.radioVal = row[this.formItems.attrs.optionValue];
      this.radioDefaultSelectValLabel = '';
      this.$emit('outOperation', row[this.formItems.attrs.optionValue], row);
      this.$emit('input', row[this.formItems.attrs.optionValue]);
      this.$nextTick(() => {
        this.$refs.selectRef.selectedLabel = row && row[this.formItems.attrs.optionLabel];
      });
      // 选择了数据关闭下拉框
      if (!this.formItems.attrs?.multiple) {
        this.$nextTick(() => {
          this.$refs.selectRef.blur();
        });
      }
    },
    // 赋值
    findLabel() {
      this.$nextTick(() => {
        if (this.formItems.attrs.multiple) {
          if (this.$refs.selectRef) {
            this.$refs.selectRef.selected.forEach((item) => {
              item.currentLabel = item.value;
            });
          }
        } else {
          if (this.$refs.selectRef) {
            this.radioVal = this.selectRow ? this.selectRow[this.formItems.attrs.optionValue] : '';
            console.log(this.selectRow, 'sss');
            this.$refs.selectRef.selectedLabel = !this.selectRow ? '' : this.selectRow[this.formItems.attrs.optionLabel] ? this.selectRow[this.formItems.attrs.optionLabel] : this.radioDefaultSelectValLabel;
          }
        }
      });
    },
    handlesCurrentChange(val) {
      this.table.params['queryParam.pageStart'] = val;
      this.getTableData();
      // this.findLabel();
    },
    handleSizeChange(val) {
      this.table.params['queryParam.pageLimit'] = val;
      this.getTableData();
      // this.findLabel();
      this.$refs.selectRef.focus();
    },
    selectClear() {
      if (this.formItems.attrs.multiple) {
        this.$refs['el-table'].clearSelection();
        this.defaultValue = [];
        this.defaultSelectValue = [];
        this.selectRow = null;
      } else {
        // 取消高亮
        this.$refs['el-table'].setCurrentRow(-1);
        this.radioVal = '';
        this.defaultValue = null;
        this.defaultSelectValue = [];
        this.selectRow = null;
        this.$emit('outOperation', '', '');
        this.$emit('input', '');
      }
      this.findLabel();
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep.el-select {
  width: 100%;
  height: 24px;
  line-height: 24px;
}

::v-deep.input-box {
  height: 24px;
}

::v-deep.el-select .el-input__icon {
  height: 24px;
  line-height: 25px;
}

::v-deep.el-select .el-input-group__prepend {
  box-sizing: border-box;
  padding: 0 10px;
  height: 24px;
  line-height: 24px;
  border: none;
}

::v-deep.el-select .el-input__inner {
  height: 24px;
  line-height: 24px;
}

.radioStyle {
    ::v-deep .el-radio {
      .el-radio__label {
        display: none;
      }
    }
    &:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner {
        box-shadow: none;
      }
  }
</style>

