<script setup lang="ts" name="SelTable">
import _ from 'lodash'
import { reactive, ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['check', 'input'])
const props = defineProps({
  poverWidth: {
    type: Number,
    default: 380
  },
  searchInput: {
    type: Array,
    default: () => []
  },
  disabled: {
    type: Boolean,
    default: false
  },
  keyVal: {
    type: String,
    default: 'city'
  },
  isError: {
    type: Boolean,
    default: false
  },
  ASSearchMode: {
    type: String,
    default: ''
  },
  ASSearchFiled: {
    type: String,
    default: ''
  },
  ASSearchObj: {
    type: Object
  }
})

const searchVal = ref(null)
const innerTags: any = ref([])
const tagInputRef: any = ref(null)

watch(
  () => props.searchInput,
  (current) => {
    innerTags.value = current
  },
  {
    deep: true,
    immediate: true
  }
)
// 响应数据
const state: any = reactive({
  poverShow: false,
  currentPage: 1,
  pageSize: 10,
  total: 0,
  activeRowIndex: '',
  tableData: [],
  loading: false
})

// 点击行
const handleRowClick = (row: any) => {
  state.poverShow = false
  if (!innerTags.value.includes(row[props.keyVal])) {
    innerTags.value.push(row[props.keyVal])
    state.activeRowIndex = row.id
    emit('input', innerTags.value)
    emit('check', innerTags.value)
  } else {
    ElMessage({
      message: 'Cannot add duplicate cities.',
      type: 'success'
    })
  }
  searchVal.value = null
}
const handleSearch = _.debounce((val?) => {
  state.loading = true
  searchVal.value = val?.target?.value
  let filterList: any = []
  setTimeout(() => {
    $api
      .getMoreFiltersTableData({
        term: searchVal.value ? searchVal.value : '',
        cp: state.currentPage,
        ps: state.pageSize,
        rc: '-1',
        search_field: props.ASSearchFiled,
        search_mode: props.ASSearchMode,
        ...props.ASSearchObj
      })
      .then((res: any) => {
        if (res.code == 200) {
          filterList = res.data.searchData
          state.loading = false
          filterList = res.data.searchData.filter((p: any) => {
            return (
              p.country.toLowerCase().indexOf(searchVal.value.toLowerCase()) > -1 ||
              p.city.toLowerCase().indexOf(searchVal.value.toLowerCase()) > -1 ||
              p.uncode.toLowerCase().indexOf(searchVal.value.toLowerCase()) > -1
            )
          })
          state.tableData = filterList
          state.total = Number(res.data.rc)
          state.loading = false
        }
      })
  }, 800)
}, 500)
// 分页 请求接口
const handleCurrentChange = () => {
  state.loading = true
  let filterList: any = []
  setTimeout(() => {
    $api
      .getMoreFiltersTableData({
        term: searchVal.value ? searchVal.value : '',
        cp: state.currentPage,
        ps: state.pageSize,
        rc: state.total,
        search_field: props.ASSearchFiled,
        search_mode: props.ASSearchMode,
        ...props.ASSearchObj
      })
      .then((res: any) => {
        if (res.code == 200) {
          filterList = res.data.searchData
          state.loading = false
          filterList = res.data.searchData.filter((p: any) => {
            return (
              p.country.toLowerCase().indexOf(searchVal.value.toLowerCase()) > -1 ||
              p.city.toLowerCase().indexOf(searchVal.value.toLowerCase()) > -1 ||
              p.uncode.toLowerCase().indexOf(searchVal.value.toLowerCase()) > -1
            )
          })
          state.tableData = filterList
          state.total = Number(res.data.rc)
          state.loading = false
        }
      })
  }, 800)
}
// 删除
const remove = (idx: number) => {
  innerTags.value.splice(idx, 1)
  emit('input', innerTags.value)
  emit('check', innerTags.value)
}

