import dayjs from 'dayjs'
import { TableProMaxProps, TableProMaxSlots } from '@/types/components/table'
import { EnterprisesUnitPagerQueryParams, securityUnitIdListPagerVo, securityUnitIdListParams, PoliceUnitPagerVo } from '@/types/views/unitManage/police/policeUnit.ts'
import { reactive, ref, h } from 'vue'
import { FormExpose } from 'ant-design-vue/es/form/Form'
import { ComponentExposed } from 'vue-component-type-helpers'
import { FormProMaxItemOptions } from '@/types/components/form'
import { dictSelectNodes } from '@/config/dict.ts'
import { Button, message, Modal, Space, Tag, Input } from 'ant-design-vue'
import api from '@/axios'
import TableProMax from '@/components/table/TableProMax.vue'
import { deleteDataModal } from '@/components/tsx/ModalPro.tsx'
import { PageParams } from '@/types/hooks/useTableProMax.ts'
import FormProMax from '@/components/form/FormProMax.vue'
import { debounce } from 'lodash-es'
import { SearchOutlined } from '@ant-design/icons-vue'
import axios from 'axios'
import SingleImageFileUpload from '@/components/upload/SingleImageFileUpload.vue'
type _TableProps = TableProMaxProps<securityUnitIdListPagerVo, EnterprisesUnitPagerQueryParams>

