<template>
  <view class="form">
    <nut-form ref="formRef" :model-value="formData" :rules="rules">
      <nut-form-item label="头像" prop="avatar">
        <!--        <view  class="uploadPictures" @click="chooseImage">-->
        <!--          <view v-if="!formData.photo">-->
        <!--            <IconFont name="uploader"  size="25" color="#98a7b0"></IconFont>-->
        <!--          </view>-->
        <!--          <image v-else :src="minioBaseUrl +formData.photo" style="width: 100%; height: 100%"></image>-->
        <!--        </view>-->
        <view @click="chooseImage" size>
          <image v-if="!formData.photo" src="@/assets/logo/avatar1.png" style="width: 50px; height: 50px"></image>
          <image v-else :src="minioBaseUrl +formData.photo" style="width: 160px; height: 128px"></image>
        </view>
      </nut-form-item>
      <nut-form-item label="身份证" prop="idCard">
        <view style="display: flex; justify-content: space-between; align-items: center">
          <nut-input v-model="formData.idCard" placeholder="请填写身份证" type="text" @blur="cardBlur"/>
          <view style="color: #3a6bbe; width: 70px; text-align: center" @click="idCardBlur(formData, 0)">查询</view>
        </view>
      </nut-form-item>
      <nut-form-item label="姓名" prop="name">
        <nut-input v-model="formData.name" placeholder="请输入姓名" type="text"/>
      </nut-form-item>
      <nut-form-item label="性别" prop="sex">
        <nut-radio-group v-model="formData.sex" direction="horizontal">
          <nut-radio v-for="item in SEX" :key="item.value" :label="item.value">{{ item.label }}</nut-radio>
        </nut-radio-group>
      </nut-form-item>
      <nut-form-item label="出生日期" prop="dateOfBirth">
        <view @click="showPicker = true">
          {{ formData.dateOfBirth ? dayjs(formData.dateOfBirth).format('YYYY-MM-DD') : '请选择出生年月' }}
        </view>
      </nut-form-item>
      <nut-form-item label="工作岗位" prop="workPost">
        <nut-input v-model="formData.workPost" placeholder="请输入工作岗位" type="text"/>
      </nut-form-item>
      <nut-form-item label="手机号" prop="telephone">
        <nut-input v-model="formData.telephone" placeholder="请输入手机号" type="text"/>
      </nut-form-item>
      <nut-form-item label="文化程度" prop="educationLevel">
        <view @click="showBottom = true" >
          {{educationLevelValue?educationLevelValue:'请选择文化程度'}}
        </view>
      </nut-form-item>
      <nut-form-item label="籍贯" prop="nativePlace">
        <nut-input v-model="formData.nativePlace" placeholder="请输入籍贯" type="text"/>
      </nut-form-item>
      <nut-form-item label="地址" prop="homeAddress">
        <nut-input v-model="formData.homeAddress" placeholder="请输入地址" type="text"/>
      </nut-form-item>
      <nut-form-item label="保安证件号" prop="securityNumber">
        <nut-input v-model="formData.securityNumber" placeholder="请输入保安证号" type="text"/>
      </nut-form-item>
      <nut-form-item label="无证说明" v-if="!formData.securityNumber">
        <nut-input v-model="formData.noSecurityNumberDesc" placeholder="无证说明" type="text"/>
      </nut-form-item>
      <nut-form-item label="备注" prop="remark">
        <nut-input v-model="formData.remark" placeholder="请填写备注" type="text"/>
      </nut-form-item>
    </nut-form>
    <view class="formButton">
      <nut-button style="width: 45%" type="success" size="small" @click="submit">提交</nut-button>
      <nut-button style="width: 45%" size="small" @click="reset">重置表单</nut-button>
    </view>
    <nut-popup v-model:visible="showPicker" position="bottom">
      <nut-date-picker
        v-model="formData.dateOfBirth"
        :three-dimensional="false"
        :min-date="new Date(1900, 1, 1)"
        :max-date="new Date(2100, 1, 1)"
        @confirm="showPicker = false"
        @cancel="showPicker = false"
      ></nut-date-picker>
    </nut-popup>
    <nut-dialog content="详情" v-model:visible="visible" @ok="onOk" @cancel="cancel">
      <slot>
        <view style="margin-bottom: 5px">
          <view>姓名：{{ securityNumberByIdCard?.name ? securityNumberByIdCard.name : '无' }}</view>
          <view>保安证件号：{{ securityNumberByIdCard?.bayzh ? securityNumberByIdCard?.bayzh : '无' }}</view>
          <view>身份证：{{ securityNumberByIdCard?.sfzhm ? securityNumberByIdCard?.sfzhm : '无' }}</view>
        </view>
      </slot>
    </nut-dialog>
    <nut-popup v-model:visible="showBottom" position="bottom" :style="{ height: '40%' }">
      <nut-picker
        :columns="columns"
        :field-names="{
      text: 'label',
      value: 'value',
      children: 'extData'
    }"
        title="学历选择"
        @confirm="confirm"
        @cancel="showBottom = false"
      />
    </nut-popup>
  </view>
