<template>
  <div class="add-inst-wrap">
    <el-dialog
      v-model="state.isShowDialog"
      :title="title"
      width="90%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="state.form"
        label-width="100px"
        size="default"
        label-position="top"
        :rules="rules"
        closeable
      >
        <el-row>
          <el-col
            :span="24"
            class="mb24"
          >
            <el-form-item
              label="姓名"
              prop="userName"
            >
              <el-input
                :disabled="dialogType != 'add'"
                v-model="state.form.userName"
                @focus="openSelectUser"
                placeholder="请选择"
              ></el-input>
              <!-- <el-select
								:disabled="dialogType != 'add'"
								filterable
								style="width: 100%"
								v-model.number="state.form.curUser"
								@change="selectUser"
								value-key="userId"
								class="w100"
								placeholder="请选择"
								clearable
							>
								<el-option :label="v.userName" :value="v" :key="v.userId" v-for="v in userOptions" />
							</el-select> -->
            </el-form-item>
          </el-col>
          <el-col
            :span="24"
            class="mb10"
          >
            <el-form-item
              label="预约资格有效开始时间"
              prop="startTime"
            >
              <el-date-picker
                style="width: 100%"
                v-model="state.form.startTime"
                type="date"
                placeholder="选择预约资格有效开始时间"
                value-format="YYYY-MM-DD"
                clearable
                :disabledDate="disabledDateFn"
              />
            </el-form-item>
          </el-col>
          <el-col
            :span="24"
            class="mb10"
          >
            <el-form-item
              label="预约资格有效结束时间"
              prop="endTime"
            >
              <el-date-picker
                style="width: 100%"
                v-model="state.form.endTime"
                type="date"
                placeholder="选择预约资格有效结束时间"
                value-format="YYYY-MM-DD"
                clearable
                :disabledDate="disabledDateFn"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="上传资格证书"
              prop="fileList"
            >
              <el-upload
                :class="{ disUoloadSty: state.form.fileList.length > 0 }"
                v-model:file-list="state.form.fileList"
                :action="uploadUrl"
                :limit="1"
                style="width: 100%"
                accept=".jpg,.png"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :before-upload="beforeAvatarFileUpload"
                :on-remove="(res, uploadFile: UploadFile) => handleRemove()"
                :on-success="(res, uploadFile: UploadFile) => handleSuccess(res, uploadFile)"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            @click="onCancel"
            type="info"
            size="default"
          >
            取 消
          </el-button>
          <el-button
            type="primary"
            @click="subAdd"
            size="default"
          >
            提 交
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible">
      <img
        w-full
        :src="dialogImageUrl"
        alt="Preview Image"
      />
    </el-dialog>
    <SelectUser
      ref="selectUserRef"
      :multiple="false"
      @selectedUserData="selectedUserData"
    />
  </div>
</template>