const _formParams = reactive<securityUnitIdListParams>({
  snowFlakeId: '', //
  serviceProjectId: '', //	服务项目id
  securityUnitId: '', //	保安单位id
  name: '', //
  photo: '',
  telephone: '',
  workPost: '',
  sex: '',
  nativePlace: '',
  idCard: '',
  dateOfBirth: '',
  securityNumber: '',
  noSecurityNumberDesc: '',
  homeAddress: '',
  remark: '',
})
const cardBlur = () => {
  let value = _formParams.idCard
  if (!value?.length || value.length < 18) {
    _formParams.dateOfBirth = ''
    return
  }
  const birthDate = value.substring(6, 14)
  const year = birthDate.substring(0, 4)
  const month = birthDate.substring(4, 6)
  const day = birthDate.substring(6, 8)
  var _data = new Date(parseInt(year), parseInt(month) - 1, parseInt(day))
  _formParams.dateOfBirth = dayjs(_data).format('YYYY-MM-DD HH:mm:ss')
  console.log('🚀 ~ cardBlur ~ _data:', _formParams.dateOfBirth)
}
const searchSecurityUnitId = debounce(async () => {
  if (process.env.NODE_ENV === 'development') {
    console.log('process.env.NODE_ENV === development')
    const res = await axios.get(`https://www.hnjinglian.cn:5678/common/querySecurityNumberByIdCard?idCard=${_formParams.idCard}`)
    if (res.data?.data?.hasOwnProperty('bayzh')) {
      _formParams.securityNumber = res.data.data.bayzh
      _formParams.name = res.data.name
      message.success(res.data.message)
    } else {
      message.error('未查询到保安证件号')
    }
  } else {
    const res = await api.get<any>('/common/querySecurityNumberByIdCard', { idCard: _formParams.idCard })
    console.log(res)
    if (res.data?.hasOwnProperty('bayzh')) {
      _formParams.securityNumber = res.data.bayzh
      _formParams.name = res.data.name
      message.success(res.message)
    } else {
      message.error('未查询到保安证件号')
    }
  }
  cardBlur()
}, 300)
const saveOrUpdateEnterprisesUnit = (callback: Function, params, type: string) => {
  // console.log('🚀 ~ saveOrUpdateEnterprisesUnit ~ params:', params)
  if (type === 'add') {
    _formParams.serviceProjectId = params.snowFlakeId
    _formParams.securityUnitId = params.securityUnitId
  } else {
    _formParams.snowFlakeId = params.snowFlakeId
    _formParams.serviceProjectId = params.serviceProjectId
    _formParams.securityUnitId = params.securityUnitId
    _formParams.name = params.name
    _formParams.photo = params?.photo
    _formParams.telephone = params.telephone.originalValue
    _formParams.workPost = params.workPost
    _formParams.sex = params.sex.value
    _formParams.nativePlace = params.nativePlace
    _formParams.idCard = params.idCard.originalValue
    _formParams.dateOfBirth = params.dateOfBirth
    _formParams.securityNumber = params.securityNumber
    _formParams.noSecurityNumberDesc = params?.noSecurityNumberDesc
    _formParams.homeAddress = params.homeAddress
    _formParams.remark = params.remark
  }

  const _formRef = ref<FormExpose>(null)
  const uploadFileRef = ref(null)
  const _formOptions = ref<FormProMaxItemOptions<securityUnitIdListParams>>({
    photo: {
      type: 'custom',
      label: '头像',
      customRender: () => <SingleImageFileUpload height={200} v-model:value={_formParams.photo} ref={uploadFileRef} />,
    },

    name: {
      type: 'input',
      label: '姓名',
      required: true,
    },
    idCard: {
      type: 'custom',
      label: '身份证',
      required: true,
      customRender: () => (
        <Space>
          <Input allow-clear v-model:value={_formParams.idCard} placeholder={'请输入身份证号'} />
          <Button type={'primary'} icon={h(SearchOutlined)} onClick={() => searchSecurityUnitId()}>
            搜索保安证号
          </Button>
        </Space>
      ),
    },

    telephone: {
      type: 'input',
      label: '手机号',
      // required: true,
    },
    sex: {
      type: 'radioGroup',
      label: '性别',
      required: true,
      options: [...dictSelectNodes('Sex')],
    },
    securityNumber: {
      type: 'input',
      label: '保安证号',
      required: true,
    },
    dateOfBirth: {
      type: 'datePicker',
      label: '出生日期',
      componentsProps: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
      },
      required: true,
    },

    workPost: {
      type: 'input',
      label: '工作岗位',
    },
    nativePlace: {
      type: 'input',
      label: '籍贯',
    },
    homeAddress: {
      type: 'input',
      label: '家庭住址',
    },
    noSecurityNumberDesc: {
      type: 'input',
      label: '无证说明',
    },

    remark: {
      type: 'inputTextArea',
      label: '备注',
    },
  })
  Modal.confirm({
    title: params.name ? `【${params.name}】 编辑保安信息` : '新增保安人员',
    width: 600,
    icon: ' ',
    centered: true,
    content: () => <FormProMax ref={_formRef} v-model:value={_formParams} formItemOptions={_formOptions.value} />,
    onOk: async () => {
      await _formRef.value?.validate()
      const resp = await api.post('/m2/eu/add_upd_sec_user', {
        ..._formParams,
      })
      message.success(resp.message)
      clearForm()
      callback && callback()
    },
    onCancel: async () => {
      clearForm()
    },
  })
}
const clearForm = () => {
  _formParams.snowFlakeId = ''
  _formParams.serviceProjectId = ''
  _formParams.securityUnitId = ''
  _formParams.name = ''
  _formParams.photo = ''
  _formParams.telephone = ''
  _formParams.workPost = ''
  _formParams.sex = ''
  _formParams.nativePlace = ''
  _formParams.idCard = ''
  _formParams.dateOfBirth = ''
  _formParams.securityNumber = ''
  _formParams.noSecurityNumberDesc = ''
  _formParams.homeAddress = ''
  _formParams.remark = ''
}
export const showEnterprisesUnit = (record_) => {
  // console.log('🚀 ~ showEnterprisesUnit ~ record_:', record_)
  const _tableRef = ref<ComponentExposed<typeof TableProMax>>(null)
  const _columns: _TableProps['columns'] = [
    {
      dataIndex: 'name',
      title: '姓名',
      width: 100,
      ellipsis: true,
    },

    {
      dataIndex: 'idCard',
      title: '身份证',
      customRender: ({ text }) => {
        return text.desensitizedValue
      },
      width: 160,
      ellipsis: true,
    },

    {
      dataIndex: 'sex',
      title: '性别',
      width: 60,
      customRender: ({ record }) => {
        return <Tag color={'success'}>{record.sex.label}</Tag>
      },
    },
    {
      dataIndex: 'dateOfBirth',
      title: '出生日期',
      width: 100,
      ellipsis: true,
    },
    {
      dataIndex: 'telephone',
      title: '手机号',
      width: 120,
      ellipsis: true,
      customRender: ({ text }) => text?.originalValue,
    },
    {
      dataIndex: 'securityNumber',
      title: '保安证号',
      width: 150,
      ellipsis: true,
    },
    {
      dataIndex: 'nativePlace',
      title: '籍贯',
      width: 120,
      ellipsis: true,
    },
    {
      dataIndex: 'workPost',
      title: '工作岗位',
      width: 120,
      ellipsis: true,
    },

    {
      dataIndex: 'homeAddress',
      title: '家庭住址',
      width: 120,
      ellipsis: true,
    },
    {
      dataIndex: 'remark',
      title: '备注',
      width: 120,
    },
    {
      dataIndex: 'createTime',
      title: '创建时间',
      width: 120,
      ellipsis: true,
    },

    {
      dataIndex: 'opt',
      title: '操作',
      width: 200,
      fixed: 'right',
      customRender: ({ record }) => (
        <Space>
          <Button class='btn-warn' onClick={() => saveOrUpdateEnterprisesUnit(_tableRef.value?.requestGetTableData, record, 'edit')}>
            编辑
          </Button>
          <Button
            class='btn-danger'
            onClick={() =>
              deleteDataModal(record.name, async () => {
                const resp = await api.delete('/m2/eu/del_security_user_id', {
                  securityUserId: record?.snowFlakeId,
                })
                message.success(resp.message)
                await _tableRef.value?.requestGetTableData()
              })
            }
          >
            删除
          </Button>
        </Space>
      ),
    },
  ]
  const x: number = _columns.reduce((a, b) => a + (b.width as number), 0)
  const _reqApi: _TableProps['requestApi'] = (params) => {
    // console.log(record_);

    ;(params as PageParams<EnterprisesUnitPagerQueryParams>).params.serviceProjectId = record_.snowFlakeId
    return api.post('/m2/eu/sec_user_pager', params)
  }
  Modal.info({
    title: `【${record_.name}】 管理保安人员`,
    width: '80%',
    centered: true,
    maskClosable: true,
    content: () => (
      <TableProMax
        scroll={{ x: x }}
        ref={_tableRef}
        size='small'
        columns={_columns}
        requestApi={_reqApi}
        // searchFormOptions={{
        //   name: {
        //     type: 'input',
        //     label: '姓名',
        //   },
        //   securityNumber: {
        //     type: 'input',
        //     label: '保安证号',
        //   },
        //   telephone: {
        //     type: 'input',
        //     label: '手机号',
        //   },
        // }}
        v-slots={
          {
            tableHeader: (_) => {
              return (
                <Space>
                  <Button class='btn-success' onClick={() => saveOrUpdateEnterprisesUnit(_tableRef.value?.requestGetTableData, record_, 'add')}>
                    新增
                  </Button>
                </Space>
              )
            },
          } as TableProMaxSlots<PoliceUnitPagerVo>
        }
      />
    ),
  })
}
