<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCardNo">
        <el-input
          v-model="queryParams.idCardNo"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="人员类型" prop="whitelistType">
        <el-select v-model="queryParams.whitelistType" placeholder="请选择人员类型" clearable style="width: 180px">
          <el-option
            v-for="dict in whitelist__type"
            :key="dict.value"
            :label="dict.label"
            :value="String(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="来源类型" prop="sourceType">
        <el-select v-model="queryParams.sourceType" placeholder="请选择来源类型" clearable style="width: 180px">
          <el-option
            v-for="dict in source_type"
            :key="dict.value"
            :label="dict.label"
            :value="String(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择启用状态" clearable style="width: 180px">
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['base:whitelist:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:whitelist:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:whitelist:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['base:whitelist:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['base:whitelist:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="whitelistList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="name" min-width="120" show-overflow-tooltip />
      <el-table-column label="手机号" align="center" prop="mobile" width="140" />
      <el-table-column label="身份证号" align="center" prop="idCardNo" min-width="180" show-overflow-tooltip />
      <el-table-column label="人员类型" align="center" prop="whitelistType" width="120">
        <template #default="scope">
          <dict-tag :options="whitelist__type" :value="String(scope.row.whitelistType)"/>
        </template>
      </el-table-column>
      <el-table-column label="人脸照片" align="center" prop="faceImageUrl" width="100">
        <template #default="scope">
          <image-preview
            v-if="scope.row.faceImageUrl"
            :src="scope.row.faceImageUrl"
            :width="44"
            :height="44"
          />
          <el-tag v-else type="info">未上传</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="来源类型" align="center" prop="sourceType" width="120">
        <template #default="scope">
          <dict-tag :options="source_type" :value="String(scope.row.sourceType)"/>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" min-width="240" show-overflow-tooltip>
        <template #default="scope">
          <div class="valid-time-cell">
            <span>{{ formatValidTime(scope.row.validStartTime, scope.row.validEndTime) }}</span>
            <el-tag
              size="small"
              :type="getValidStatusTagType(scope.row.validStartTime, scope.row.validEndTime)"
            >
              {{ getValidStatusText(scope.row.validStartTime, scope.row.validEndTime) }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag v-if="String(scope.row.status) === '1'" type="success">启用</el-tag>
          <el-tag v-else type="info">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
      <el-table-column label="操作" align="center" width="240" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            v-if="String(scope.row.status) !== '1'"
            link
            type="primary"
            icon="CircleCheck"
            @click="handleStatusChange(scope.row, '1')"
            v-hasPermi="['base:whitelist:edit']"
          >启用</el-button>
          <el-button
            v-if="String(scope.row.status) === '1'"
            link
            type="warning"
            icon="CircleClose"
            @click="handleStatusChange(scope.row, '0')"
            v-hasPermi="['base:whitelist:edit']"
          >停用</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['base:whitelist:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['base:whitelist:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改白名单对话框 -->
    <el-dialog :title="title" v-model="open" width="760px" append-to-body>
      <el-form ref="whitelistRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" maxlength="100" show-word-limit placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="人员类型" prop="whitelistType">
              <el-select v-model="form.whitelistType" placeholder="请选择人员类型" style="width: 100%">
                <el-option
                  v-for="dict in whitelist__type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="String(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="手机号" prop="mobile">
              <el-input
                v-model="form.mobile"
                maxlength="11"
                placeholder="请输入手机号"
                @input="handleMobileInput"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="身份证号" prop="idCardNo">
              <el-input
                v-model="form.idCardNo"
                maxlength="18"
                placeholder="请输入身份证号"
                @input="handleIdCardInput"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="人脸照片" prop="faceImageUrl">
              <image-upload
                v-model="form.faceImageUrl"
                :limit="1"
                :file-size="2"
                @update:modelValue="handleIdentityInfoChange"
              />
              <div class="form-tip">用于机器人侧照片比对。建议上传清晰正脸照片。</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="来源类型" prop="sourceType">
              <el-tag type="info">{{ formatSourceType(form.sourceType) }}</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="有效开始时间" prop="validStartTime">
              <el-date-picker clearable
                v-model="form.validStartTime"
                type="date"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                placeholder="请选择有效开始时间"
                @change="handleValidTimeChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="有效结束时间" prop="validEndTime">
              <el-date-picker clearable
                v-model="form.validEndTime"
                type="date"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                placeholder="请选择有效结束时间"
                @change="handleValidTimeChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="启用状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                maxlength="500"
                show-word-limit
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Whitelist">
import { listWhitelist, getWhitelist, delWhitelist, addWhitelist, updateWhitelist } from "@/api/base/whitelist"

const { proxy } = getCurrentInstance()
const { source_type, whitelist__type } = useDict('source_type', 'whitelist__type')

const whitelistList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

/** 校验手机号、身份证号、人脸照片三者至少填写一种 */
function validateIdentityInfo(rule, value, callback) {
  if (form.value.mobile || form.value.idCardNo || form.value.faceImageUrl) {
    callback()
  } else {
    callback(new Error("手机号、身份证号、人脸照片至少填写一种"))
  }
}

/** 校验有效结束时间必须大于有效开始时间 */
function validateValidTime(rule, value, callback) {
  if (form.value.validStartTime && form.value.validEndTime && form.value.validEndTime <= form.value.validStartTime) {
    callback(new Error("有效结束时间必须大于有效开始时间"))
  } else {
    callback()
  }
}

/** 格式化有效期显示 */
function formatValidTime(startTime, endTime) {
  const start = startTime ? proxy.parseTime(startTime, "{y}-{m}-{d}") : "立即生效"
  const end = endTime ? proxy.parseTime(endTime, "{y}-{m}-{d}") : "长期有效"
  return start + " 至 " + end
}

/** 获取有效期状态 */
function getValidStatus(startTime, endTime) {
  const now = new Date()
  const start = startTime ? new Date(startTime) : null
  const end = endTime ? new Date(endTime) : null
  if (!start && !end) return "long_term"
  if (start && now < start) return "not_started"
  if (end && now > end) return "expired"
  return "valid"
}

/** 有效期状态文本 */
function getValidStatusText(startTime, endTime) {
  const status = getValidStatus(startTime, endTime)
  const map = {
    valid: "有效",
    not_started: "未生效",
    expired: "已过期",
    long_term: "长期有效"
  }
  return map[status] || "-"
}

/** 有效期状态标签类型 */
function getValidStatusTagType(startTime, endTime) {
  const status = getValidStatus(startTime, endTime)
  const map = {
    valid: "success",
    not_started: "warning",
    expired: "danger",
    long_term: "info"
  }
  return map[status] || "info"
}

/** 身份识别信息变化时，主动触发三选一校验 */
function handleIdentityInfoChange() {
  nextTick(() => {
    proxy.$refs["whitelistRef"]?.validateField(["mobile", "idCardNo", "faceImageUrl"])
  })
}

/** 格式化来源类型显示 */
function formatSourceType(value) {
  const target = source_type.value.find(item => String(item.value) === String(value))
  return target ? target.label : "-"
}

/** 手机号输入处理 */
function handleMobileInput(value) {
  form.value.mobile = String(value || "").replace(/\D/g, "").slice(0, 11)
  handleIdentityInfoChange()
}

/** 身份证号输入处理 */
function handleIdCardInput(value) {
  form.value.idCardNo = String(value || "")
    .toUpperCase()
    .replace(/[^0-9X]/g, "")
    .slice(0, 18)
  handleIdentityInfoChange()
}

/** 手机号格式校验 */
function validateMobile(rule, value, callback) {
  if (!value) {
    callback()
    return
  }
  const reg = /^1[3-9]\d{9}$/
  if (!reg.test(value)) {
    callback(new Error("请输入正确的手机号"))
    return
  }
  callback()
}

/** 身份证号格式校验 */
function validateIdCardNo(rule, value, callback) {
  if (!value) {
    callback()
    return
  }
  const reg = /^\d{17}[\dX]$/
  if (!reg.test(value)) {
    callback(new Error("请输入正确的18位身份证号"))
    return
  }
  callback()
}

/** 有效期变化时校验结束时间 */
function handleValidTimeChange() {
  nextTick(() => {
    proxy.$refs["whitelistRef"]?.validateField("validEndTime")
  })
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    mobile: undefined,
    idCardNo: undefined,
    whitelistType: undefined,
    sourceType: undefined,
    status: undefined
  },
  rules: {
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    whitelistType: [
      { required: true, message: "请选择人员类型", trigger: "change" }
    ],
    mobile: [
      { validator: validateIdentityInfo, trigger: "blur" },
      { validator: validateMobile, trigger: "blur" }
    ],
    idCardNo: [
      { validator: validateIdentityInfo, trigger: "blur" },
      { validator: validateIdCardNo, trigger: "blur" }
    ],
    faceImageUrl: [
      { validator: validateIdentityInfo, trigger: "change" }
    ],
    sourceType: [
      { required: true, message: "来源类型不能为空", trigger: "change" }
    ],
    validEndTime: [
      { validator: validateValidTime, trigger: "change" }
    ],
    status: [
      { required: true, message: "请选择启用状态", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询访客白名单列表 */
function getList() {
  loading.value = true
  listWhitelist(queryParams.value).then(response => {
    whitelistList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    name: null,
    mobile: null,
    idCardNo: null,
    faceImageUrl: null,
    whitelistType: null,
    sourceType: "1",
    validStartTime: null,
    validEndTime: null,
    status: "1",
    remark: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("whitelistRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加白名单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value[0]
  getWhitelist(_id).then(response => {
    const data = response.data || {}
    form.value = {
      ...data,
      idCardNo: data.idCardNo || data.id_card_no || null,
      faceImageUrl: data.faceImageUrl || data.face_image_url || null,
      validStartTime: data.validStartTime || data.valid_start_time || null,
      validEndTime: data.validEndTime || data.valid_end_time || null,
      status: data.status != null ? String(data.status) : "1",
      whitelistType: data.whitelistType != null ? String(data.whitelistType) : null,
      sourceType: data.sourceType != null ? String(data.sourceType) : "1"
    }
    open.value = true
    title.value = "修改白名单"
  })
}

/** 启用/停用白名单 */
function handleStatusChange(row, status) {
  const actionText = status === "1" ? "启用" : "停用"
  proxy.$modal.confirm('确认' + actionText + '白名单人员“' + row.name + '”吗？').then(() => {
    return updateWhitelist({
      ...row,
      status
    })
  }).then(() => {
    proxy.$modal.msgSuccess(actionText + "成功")
    getList()
  }).catch(() => {})
}

/** 导入按钮操作 */
function handleImport() {
  proxy.$modal.msgWarning("白名单导入功能待后端接口完成后接入")
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["whitelistRef"].validate(valid => {
    if (valid) {
      if (!form.value.mobile && !form.value.idCardNo && !form.value.faceImageUrl) {
        proxy.$modal.msgWarning("手机号、身份证号、人脸照片至少填写一种")
        return
      }
      if (!form.value.sourceType) {
        form.value.sourceType = "1"
      }
      if (form.value.id != null) {
        updateWhitelist(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addWhitelist(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('确认删除选中的白名单数据吗？删除后不可恢复。').then(function() {
    return delWhitelist(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('base/whitelist/export', {
    ...queryParams.value
  }, `白名单_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.app-container {
  padding: 20px;
}
:deep(.el-table .cell) {
  line-height: 22px;
}
.form-tip {
  margin-top: 6px;
  font-size: 12px;
  line-height: 1.5;
  color: #909399;
}
.valid-time-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
</style>
