<!-- 新增通知公告弹窗 -->
<script lang="ts" setup name="addNotice">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import type { signType } from '../tool_interface'
import showPhoto from '../showPhoto.vue'
import { getUserList } from '@/api/system/user'
import { uploadApi } from '@/api/system/notice'
import { addApi, getPhotoUrl, listPageDetailApi, updateApi } from '@/api/system/tool'
import type { userType } from '@/views/system/user/user-interface'
const emits = defineEmits(['resetData'])
const ruleFormRef = ref<FormInstance>() // from组件
const ruleForm = reactive<signType>({
  userIdList: [], // 可使用人列表
  signType: '', // 类型
  signName: '', // 名称
  signDirector: '', // 负责人
  minioFileName: '', // 上传文件名
  signDesc: '', // 描述
  signNo: '',
  createTime: '',
  id: '0',
}) // 表单
const title = ref('')
const rules = ref<FormRules>({
  userIdList: [{ required: true, message: '可使用人列表不能为空', trigger: 'blur' }],
  signName: [{ required: true, message: '签章名称不能为空', trigger: 'blur' }],
  signDirector: [{ required: true, message: '签章负责人不能为空', trigger: 'blur' }],
  minioFileName: [{ 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 initDialog = (row: signType) => {
  title.value = row.title as string
  console.log(title.value, 'title')
  ruleForm.signNo = ''
  ruleForm.signName = ''
  ruleForm.createTime = ''
  ruleForm.signDesc = ''
  ruleForm.minioFileName = ''
  ruleForm.userIdList = []
  ruleForm.signDirector = ''
  dialogVisible.value = true
  // ruleForm.noticePublisher = userInfo.$state.name
  // ruleForm.noticeCompany = userInfo.$state.deptName
  // ruleForm.noticeTime = dayjs().format('YYYY-MM-DD')
  if (row.title === '新增') {
    // 新增
    ruleFormRef.value?.resetFields()
    ruleForm.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  }
  else if (row.title === '编辑') {
    ruleForm.signNo = row.signNo
    ruleForm.signName = row.signName
    // ruleForm.createTime = row.createTime
    ruleForm.signDesc = row.signDesc
    ruleForm.minioFileName = row.minioFileName
    ruleForm.userIdList = row.userIdList
    ruleForm.signDirector = row.signDirector
    ruleForm.id = row.id
    ruleForm.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    // 获取详情列表
    listPageDetailApi({ ...row }).then((res) => {
      ruleForm.id = res.data.id
      res.data.userList.forEach((element: userType) => {
        ruleForm.userIdList?.push(element.id)
      })
    })
    // 修改
  }
  else {
    // 详情
    ruleForm.signNo = row.signNo
    ruleForm.signName = row.signName
    ruleForm.createTime = row.createTime
    ruleForm.signDesc = row.signDesc
    ruleForm.minioFileName = row.minioFileName
    ruleForm.userIdList = row.userIdList
    ruleForm.signDirector = row.signDirector
    // 获取详情列表
    listPageDetailApi({ ...row }).then((res) => {
      // ruleForm.id = res.data.id
      res.data.userList.forEach((element: userType) => {
        ruleForm.userIdList?.push(element.id)
      })
    })
  }
  ruleForm.signType = row.signType
  getuser()
}
defineExpose({ initDialog })
// 关闭弹窗
const close = () => {
  dialogVisible.value = false
  emits('resetData')
}
// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (title.value === '新增') {
        addApi(ruleForm).then((res) => {
          if (res.code === 200) {
            ElMessage.success('新增成功')
            close()
          }
        })
      }
      else {
        updateApi(ruleForm).then((res) => {
          if (res.code === 200) {
            ElMessage.success('更新成功')
            close()
          }
        })
      }
    }
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  dialogVisible.value = false
  emits('resetData')
}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  console.log()
  // 原生上传
  // 创建formdata对象
  const fd = new FormData()
  fd.append('multipartFile', event.target.files[0])
  uploadApi(fd).then((res) => {
    if (res.code === 200) {
      ruleFormRef.value?.clearValidate('minioFileName')
      ruleForm.minioFileName = res.data[0]
      ElMessage.success('上传成功')
    }
    else {
      ElMessage.error(res.message)
    }
  })
}
const upload = () => {
  fileRef.value.click()
}
</script>

<template>
  <el-dialog v-if="dialogVisible" v-model="dialogVisible" :title="title" width="50%" append-to-body class="container" @close="resetForm">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="right" label-width="110px" :class="[title === '详情' ? 'isDetail' : 'xxx']">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="签章编号" prop="signNo">
            <el-input v-model.trim="ruleForm.signNo" placeholder="系统自动生成" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签章名称" prop="signName">
            <el-input v-model.trim="ruleForm.signName" placeholder="签章名称" :disabled="title === '详情'" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="创建时间" prop="noticeCompany">
            <el-input v-model.trim="ruleForm.createTime" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签章负责人" prop="signDirector">
            <el-input v-model.trim="ruleForm.signDirector" placeholder="签章负责人" :disabled="title === '详情'" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="签章描述" prop="signDesc">
        <el-input v-model.trim="ruleForm.signDesc" placeholder="签章描述" :disabled="title === '详情'" />
      </el-form-item>
      <el-form-item label="可使用人" prop="userIdList">
        <el-select v-model="ruleForm.userIdList" :placeholder="title === '详情' ? '暂无可使用人' : '请选择可使用人'" multiple :disabled="title === '详情'">
          <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="发布内容" prop="noticeContent">
        <el-input v-model.trim="ruleForm.noticeContent" :rows="4" type="textarea" />
      </el-form-item> -->
      <el-form-item label="签章图片" prop="minioFileName">
        <show-photo :minio-file-name="ruleForm.minioFileName" />
        <el-button v-if="title !== '详情'" type="primary" :disabled="title === '详情'" :style="{ 'margin-left': ruleForm.minioFileName === '' ? '0px' : '20px', 'margin-top': ruleForm.minioFileName === '' ? '0px' : '56px' }" @click="upload">
          {{ ruleForm.minioFileName === '' ? '上传' : '更换图片' }}
        </el-button>
        <input v-show="title === ''" ref="fileRef" type="file" accept="image/*" @change="onFileChange">
      </el-form-item>
      <el-form-item>
        <el-button v-if="title !== '详情'" type="primary" @click="submitForm(ruleFormRef)">
          发布
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">
          关闭
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style lang="scss" scoped>
.container {
  .isDetail {
    ::v-deep {
      .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
      .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
        display: none;
      }
    }
  }
}
</style>
