<template>
  <browser
    :component-loading="componentLoading"
    :api-config="apiConfig"
    :table-config="tableConfig"
    :permissions="permissions"
    :dialog-config="dialogConfig"
    :actions="actions"
    :default-query-params="queryParams"
    @update:query-params="queryParams = $event"
    @update:actions="actions = $event"
    @update:dialog-config="dialogConfig = $event"
  >
    <template #queryPanel="{ queryParams: qp }">
      <el-form :model="qp" label-width="100px">
        <el-row class="query-condition">
          <el-col :span="6">
            <el-form-item label="姓名" prop="officerName">
              <el-input v-model="qp.officerName" placeholder="请输入姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="执法号" prop="lawNo">
              <el-input v-model="qp.lawNo" placeholder="请输入执法号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="qp.contactPhone" placeholder="请输入联系电话" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="系统用户ID" prop="certificateNo">
              <el-input v-model="qp.certificateNo" placeholder="请输入系统用户ID" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <el-table-column prop="officerName" label="姓名" min-width="140" show-overflow-tooltip />
    <el-table-column prop="lawNo" label="执法号" min-width="140" />
    <el-table-column prop="contactPhone" label="联系电话" min-width="140" />
    <el-table-column prop="agencyName" label="机构名称" min-width="180" />
    <el-table-column prop="certificateNo" label="系统用户ID" min-width="160" />

    <template #dialogContent="{ dialogConfig: dc }">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="officerName">
            <el-input :disabled="dc.mode === 'detail'" v-model="dc.data.officerName" placeholder="请输入姓名" maxlength="100" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="执法号" prop="lawNo">
            <el-input :disabled="dc.mode === 'detail'" v-model="dc.data.lawNo" placeholder="请输入执法号" maxlength="50" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input :disabled="dc.mode === 'detail'" v-model="dc.data.contactPhone" placeholder="请输入联系电话" maxlength="20" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="系统用户ID" prop="certificateNo">
            <el-input :disabled="dc.mode === 'detail'" v-model="dc.data.certificateNo" placeholder="请输入系统用户ID" maxlength="50" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="所属机构" prop="agency">
            <AgencySelector v-model="dc.data.agency" :disabled="dc.mode === 'detail'" placeholder="请选择机构" :lazy-load="true" />
          </el-form-item>
        </el-col>
      </el-row>
    </template>
  </browser>
</template>

<script setup>
import { reactive, toRefs, ref } from 'vue'
import Browser from '@/components/Browser.vue'
import BusinessTable from '@/components/BusinessTable.vue'
import AgencySelector from '@/components/AgencySelector.vue'
import { ElMessage } from 'element-plus'
import officers from '@/api/lawenforcement/Officer.js'
import agencies from '@/api/lawenforcement/Agency.js'

const busiTable = ref(null)

const phoneValidator = (rule, value, callback) => {
  if (!value) return callback()
  const mobile = /^(?:\+?86)?1[3-9]\d{9}$/
  const landline = /^(\d{3,4}-?)?\d{7,8}$/
  if (mobile.test(value) || landline.test(value)) return callback()
  callback(new Error('联系电话格式不正确'))
}

async function handleDialogOk(formRef) {
  const doValidate = () => new Promise((resolve) => {
    if (!formRef) return resolve(true)
    formRef.validate((valid) => resolve(valid))
  })
  const valid = await doValidate()
  if (!valid) return
  dialogConfig.value.loading = true
  let res
  try {
    const payload = { ...dialogConfig.value.data }
    payload.agencyId = payload.agency?.agencyId || payload.agencyId || null
    delete payload.agency
    if (dialogConfig.value.mode === 'add') {
      res = await officers.add(payload)
    } else if (dialogConfig.value.mode === 'modify') {
      res = await officers.modify(payload[apiConfig.value.modelId], payload)
    }
    if (res?.success) {
      dialogConfig.value.loading = false
      dialogConfig.value.show = false
      actions.value.query()
      return
    }
    throw new Error('操作失败')
  } catch (e) {
    ElMessage.error(e.message || '操作失败')
  } finally {
    dialogConfig.value.loading = false
  }
}