</template>
<script setup lang="ts">
import {ref} from 'vue'
import {enumSelectNodes} from '@/enums'
import {FormRules} from '@nutui/nutui-taro/dist/types/__VUE/form/types'
import api from '@/request'
import './securityUserForm.scss'
import Taro, {useLoad} from '@tarojs/taro'
import dayjs from 'dayjs'
import {SecurityUserFormParams, securityNumberByIdCard} from '@/types/subPages/projectManager/securityUserForm'
import {FormInstance} from '@nutui/nutui-taro'
import {generateSimpleObjectName, getResignedObjectUrl} from '@/utils'

const SEX: any = enumSelectNodes('Sex')
const minioBaseUrl = process.env.TARO_APP_MINIO_URL
const BUCKET = process.env.TARO_APP_MINIO_BUCKET
const showPicker = ref(false)
const showBottom = ref(false)
const Url = ref('')
const type = ref<'formInput' | 'QcCodeInput'>(null!)
const formData = ref<SecurityUserFormParams>({} as any)
const formRef = ref<FormInstance>(null!)
const visible = ref<boolean>(false)
const securityNumberByIdCard = ref<securityNumberByIdCard | any>()
const uploadRef = ref<any>(null)
const modelValue = ref('')
const columns: any = enumSelectNodes('EducationLevel')


const rules: FormRules = {
  name: [{required: true, message: '请输入姓名'}],
  sex: [{required: true, message: '请选择性别'}],
  idCard: [
    {required: true, message: '请输入身份证号'},
    {
      regex: /^(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))((0[1-9])|([12][0-9])|(30|31))\d{3}(\d|X)$)/,
      message: '身份证格式错误',
    },
  ],
  telephone: [{required: true, message: '请输入手机号'}],
  educationLevel:[{required: true, message: '请选择文化程度'}]
}

const educationLevelValue = ref('')
// 文化程度
const confirm = ({selectedOptions}) => {
  Object.keys(selectedOptions).forEach((item:any,index:number)=>{
    console.log(item)
    educationLevelValue.value = selectedOptions[index].label
    formData.value.educationLevel =  selectedOptions[index].value
  })
  showBottom.value = false
}
useLoad((options) => {
  type.value = options.type
  if (type.value === 'QcCodeInput') {
    console.log(1111)
    formData.value = {
      name: '',
      serviceProjectId: options.pid,
      securityUnitId: options.uid,
      sex: 0,
      idCard: null,
      telephone: null,
      dateOfBirth: null,
      noSecurityNumberDesc: options.noSecurityNumberDesc,
      photo: '',
      educationLevel: ''
    }
  } else {
    const form = JSON.parse(options.securityUser)
    educationLevelValue.value = form.educationLevel?.label
    formData.value = Object.assign({}, form, {
      idCard: form.idCard.originalValue,
      telephone: form.telephone.originalValue,
      photo: form.photo,
      educationLevel:  form.educationLevel?.value
    })
  }
})