const onInput = () => {
  tagInputRef.value.focus()
}
</script>
<template>
  <div>
    <el-popover
      v-model:visible="state.poverShow"
      placement="bottom-start"
      :teleported="false"
      :width="props.poverWidth"
      trigger="click"
    >
      <template #reference>
        <div
          class="el-input el-input--suffix el-tooltip__trigger"
          @click="disabled ? null : onInput"
          :class="{ is_error: props.isError }"
        >
          <div class="el-input__wrapper" :class="{ 'is-disabled': disabled }">
            <el-space :class="[innerTags.length ? 'custom-el-spaceno' : 'custom-el-space']">
              <template v-for="(item, idx) in innerTags" :key="item">
                <template v-if="idx <= 2">
                  <el-tag type="info" closable :disable-transitions="false" @close="remove(idx)">
                    {{ item }}
                  </el-tag>
                </template>
              </template>
              <template v-if="innerTags.length && innerTags.length > 3">
                <el-popover placement="bottom" trigger="hover">
                  <template #reference>
                    <el-tag type="info" size="small" round :disable-transitions="false">
                      +{{ innerTags.length - 3 }}
                    </el-tag>
                  </template>
                  <template #default>
                    <div style="padding: 5px 5px 0">
                      <template v-for="(item, idx) in innerTags" :key="item">
                        <template v-if="idx >= 3">
                          <el-tag
                            type="info"
                            style="
                              width: 100% !important;
                              justify-content: space-between;
                              margin-bottom: 5px;
                            "
                            closable
                            :disable-transitions="false"
                            @close="remove(idx)"
                          >
                            {{ item }}
                          </el-tag>
                        </template>
                      </template>
                    </div>
                  </template>
                </el-popover>
              </template>
              <input
                :disabled="props.disabled"
                :value="searchVal"
                ref="tagInputRef"
                :placeholder="innerTags.length ? '' : 'Please input country/city/uncode'"
                class="el-input__inner"
                type="text"
                @input="handleSearch"
                @click="handleSearch"
              />
            </el-space>
            <div class="el-input__suffix">
              <div class="el-input__suffix-inner" v-if="!disabled">
                <el-icon :class="state.poverShow ? 'reverse' : ''">
                  <CaretBottom />
                </el-icon>
              </div>
            </div>
          </div>
        </div>
      </template>
      <el-table
        :data="state.tableData"
        border
        stripe
        v-loading="state.loading"
        @row-click="handleRowClick"
        header-row-class-name="cus-header"
      >
        <el-table-column property="country" label="Country" />
        <el-table-column property="city" label="City" />
        <el-table-column property="uncode" label="Uncode" />
      </el-table>
      <div class="pagination">
        <span>Total {{ state.total }}</span>
        <el-pagination
          v-model:currentPage="state.currentPage"
          v-model:page-size="state.pageSize"
          size="small"
          layout="prev, pager, next"
          :pager-count="5"
          :total="state.total"
          @current-change="handleCurrentChange"
          @size-change="handleCurrentChange"
        />
      </div>
    </el-popover>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-input) {
  input {
    cursor: pointer;
  }

  .el-input__suffix-inner {
    i {
      transition: all 0.3s;
    }

    .reverse {
      transform: rotate(-180deg);
    }
  }

  .el-input__wrapper {
    justify-content: space-between;
  }

  .el-input__wrapper.is-focus {
    box-shadow: 0 0 0 1px #ffbc79 inset !important;
  }
}

:deep(.cus-header) th {
  background-color: var(--color-table-header-bg) !important;
}

:deep(.el-table__row) {
  td {
    cursor: pointer;
  }
}

:deep(.el-table__row:not(.current-row):hover) {
  td {
    background-color: #fff1e6 !important;
  }
}

:deep(.current-row) {
  td {
    background-color: #ffe3cd !important;
  }
}

.pagination {
  display: flex;
  align-items: center;
  height: 40px;
  justify-content: space-between;
  padding: 0 12px 0 8px;

  > span {
    font-size: 13px;
  }
}

:deep(.el-popper) {
  border-radius: 12px !important;
}

:deep(.el-pagination) {
  .is-active {
    color: #b57b32 !important;
  }
}

:deep(.el-table--fit) {
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

:deep(.el-scrollbar__wrap--hidden-default) {
  border-radius: 0;
}

.is-disabled {
  background-color: #f5f7fa;
  color: #a8abb2;
  cursor: not-allowed;
  box-shadow: none !important;
}

:deep(.el-tag) {
  border-color: transparent;
}

:deep(.custom-el-space) {
  flex-grow: 1;
}

:deep(.custom-el-spaceno .el-space__item) {
  width: initial;
}

:deep(.custom-el-space .el-space__item) {
  width: 100%;
}

.is_error {
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 0.5px var(--color-danger) !important;
  }
}
</style>