<script setup lang="ts" name="addInstrument">
  import { reactive, ref, nextTick, defineAsyncComponent } from 'vue'
  import { ElMessage } from 'element-plus'
  import to from 'await-to-js'
  import type { UploadFile } from 'element-plus'
  import { useSystemApi } from '/@/api/instr/system'
  const systemApi = useSystemApi()
  import { useGrantApi } from '/@/api/instr/inst/grant'
  import { useGrantApplyApi } from '/@/api/instr/inst/grantApply'
  const grantApi = useGrantApi()
  const grantApplyApi = useGrantApplyApi()
  import { deepClone } from '/@/utils/other'
  import { storeToRefs } from 'pinia'
  import mittBus from '/@/utils/mitt'
  import { useUserInfo } from '/@/stores/userInfo'
  const SelectUser = defineAsyncComponent(() => import('/@/views/instr/component/selectUserByDept/index.vue'))
  // 向父组件传值/事件
  const emit = defineEmits(['refresh'])
  // 定义变量内容
  const selectUserRef = ref()
  const stores = useUserInfo()
  const { userInfos } = storeToRefs(stores)
  const uploadUrl = import.meta.env.VITE_UPLOAD
  const editFormRef = ref()
  const title = ref('')
  const dialogVisible = ref(false) //查看大图
  const dialogImageUrl = ref('') //查看大图
  const userOptions = ref<RowUserType[]>([]) //用户列表
  const dialogType = ref('') //编辑、新增
  const disabledDateFn = (time: any) => {
    // 获取当前日期的0点时间戳
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    // 如果传递进来的日期时间戳小于今天的0点时间戳，则禁止选择
    return time.getTime() < today.getTime()
  }
  const state = reactive({
    isShowDialog: false,
    form: {
      id: 0,
      userId: null,
      userName: '',
      instCode: '', //	仪器编码
      instId: 0, //仪器ID
      instName: '', //仪器名称
      date: null,
      startTime: '',
      endTime: '',
      curtName: '',
      curtFile: '',
      fileList: [],
      curUser: {},
    },
  })

  const rules = reactive({
    userId: [{ required: true, message: '人员不能为空', trigger: 'blur' }],
    startTime: [{ required: true, message: '预约资格有效开始时间不能为空', trigger: 'blur' }],
    endTime: [{ required: true, message: '预约资格有效结束时间不能为空', trigger: 'blur' }],
    // fileList: [{ required: true, message: '资格证书不能为空', trigger: 'blur' }],
  })

  const selectUser = (data) => {
    console.log(data)
    state.form.userId = data.userId
    state.form.userName = data.userName
  }

  // 打开弹窗
  const openDialog = (type: 'add' | 'edit', row) => {
    console.log(row)
    state.isShowDialog = true
    getDicts()
    nextTick(() => {
      editFormRef.value.clearValidate()
      editFormRef.value.resetFields()
      state.form.fileList = []
      state.form.date = null
      state.form.curUser = []
      dialogType.value = type
      if (type == 'edit') {
        getInstDetail(row.id)
        title.value = '编辑人员授权'
      } else if (type == 'add') {
        title.value = '新增人员授权'
        state.form.instCode = row.instCode
        state.form.instId = row.id
        state.form.instName = row.instName
      } else if (type == 'personal') {
        title.value = '申请预约资格授权'
        state.form.instCode = row.instCode
        state.form.instId = row.id
        state.form.instName = row.instName
        state.form.userId = userInfos.value.id
        state.form.userName = userInfos.value.nickName
        state.form.curUser = { userId: userInfos.value.id, userName: userInfos.value.nickName }
      }
    })
  }

  // 获取仪器详情
  const getInstDetail = async (id) => {
    const [err, res]: ToResponse = await to(grantApi.detail({ id }))
    if (err) return
    if (res?.code == 200) {
      console.log(res.data)
      state.form = res.data
      state.form.fileList = [{ name: res.data.curtName, url: res.data.curtFile }]
      state.form.curUser = { userId: res.data.userId, userName: res.data.userName }
      state.form.date = res.data.startTime ? [res.data.startTime, res.data.endTime] : null
    }
  }

  const getDicts = () => {
    Promise.all([systemApi.getUserList({ noPage: true })]).then(([user]) => {
      userOptions.value = user.data.list.map((item: any) => ({ userId: item.id, userName: item.nickName }))
    })
  }
  // 关闭弹窗
  const closeDialog = () => {
    // 清空表单，此项需加表单验证才能使用
    editFormRef.value.resetFields()
    state.form.fileList = []
    state.form.curtName = ''
    state.form.curtFile = ''
    state.form.userId = null
    state.isShowDialog = false
  }
  const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
  }
  const handleSuccess = (res: any, uploadFile: UploadFile) => {
    state.form.curtName = uploadFile.name
    state.form.curtFile = res?.Data || ''
  }
  const handleRemove = () => {
    state.form.fileList = []
    state.form.curtName = ''
    state.form.curtFile = ''
  }
  const beforeAvatarFileUpload = (file) => {
    let isLt10m = file.size / 1024 / 1024 / 20 < 1
    if (!isLt10m) {
      ElMessage.error('上传文件大小不能超过 20MB!')
      return false
    }
    return true
  }
  const openSelectUser = () => {
    const param = state.form.userId
      ? { checkedUser: [{ id: state.form.userId, name: state.form.userName }] }
      : undefined
    selectUserRef.value.openDialog(param)
  }
  const selectedUserData = (data) => {
    state.form.userId = data.user[0].id
    state.form.userName = data.user[0].name
  }
  // 取消
  const onCancel = () => {
    closeDialog()
  }

  // 创建
  const subAdd = () => {
    editFormRef.value.validate(async (valid: any, error: any) => {
      if (valid) {
        let params = deepClone(state.form)
        let post = grantApi.add
        if (dialogType.value == 'edit') {
          post = grantApi.update
        } else if (dialogType.value == 'add') {
          post = grantApi.add
        } else if (dialogType.value == 'personal') {
          post = grantApplyApi.add
        }
        const [err, res]: ToResponse = await to(post({ ...params }))
        if (err) return
        if (res?.code == 200) {
          ElMessage.success('提交成功')
          closeDialog()
          mittBus.emit('refresAuthOrApplicationList', 'myAuth')
          mittBus.emit('refresAuthOrApplicationList', 'auth')
          emit('refresh')
        }
      } else {
        Object.keys(error).forEach((key, i) => {
          if (i == 0) {
            const firstFiled = error[key][0].field
            editFormRef.value.scrollToField(firstFiled)
          }
        })
      }
    })
  }
  // 暴露方法
  defineExpose({
    openDialog,
  })
