<script setup name="driverDialog">
import { getCurrentInstance, reactive, ref, watch } from 'vue'
import { getExpertList } from '@/http/apis/expertManage/expertStore'
import store from '@/store'
import { districtList } from '@/http/apis/commonApi'

const { proxy } = getCurrentInstance(),
  props = defineProps({
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    data: {
      type: Array,
      default: undefined
    },
    selectExpertType: {
      type: Number,
      default: 1
    }
  }),
  emits = defineEmits(['close', 'getUserData']),
  searchForm = reactive({
    expertRegionLevel: undefined,
    expertName: undefined,
    company: undefined
  }),
  tableListRef = ref(),
  total = ref(0),
  column = [
    {
      type: 'selection',
      reserveSelection: true,
      width: '55'
    },
    {
      label: '姓名',
      key: 'expertName',
      prop: 'expertName'
    },
    {
      label: '工作单位',
      key: 'company',
      prop: 'company',
      showOverflowTooltip: true,
      width: 250
    },
    {
      label: '专家级别',
      key: 'expertRegionInfo',
      slot: 'expertRegionInfo',
      width: '150'
    },
    {
      label: '手机号码',
      key: 'phoneNo',
      prop: 'phoneNo',
      width: '150'
    },
    {
      label: '专家类型',
      key: 'expertType[0].dictionaryName',
      prop: 'expertType[0].dictionaryName',
      width: '150'
    }
  ],
  tableData = ref([]),
  getTableData = async (pageParams = tableListRef.value?.pageParams) => {
    const res = await getExpertList({
      ...pageParams,
      ...searchForm,
      expertRegionInfo: searchForm.expertRegionInfo ? {
        regionCode: searchForm.expertRegionInfo.slice(-1)[0].split('##')[0],
        regionLevel: searchForm.expertRegionInfo.slice(-1)[0].split('##')[2],
        regionName: searchForm.expertRegionInfo.slice(-1)[0].split('##')[1]
      } : undefined
    })
    total.value = res.data.total
    tableData.value = res.data.records || []
    const selectCopyData = JSON.parse(JSON.stringify(selectData.value))
    if (selectCopyData?.length) {
      tableData.value && tableData.value.forEach(item => {
        const dataIds = selectCopyData.map(i => i.userId * 1)
        if (dataIds.includes(item.userId)) {
          tableListRef.value.toggleRowSelect(item, true)
        }
      })
    }
  },
  search = () => {
    getTableData()
  },
  reset = () => {
    searchForm.expertRegionInfo = undefined
    searchForm.expertName = undefined
    searchForm.company = undefined
    tableListRef.value.pageParams.pageNumber = 1
    tableListRef.value.pageParams.pageSize = 10
    getTableData()
  },
  selectData = ref([]),
  selectionChange = val => {
    // selectData.value = val
    const ids = val.map(i => i.userId)
    tableData.value.forEach(row => {
      if (ids.includes(row.userId)) {
        selectData.value.push(row)
      } else {
        selectData.value = selectData.value.filter(i => i.userId !== row.userId)
      }
    })
  },
  confirm = () => {
    const obj = {}
    const data = selectData.value.reduce((cur, next) => {
      obj[next.userId] ? '' : obj[next.userId] = true && cur.push(next)
      return cur
    }, [])
    if (props.selectExpertType === 1 && data?.length > 10) {
      proxy.$message.warning('最多选择10位人员')
    } else {
      emits('getUserData', data)
    }
  },
  regionTree = ref([])
watch(
  () => props.visible,
  async val => {
    if (val) {
      if (props.data?.length) {
        selectData.value = props.data.map(i => i)
      }
      const res = await districtList({ regionCode: 330500, regionLevel: 2 })
      regionTree.value = [res.data]
      getTableData()
      store.userStore.setRoleStore()
    }
  }
)
</script>

<template>
  <el-dialog
    :model-value="visible"
    title="选择人员"
    width="840px"
    destroy-on-close
    @close="emits('close')"
  >
    <div class="search mb-16">
      <el-form label-suffix=":" :model="searchForm" size="small">
        <el-row :gutter="16" class="mb-16">
          <el-col :span="8">
            <el-form-item label="专家级别">
              <el-cascader
                v-model="searchForm.expertRegionInfo"
                :options="regionTree"
                placeholder="请选择"
                class="w-full"
                :props="{
                  value:'unionCode',
                  label:'name'
                }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="专家姓名">
              <el-input
                v-model="searchForm.expertName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作单位">
              <el-input
                v-model="searchForm.company"
                maxlength="11"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item class="btn">
              <el-button type="primary" @click="search">查询</el-button>
              <el-button @click="reset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <table-list
      ref="tableListRef"
      :column="column"
      :data="tableData"
      :total="total"
      row-key="userId"
      @selection-change="selectionChange"
      @get-table-data="getTableData"
    >
      <template #expertRegionInfo="{scope}">
        <span>{{ scope.row?.expertRegionInfo?.regionName||'-' }}</span>
      </template>
    </table-list>
    <template #footer>
      <el-button type="primary" size="small" @click="confirm">
        确定
      </el-button>
      <el-button size="small" @click="emits('close')">
        关闭
      </el-button>
    </template>
  </el-dialog>
</template>
