<!-- 新增或详情弹窗 -->
<script lang="ts" setup name="addNotice">
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { deptType } from '../file-interface'
import { getUserList } from '@/api/system/user'
import useUserStore from '@/store/modules/user'
import { getDeptTreeList } from '@/api/system/dept'
import { UploadFile, addApi } from '@/api/measure/file'
import type { userType } from '@/views/system/user/user-interface'
const emits = defineEmits(['resetData'])
const ruleFormRef = ref<FormInstance>() // from组件
const userInfo = useUserStore() // 当前用户信息
const ruleForm = reactive({
  fileType: '', // 类型
  fileTypeName: '', // 类型名称  不传
  fileName: '', // 名称
  fileNo: '', // 编号  不传
  fileCode: '', // 文件号
  minioFileName: '', // 上传文件返回名称
  publishTime: '', // 发布时间
  publisher: '', // 发布单位
  remark: '', // 备注
  effectiveTime: '', // 实施时间
  effectiveStatus: '', // 实施状态
  effectiveStatusName: '', // 实时状态名字  不传
  createUser: '', // 创建人
  createUserId: '', // 创建人id
  id: '',
}) // 表单
const fileTypeName = ref('')
const effectiveStatusName = ref('')
const title = ref('')
const rules = ref<FormRules>({
  fileName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  publishTime: [{ required: true, message: '创建不能为空', trigger: 'blur' }],
  publisher: [{ required: true, message: '发布单位不能为空', trigger: 'blur' }],
  minioFileName: [{ required: true, message: '上传文件不能为空', trigger: 'blur' }],
  effectiveTime: [{ required: true, message: '实施时间不能为空', trigger: 'blur' }],
  createUserId: [{ required: true, message: '发布人不能为空', trigger: 'blur' }],
  fileCode: [{ required: true, message: '文件号不能为空', trigger: 'blur' }],
}) // 表单验证规则

const dialogVisible = ref<boolean>(false) // 弹窗显示
const userList = ref<userType[]>([]) // 可使用人列表
const getuser = () => {
  getUserList({ offset: 1, limit: 99999 }).then((res) => {
    userList.value = res.data.rows
  })
} // 获取创建人列表
const PubList = ref<deptType[]>([])
// 获取发布单位列表
const getPubList = () => {
  getDeptTreeList().then((res) => {
    PubList.value = res.data
  })
}
// 弹窗初始化
const initDialog = (row: any) => {
  console.log(row)
  ruleForm.fileType = row.fileType
  fileTypeName.value = row.fileTypeName
  dialogVisible.value = true
  getuser()
  if (row.title === '新增') {
    getuser()
    getPubList()
    // 默认发布人和发布单位
    ruleForm.createUserId = userInfo.$state.id
    ruleForm.publisher = userInfo.$state.deptId
  }
}
defineExpose({ initDialog, dialogVisible })
// 关闭弹窗
const close = () => {
  dialogVisible.value = false
  emits('resetData')
}
// 提交
const submitForm = async (formEl: FormInstance | undefined, flag: string) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
    `确认${flag}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
      ).then((res) => {
        if (flag == '提交') {
          addApi(ruleForm).then((res) => {
            if (res.code == 200) {
              formEl?.resetFields()
              dialogVisible.value = false
              ElMessage.success('提交成功')
              emits('resetData')
            }
          })
        }
        else {
          // 保存
          // 暂时未写
          ElMessage.success('保存成功')
        }
      })
    }
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  dialogVisible.value = false
  emits('resetData')
}
const fileList = ref<UploadUserFile[]>([])

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning('只能上传一个文件')
}
// 移除时触发
const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `确认移除${uploadFile.name}文件吗 ?`,
  ).then(
    () => true,
    () => false,
  )
}
// 上传请求
const uploadQuarterlyEvaluateFile = (file: File) => {
  UploadFile(file).then((res) => {
    if (res.code === 200) {
      ruleForm.minioFileName = res.data.fileName
      // fileList.value.push({
      //   name: res.data.fileName,
      //   url: res.data.fileId,
      //   // type: file.file.type,
      // })
      // 重置当前验证
      ruleFormRef.value?.validateField('minioFileName')
      ElMessage.success('文件上传成功')
    }
  })
}
// 实施状态判断
// const statusList = ref([
//   { name: '在使用', id: '1595030082091040769', value: '1' },
//   { name: '未使用', id: '1595030082544025602', value: '2' },
//   { name: '已废止', id: '1595030083114450945', value: '3' },
// ])
watch(() => ruleForm.effectiveTime, (newVal) => {
  const diffDat = dayjs(newVal).diff(dayjs().format('YYYY-MM-DD HH:mm:ss'), 'day')
  if (diffDat < 0) {
    effectiveStatusName.value = '已废止'
    ruleForm.effectiveStatus = '3'
  }
  else if (diffDat == 0) {
    effectiveStatusName.value = '在使用'
    ruleForm.effectiveStatus = '1'
  }
  else {
    effectiveStatusName.value = '未使用'
    ruleForm.effectiveStatus = '2'
  }
})
</script>

<template>
  <el-dialog v-if="dialogVisible" v-model="dialogVisible" :title="title" width="80%" append-to-body @close="resetForm">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="right" label-width="110px">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="系统编号" prop="fileNo">
            <el-input v-model.trim="ruleForm.fileNo" placeholder="系统编号" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="名称" prop="fileName">
            <el-input v-model.trim="ruleForm.fileName" placeholder="名称" :disabled="title === '详情'" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="文件号" prop="fileCode">
            <el-input v-model.trim="ruleForm.fileCode" placeholder="文件号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="类别">
            <span>{{ fileTypeName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="发布单位" prop="publisher">
            <el-select v-model="ruleForm.publisher" placeholder="请选择发布单位" :disabled="title === '详情'">
              <el-option v-for="item in PubList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="实施时间" prop="effectiveTime">
            <el-date-picker
              v-model="ruleForm.effectiveTime" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择实施时间"
              class="normal-date"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="实施状态">
            {{ effectiveStatusName }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="创建时间" prop="publishTime">
            <el-date-picker
              v-model="ruleForm.publishTime" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择创建时间"
              class="normal-date"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建人" prop="createUserId">
            <el-select v-model="ruleForm.createUserId" placeholder="请选择创建人" :disabled="title === '详情'">
              <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model.trim="ruleForm.remark" placeholder="请输入备注" :disabled="title === '详情'" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="附件" prop="minioFileName">
            <el-upload
              v-model:file-list="fileList"
              enctype="multipart/form-data"
              :http-request="uploadQuarterlyEvaluateFile"
              :before-remove="beforeRemove"
              :on-exceed="handleExceed"
              :limit="1"
            >
              <el-button type="primary">
                上传
              </el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24" class="btn-container">
          <span class="btns">
            <el-button type="primary" @click="submitForm(ruleFormRef, '提交')">
              提交
            </el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef, '保存')">
              保存
            </el-button>
            <el-button type="info" @click="resetForm(ruleFormRef)">
              关闭
            </el-button>
          </span>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<style lang="scss" scoped>
.btn-container {
  position: relative;

  .btns {
    position: relative;
    left: 50%;
    top: 0;
    margin-left: -108px;
  }
}
</style>