const idCardBlur = async (e: any, num: number) => {
  const value = e.idCard
  if (value) {
    if (BUCKET === 'police-security-dev') {
      Taro.request({
        url: 'https://www.hnjinglian.cn:5678/common/querySecurityNumberByIdCard',
        data: {
          idCard: value,
        },
        method: 'GET',
        success: ({data}) => {
          console.log(data.data)
          visible.value = true
          securityNumberByIdCard.value = data.data
        },
      })
    } else {
      const resp = await api.get('/common/querySecurityNumberByIdCard', {idCard: value})
      visible.value = true
      securityNumberByIdCard.value = resp?.data
    }
  } else {
    visible.value = false
  }
  cardBlur(value, num)
}

const cardBlur = (e: any, num: number) => {
  let value: string
  if (num === 0) {
    value = e
  } else {
    value = e.detail.value
  }
  if (!value?.length || value.length < 18) {
    formData.value.dateOfBirth = null
    cancel()
    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)
  formData.value.dateOfBirth = new Date(parseInt(year), parseInt(month) - 1, parseInt(day))
}

const onOk = () => {
  formData.value.securityNumber = securityNumberByIdCard.value?.bayzh
  formData.value.name = securityNumberByIdCard.value?.name
}
const cancel = () => {
  formData.value.securityNumber = ''
  formData.value.name = ''
  visible.value = false
}
const chooseImage = () => {
  Taro.chooseMedia({
    count: 1, // 选择一个文件
    mediaType: ['image', 'video'],
    sourceType: ['album', 'camera'],
    sizeType: ['original', 'compressed'],
    camera: 'front',
    success: async (res) => {
      Url.value = res.tempFiles[0].tempFilePath
      const objectName = generateSimpleObjectName(Url.value, '/securityUser')
      const uploadUrl = await getResignedObjectUrl(process.env.TARO_APP_MINIO_BUCKET, objectName)

      modelValue.value = '/' + process.env.TARO_APP_MINIO_BUCKET + objectName
      // 使用 wx.getFileSystemManager().readFileSync 读取文件的二进制内容
      const fs = Taro.getFileSystemManager()
      const fileData = fs.readFileSync(Url.value) // 返回的是文件的二进制内容
      // 发送 PUT 请求上传二进制文件
      Taro.request({
        url: uploadUrl, // 后端上传接口
        method: 'PUT',
        header: {
          'Content-Type': 'application/octet-stream', // 设置为二进制流
        },
        data: fileData, // 传递二进制数据
        success(res) {
          formData.value.photo = modelValue.value
          console.log('上传成功', res)
        },
        fail(err) {
          console.error('上传失败', err)
        },
      })
    },
    fail(err) {
      console.error('选择文件失败', err)
    },
  })
}
const submit = () => {
  formData.value.photo = modelValue.value
  formRef.value?.validate().then(async ({valid}) => {
    if (valid) {
      let url: string
      if (type.value === 'formInput') {
        url = '/mp/user/add_security_user_upd'
      } else {
        url = '/mp/user/qrCodeFormInputSecurityUser'
      }
      console.log(formData.value)
      const resp = await api.post(url, formData.value)
      Taro.showToast({
        title: resp.message,
        icon: 'success',
        duration: 2000,
        mask: true,
      }).then()
      formData.value = {
        snowFlakeId: undefined,
        serviceProjectId: formData.value.serviceProjectId,
        securityUnitId: formData.value.securityUnitId,
        name: '',
        workPost: '',
        telephone: null,
        sex: 0,
        nativePlace: '',
        idCard: null,
        dateOfBirth: null,
        securityNumber: '',
        remark: '',
        homeAddress: '',
        noSecurityNumberDesc: '',
        photo: '',
        educationLevel: ''
      }
      educationLevelValue.value = ''
      uploadRef.value?.clearUploadQueue()
    }
  })
}

const reset = () => {
  formRef.value?.reset()
}
</script>