const state = reactive({
  componentLoading: false,
  permissions: {
    query: true,
    add: true,
    modify: true,
    detail: true,
    delete: true,
    deleteAll: true,
    importFile: false,
    exportFile: false,
    exportSelectFile: false,
    downloadTemp: false,
    canDeleteCustom: () => true,
    canModifyCustom: () => true,
    canDetailCustom: () => true,
  },
  tableConfig: {
    hasControlColumn: true,
    controlWidth: '220',
    tableLoading: false,
    multipleSelect: true,
  },
  apiConfig: {
    api: officers,
    modelId: 'officerId',
  },
  dialogConfig: {
    type: 'min',
    show: false,
    mode: 'detail',
    formLabelWidth: '120px',
    baseTitle: '执法人员',
    loading: false,
    rules: {
      officerName: [
        { required: true, message: '姓名不能为空', trigger: 'blur' },
        { min: 1, max: 100, message: '姓名长度为1-100个字符', trigger: 'blur' }
      ],
      lawNo: [
        { required: true, message: '执法号不能为空', trigger: 'blur' },
        { min: 1, max: 50, message: '执法号长度为1-50个字符', trigger: 'blur' }
      ],
      contactPhone: [
        { validator: phoneValidator, trigger: 'blur' },
        { min: 0, max: 20, message: '联系电话长度不能超过20个字符', trigger: 'blur' }
      ],
      certificateNo: [
        { min: 0, max: 50, message: '系统用户ID长度不能超过50个字符', trigger: 'blur' }
      ],
      agency: [
        { required: true, message: '所属机构不能为空', trigger: 'change' }
      ]
    },
    data: {},
    actions: { handleDialogOk }
  },
  actions: {
    add: handleAdd,
    detail: handleDetail,
    modify: handleModify,
  },
  queryParams: {}
})

const {
  componentLoading,
  permissions,
  tableConfig,
  apiConfig,
  dialogConfig,
  actions,
  queryParams,
} = toRefs(state)

async function handleAdd() {
  dialogConfig.value.mode = 'add'
  dialogConfig.value.title = '新增执法人员'
  dialogConfig.value.data = {
    officerId: null,
    officerName: '',
    lawNo: '',
    contactPhone: '',
    certificateNo: '',
    agencyId: null,
    agency: null,
  }
  dialogConfig.value.show = true
}

async function handleDetail(row) {
  dialogConfig.value.data = {}
  dialogConfig.value.title = '详情执法人员'
  dialogConfig.value.show = true
  dialogConfig.value.mode = 'detail'
  dialogConfig.value.showFooter = false
  dialogConfig.value.loading = true
  try {
    const res = await officers.findOne(row[apiConfig.value.modelId])
    if (!res?.success) throw new Error('接口返回数据异常')
    const data = res.data || {}
    if (!data.agency && data.agencyId) {
      try {
        const a = await agencies.findOne(data.agencyId)
        if (a?.success) data.agency = a.data
      } catch (_) {}
    }
    dialogConfig.value.data = data
  } catch (e) {
    ElMessage.error(e.message || '详情加载失败')
  } finally {
    dialogConfig.value.loading = false
  }
}

async function handleModify(row) {
  dialogConfig.value.data = {}
  dialogConfig.value.title = '修改执法人员'
  dialogConfig.value.show = true
  dialogConfig.value.mode = 'modify'
  dialogConfig.value.loading = true
  try {
    const res = await officers.findOne(row[apiConfig.value.modelId])
    if (!res?.success) throw new Error('接口返回数据异常')
    const data = res.data || {}
    if (!data.agency && data.agencyId) {
      try {
        const a = await agencies.findOne(data.agencyId)
        if (a?.success) data.agency = a.data
      } catch (_) {}
    }
    dialogConfig.value.data = data
  } catch (e) {
    ElMessage.error(e.message || '详情加载失败')
  } finally {
    dialogConfig.value.loading = false
  }
}
</script>

<style lang="scss" scoped>
</style>