</script>

<style scoped lang="scss">
  .add-inst-wrap {
    // :deep(.el-dialog) {
    // 	border-radius: 8px;
    // }
    :deep(.el-dialog__header) {
      border-radius: 8px 8px 0 0;
      margin: 0;
      font-size: 16px;
      font-weight: bold;
      color: #333333;
      padding: 12px 0 12px 22px;
    }
    :deep(.el-dialog__headerbtn) {
      top: 0;
    }
    .add-inst-content {
      .r-form {
        padding: 10px 0 0 5px;
        .w100 {
          width: 100%;
        }
        .upload-box {
          :deep(.el-form-item__content) {
            justify-content: center;
          }
          :deep(.el-form-item__error) {
            width: 100%;
            text-align: center;
            margin-top: 40px;
          }
          .upload-btn {
            width: 200px;
            height: 200px;
            border-radius: 4px;
            border: 1px solid #cdcdcd;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            > p {
              font-size: 14px;
              color: #969696;
              margin-top: 30px;
            }
          }
        }
        .file-size-tips {
          text-align: center;
          margin-top: 8px;
          font-size: 16px;
          color: #969696;
        }
        .form-group {
          // padding: 15px 0 0 15px;
          .form-item-tit {
            font-size: 14px;
            font-weight: bold;
            color: #333333;
            position: relative;
            .form-item-icon {
              position: absolute;
              top: -2px;
              left: -5px;
              width: 12px;
              height: 12px;
              background: linear-gradient(138deg, #4e82ff 0%, #2c46ff 100%);
              opacity: 0.3;
              border-radius: 50%;
            }
          }
          .form-row-wrap {
            // padding-left: 27px;
          }
        }
        :deep(.el-form-item__label) {
          font-size: 14px;
          // font-weight: bold;
          color: #343a3f;
        }
        .report-link {
          background: #eef3fe;
          border-radius: 12px;
          padding: 0 12px;
          line-height: 24px;
        }
      }
      :deep(.el-input-number) {
        width: 90px;
      }
      .add-btn {
        width: 113px;
        height: 32px;
        color: #2c78ff;
      }
    }
    .algin-center {
      align-items: center;
    }
  }
  .disUoloadSty {
    :deep(.el-upload--picture-card) {
      display: none; /* 上传按钮隐藏 */
    }
  }
</style>
