<template>
  <!-- 背景色覆盖整个页面，并且能够正常滚动内容，同时固定内层内容的位置 -->
  <body style="margin: 0; padding: 0; overflow: auto">
    <!-- 背景色层 -->
    <div class="bg-gray-100" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: -1"></div>
    <!-- 内容层 -->
    <div class="flex justify-center" style="position: relative; margin: 20px auto">
      <!-- 卡片盒子 -->
      <div class="w-full max-w-3xl p-6 bg-white rounded-xl shadow-md">
        <!-- type="card" -->
        <a-tabs v-model:activeKey="activeKey" :tabBarGutter="300" centered>
          <a-tab-pane key="1" tab="注册">
            <div style="max-height: 500px; overflow-y: auto">
              <a-form ref="formRef" name="custom-validation" :model="formState" :rules="rules" v-bind="layout" @finish="handleFinish" @validate="handleValidate" @finishFailed="handleFinishFailed">
                <div style="height: 100%">
                  <a-form-item v-if="options.length > 0" label="行政区划">
                    <a-cascader
                      change-on-select
                      :load-data="loadData"
                      :field-names="{ label: 'label', value: 'value', children: 'children' }"
                      @change="cascaderChange"
                      style="width: 300px"
                      v-if="options.length > 0"
                      v-model:value="value"
                      :options="options"
                      :show-search="{ filter }"
                      placeholder="请选择行政区划"
                    />
                  </a-form-item>
                  <a-form-item v-else label="行政区划">
                    <!-- &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp数据加载中～～～ -->

                    <div class="flex justify-center items-center" style="width: 200px"><a-spin /></div>
                  </a-form-item>
                </div>
                <!-- 用户根据单位代码去查询 审核状态 -->
                <a-form-item has-feedback label="单位机构代码" name="code">
                  <a-input v-model:value="formState.code" autocomplete="off" />
                </a-form-item>
                <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="address">
                  <a-input v-model:value="formState.address" autocomplete="off" />
                </a-form-item>
                <a-form-item has-feedback label="联系人姓名" name="contactName">
                  <a-input v-model:value="formState.contactName" autocomplete="off" />
                </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 :wrapper-col="{ span: 14, offset: 4 }">
                  <a-button type="primary" html-type="submit">提交</a-button>
                  <a-button style="margin-left: 10px" @click="resetForm">重置表单</a-button>
                </a-form-item>
              </a-form>
            </div>
          </a-tab-pane>
          <a-tab-pane key="2" tab="查询注册结果">
            <div class="flex items-center justify-center flex-col" style="max-height: 500px; overflow-y: auto">
              <a-form :label-col="labelCol" :wrapper-col="wrapperCol" :model="statusDate" layout="horizontal">
                <a-form-item label="单位机构代码" name="onlyCode" :rules="[{ required: true, message: '请输入单位代码进行查询' }]">
                  <a-input placeholder="请输入单位代码查询" :allowClear="true" v-model:value="statusDate.onlyCode"></a-input>
                </a-form-item>
                <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
                  <a-button type="primary" html-type="submit" style="width: 100px" @click="getCheckStatus">确认</a-button>
                </a-form-item>
              </a-form>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
  </body>
</template>

