<template>
  <!-- 后台用户 -->
  <!-- template 内部必须有一个根节点 div，否则<Transition>将会失效，所以这个<a-modal></a-modal> 组件必须放在 根节点 div 里面 -->
  <div>
    <div class="h-16 w-full bg-white rounded shadow-md py-5 px-10 flex items-center">
      <div class="mr-5">名称</div>
      <a-input class="w-40 mr-5" v-model:value="searchUser" autocomplete="off" placeholder="请输入名称搜索" />
      <div class="mr-5 ml-5">是否启用</div>
      <a-space>
        <a-select ref="select" v-model:value="isEnableValue" style="width: 120px" @focus="focus" @change="handleChange">
          <a-select-option v-for="(item, index) in enumsIsEnable" :key="index" :value="item.value">{{ item.label }}</a-select-option>
        </a-select>
      </a-space>

      <div class="mr-5 ml-5">性别</div>
      <a-space>
        <a-select ref="select" v-model:value="sexValue" style="width: 120px" @focus="focus" @change="sexChange">
          <a-select-option v-for="(item, index) in enumsSex" :key="index" :value="item.value">{{ item.label }}</a-select-option>
        </a-select>
      </a-space>
      <div class="mr-5 ml-5">手机号</div>
      <a-input class="w-40 mr-5" v-model:value="searchTelePhone" autocomplete="off" placeholder="请输入手机号搜索" />
      <a-button @click="search" class="ml-5 flex items-center" type="primary"> <SearchOutlined style="font-size: 16px" />搜索 </a-button>
      <a-button @click="resetSearch" class="ml-5 flex items-center"><SyncOutlined style="font-size: 16px" />重置</a-button>
    </div>

    <div class="w-full h-full bg-white mt-5 rounded">
      <div class="w-full h-16 py-5 px-10 flex items-center">
        <a-button class="flex items-center" type="primary" @click="addUser"><PlusOutlined style="font-size: 16px" />新增</a-button>
        <!-- <a-button :disabled="!hasSelected" class="ml-5 flex items-center" type="primary" danger @click="search"><DeleteOutlined style="font-size: 16px" />删除</a-button> -->
      </div>

      <div class="px-10">
        <!-- :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }" -->
        <a-table :pagination="pagination" :columns="columns" :data-source="tableData" />
      </div>
    </div>
    <!-- template 内部必须有一个根节点 div，否则<Transition>将会失效，所以这个<a-modal></a-modal> 组件必须放在 根节点 div 里面 -->
    <a-modal v-model:open="visible" :title="title" @ok="submit" @cancel="closeModal">
      <a-form ref="formRef" name="custom-validation" :model="formState" :rules="rules" v-bind="layout" @finish="handleFinish" @validate="handleValidate" @finishFailed="handleFinishFailed">
        <!-- 用户根据单位代码去查询 审核状态 -->
        <a-form-item has-feedback label="姓名" name="name">
          <a-input v-model:value="formState.name" autocomplete="off" />
        </a-form-item>
        <a-form-item has-feedback label="性别" name="sex">
          <a-radio-group v-model:value="formState.sex" name="radioGroup">
            <a-radio v-for="(item, index) in enumsSex" :key="index" :value="item.value">{{ item.label }}</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item has-feedback label="手机号" name="telephone">
          <a-input v-model:value="formState.telephone" autocomplete="off" />
        </a-form-item>
        <a-form-item has-feedback label="启用状态" name="isEnable">
          <a-radio-group v-model:value="formState.isEnable" name="radioGroup">
            <a-radio v-for="(item, index) in enumsIsEnable" :key="index" :value="item.value">{{ item.label }}</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="tsx">
/**
 * @current 当前页
 * @pages 总页数
 * @size 每页多少条
 * @total 总条数
 */