<script setup lang="ts">
// import { storeTreeData, loadTreeFromCache } from '@/utils/DB.ts'
import { useRouter } from 'vue-router'
const router = useRouter()
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import api from '@/axios/index.ts'
import type { ShowSearchType } from 'ant-design-vue/es/cascader'
import { onMounted, reactive, ref, defineComponent, createVNode, h } from 'vue'
defineComponent({
  name: 'Register',
})
onMounted(() => {
  getTree(0)
})
import type { CascaderProps } from 'ant-design-vue'
const loadData: CascaderProps['loadData'] = async (selectedOptions) => {
  const targetOption = selectedOptions[selectedOptions.length - 1]
  targetOption.loading = true
  const res = await api.get<any>('/common/administrativeDivisionByParentCode', { parentCode: targetOption.value })
  for (let index = 0; index < res.data.length; index++) {
    delete res.data[index].children
  }
  targetOption.children = [...res.data]
  options.value = [...options.value]
  targetOption.loading = false
}
const labelCol = { style: { width: '120px' } }
const wrapperCol = { span: 14 }
const filter: ShowSearchType['filter'] = (inputValue, path) => {
  return path.some((option) => option.title.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
}
const value = ref<string[]>([])
const options = ref<CascaderProps['options']>([])

const cascaderChange = (value: any): void => {
  formState.administrativeDivisionCodes = [...value]
}

// 获取树形结构数据并存储在 IndexedDB 中的主函数
const getTree = async (parentCode: string | number) => {
  const res = await api.get<any>('/common/administrativeDivisionByParentCode', { parentCode })
  for (let index = 0; index < res.data.length; index++) {
    delete res.data[index].children
  }
  options.value = res.data
  // // 先尝试从缓存中加载数据
  // const cachedData = await loadTreeFromCache()
  // if (cachedData) {
  //   console.log('未发请求')
  //   // 如果缓存存在，直接使用缓存数据
  //   options.value = cachedData
  //   // console.log('Loaded from cache:', cachedData)
  // } else {
  //   console.log('发起了请求')
  //   // 如果缓存不存在，发起 API 请求
  //   const res = await api.get<any>('/common/administrativeDivisionTree', { level: 0 })
  //   options.value = res.data
  //   await storeTreeData(res.data)
  // }
}
import type { Rule } from 'ant-design-vue/es/form'
import type { FormInstance } from 'ant-design-vue'

interface FormState {
  name: string
  code: number | string
  administrativeDivisionCodes: any[]
  address: string
  telephone: string //联系人手机
  contactName: string //联系人姓名
}
const formRef = ref<FormInstance>()
const formState = reactive<FormState>({
  name: '',
  code: '',
  administrativeDivisionCodes: [],
  address: '',
  telephone: '',
  contactName: '',
})

const checkName = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请输入单位机构名称')
  } else {
    return Promise.resolve()
  }
}
const checkCode = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请输入单位机构代码')
  } else {
    return Promise.resolve()
  }
}
const checkAddress = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请输入详细地址')
  } else {
    return Promise.resolve()
  }
}
const checkTelephone = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请输入联系人电话')
  } else {
    return Promise.resolve()
  }
}
const checkContactName = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请输入联系人姓名')
  } else {
    return Promise.resolve()
  }
}
// 写自定义 Rule 是为之后修改做准备
const rules: Record<string, Rule[]> = {
  name: [{ required: true, validator: checkName, trigger: 'change' }],
  code: [{ required: true, validator: checkCode, trigger: 'change' }],
  address: [{ required: true, validator: checkAddress, trigger: 'change' }],
  telephone: [{ required: true, validator: checkTelephone, trigger: 'change' }],
  contactName: [{ required: true, validator: checkContactName, trigger: 'change' }],
}
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 14 },
}

const register = () => {
  if (value.value.length === 0) {
    message.error('请选择行政区划')
    return
  } else {
    const { telephone, contactName, ...rest } = formState
    const contactPersonInfo = {
      telephone,
      name: contactName,
    }
    const submitForm = {
      ...rest,
      contactPersonInfo,
    }
    api.post<any>('/common/policeUnitRegister', { ...submitForm }).then((res) => {
      console.log(res)
      if (res.code === 200) {
        message.success('提交成功')
      }
    })
  }
}

const handleFinish = (values: FormState) => {
  console.log('自定义校验成功')
  console.log(values)
  register()
}
const handleFinishFailed = (errors: any) => {
  console.log(errors)
}
const resetForm = () => {
  formRef.value?.resetFields()
  value.value = []
}
const handleValidate = (...args: any[]) => {
  console.log(args)
}

const activeKey = ref('1')
const loading = ref<boolean>(false)

const getCheckStatus = async () => {
  if (statusDate.onlyCode.trim() === '') {
    return
  }
  loading.value = true
  api
    .post<dataStatus>('/management/getCheckStatus', statusDate)
    .then((res) => {
      showConfirm(res.data as dataStatus)
    })
    .finally(() => {
      loading.value = false
    })
}
import { useUserStore } from '@/stores/modules/userStore.ts'
import { log } from 'console'
const showConfirm = (columnsDate: dataStatus) => {
  if (columnsDate.checkStatus.value === 0) {
    Modal.success({
      title: `审核通过`,
      icon: createVNode(ExclamationCircleOutlined),
      content: h('div', {}, [h('div', `账号：${columnsDate.account}`), h('div', `密码：${columnsDate.password}`), h('div', `${columnsDate.remark}`)]),
      okText: '跳转',
      async onOk() {
        await useUserStore().resetUserInfo()
        await router
          .replace({
            path: '/login',
            query: {
              account: columnsDate.account,
              password: columnsDate.password,
            },
          })
          .then(() => {})
      },
      onCancel() {},
    })
  } else {
    Modal.error({
      title: `未审核`,
      icon: createVNode(ExclamationCircleOutlined),
      content: `${columnsDate.remark}`,
    })
  }
}

const statusDate = reactive({
  // __APP_ENV.VITE_APP_ENV === 'development' ? 'dawda' : '',
  onlyCode: '',
  unitOptType: 'POLICE_UNIT',
})
</script>