import { message } from 'ant-design-vue'
import { dictSelectNodes } from '@/config/dict.ts'
const enumsSex = ref<any[]>(dictSelectNodes('Sex'))
const enumsIsEnable = ref<any[]>(dictSelectNodes('IsEnable'))
import api from '@/axios/index.ts'
import { SearchOutlined, SyncOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { ref, computed, reactive, onMounted, watch } from 'vue'

const focus = () => {
  console.log('focus')
}

const handlePageChange = (page: any, pageSize: any) => {
  console.log('🚀 ~ handlePageChange ~ page, pageSize:', page, pageSize)

  pagination.current = page
  pagination.pageSize = pageSize
  getUserList()
}

const pagination = reactive({
  pageSize: 5, // 每页显示的条数
  showSizeChanger: true, // 是否可以改变每页显示的条数
  pageSizeOptions: ['5', '10'], // 可选的每页显示条数
  showQuickJumper: true, // 是否可以快速跳转到指定页
  showTotal: (total: string | number) => `共 ${total} 条`, // 显示总条数和当前数据范围
  current: 1, // 当前页数
  total: null as number | string | null, // 总条数
  onChange: handlePageChange, // 页码改变时的回调函数
})

const getUserList = async function (params?: any) {
  let obj = { page: { size: pagination.pageSize, current: pagination.current }, params }
  const res = await api.post<any>('/managementPoliceUnitUser/pager', obj)
  const { total, records } = res.data
  tableData.value = records
  pagination.total = Number(total)
}

onMounted(() => {
  getUserList()
})

type Key = string | number

interface DataType {
  key: Key
  name: string
  age: number
  address: string
}

interface RecordItem {
  account: string
  createTime: string
  createUserName: string | null
  isAdmin: LabelValue // 对象结构
  isEnable: EnableStatus // 包含扩展数据的对象
  name: string
  sex: LabelValue // 对象结构
  snowFlakeId: string // Snowflake ID 是字符串
  telephone: string
}

interface LabelValue {
  value: number
  label: string
}

interface EnableStatus {
  value: number
  label: string
  extData: {
    color: string
  }
}
const columns = [
  // {
  //   title: '序号',
  //   customRender: (text, record, index, column) => {
  //     console.log(index)
  //   },
  // },
  {
    title: '账号',
    dataIndex: 'account',
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    dataIndex: 'sex',
    title: '性别',
    customRender: ({ record }: { record: RecordItem }) => {
      return <a-tag>{record.sex.label}</a-tag>
    },
  },

  {
    title: '是否启用',
    dataIndex: 'isEnable',
    customRender: ({ record }: { record: RecordItem }) => {
      return record.isEnable.extData?.color === 'success' ? <a-tag color='green'>{record.isEnable.label}</a-tag> : <a-tag color='#f50'>{record.isEnable.label}</a-tag>
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    dataIndex: 'opt',
    title: '操作',
    fixed: 'right',
    customRender({ record }: { record: RecordItem }) {
      return record.isAdmin.value === 1 ? (
        <a-space>
          <a-button
            type='primary'
            onClick={async () => {
              console.log(record)
              {
                visible.value = true
                title.value = '编辑用户'
                formState.name = record.name
                formState.telephone = record.telephone
                formState.sex = record.sex.value
                formState.isEnable = record.isEnable.value
                formState.snowFlakeId = record.snowFlakeId
              }
            }}
          >
            编辑
          </a-button>
          <a-button type='primary' danger>
            <a-popconfirm
              title='确认删除账号吗?'
              onConfirm={async () => {
                {
                  const resp = await api.delete('/managementPoliceUnitUser/deleteById', {
                    managementPoliceUnitUserId: record.snowFlakeId,
                  })
                  message.success(resp.message)
                  getUserList()
                }
              }}
            >
              删除
            </a-popconfirm>
          </a-button>
        </a-space>
      ) : (
        <i></i>
      )
    },
  },
]

const saveOrUpdate = async () => {
  const res = await api.post<any>('/managementPoliceUnitUser/saveOrUpdate', formState)
  message.success(res.message)
  visible.value = false
  getUserList() //刷新数据
  resetForm() //重置表单
  resetFormState()
  if (formState.hasOwnProperty('snowFlakeId')) {
    delete formState.snowFlakeId
  }
  if (title.value === '新增用户') {
  }
  // console.log('saveOrUpdate', res)
}
const visible = ref(false)
const title = ref('')
const submit = async () => {
  await formRef.value?.validate() //等待表单校验
  console.log('表单校验完成')
  saveOrUpdate()
}
const closeModal = () => {
  resetForm()
  resetFormState()
}
const addUser = () => {
  visible.value = true
  title.value = '新增用户'
}

const tableData = ref<DataType[]>([])
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 14 },
}
import type { FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
interface FormState {
  name: string
  sex: string | number
  telephone: string
  isEnable: string | number
  snowFlakeId?: string | number
  [key: string]: any // 添加索引签名
}
const formRef = ref<FormInstance>()
const formState = reactive<FormState>({
  name: '',
  sex: '',
  telephone: '',
  isEnable: '',
})
const checkName = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请输入姓名')
  } else {
    return Promise.resolve()
  }
}
const checkSex = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请选择姓名')
  } else {
    return Promise.resolve()
  }
}
var reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
const checkTelephone = async (_rule: Rule, value: string) => {
  if (reg_tel.test(value.trim())) {
    return Promise.resolve()
  } else {
    return Promise.reject('手机号格式不正确')
  }
}
const checkIsEnable = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请选择启用状态')
  } else {
    return Promise.resolve()
  }
}
const rules: Record<string, Rule[]> = {
  name: [{ required: true, validator: checkName, trigger: 'change' }],
  sex: [{ required: true, validator: checkSex, trigger: 'change' }],
  telephone: [{ required: true, validator: checkTelephone, trigger: 'change' }],
  isEnable: [{ required: true, validator: checkIsEnable, trigger: 'change' }],
}

const handleFinish = (values: FormState) => {
  console.log('自定义校验成功')
  console.log(values)
}
const handleFinishFailed = (errors: any) => {
  console.log(errors)
}
const resetForm = () => {
  formRef.value?.resetFields()
}
const resetFormState = () => {
  // Object.keys(formState).forEach((key) => (formState[key] = ''))
  for (const key in formState) {
    if (Object.prototype.hasOwnProperty.call(formState, key)) {
      formState[key] = '' // 或者根据实际情况设为 null、undefined 或其他值
    }
  }
}

const handleValidate = (...args: any[]) => {
  console.log(args)
}

// 搜索相关 ⬇️
const searchParams = reactive({
  name: '',
  telephone: '',
  sex: null,
  isEnable: null,
})

const searchUser = ref('')
const isEnableValue = ref(null)
const sexValue = ref(null)
const searchTelePhone = ref('')
const handleChange = (value: string) => {
  console.log(`selected ${value}`)
}
const sexChange = (value: string) => {
  console.log(`selected ${value}`)
}
const search = async () => {
  searchParams.name = searchUser.value
  searchParams.telephone = searchTelePhone.value
  searchParams.sex = sexValue.value
  searchParams.isEnable = isEnableValue.value

  getUserList(searchParams)
}
const resetSearch = () => {
  searchUser.value = ''
  isEnableValue.value = null
  sexValue.value = null
  searchTelePhone.value = ''
}
</script>
