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

const userList = ref<userType[]>([]) // 可使用人列表
const getuser = () => {
  getUserList({ offset: 1, limit: 99999 }).then((res) => {
    userList.value = res.data.rows
  })
} // 获取创建人列表
const PubList = ref<deptType[]>([])
const PubListTree = ref([])
// 获取发布单位列表
const getPubList = () => {
  getDeptTreeList().then((res) => {
    PubList.value = res.data
    PubListTree.value = toTreeList(res.data, '0', true)
  })
}
const formDataRow = ref() // 父组件传来的row
// 弹窗初始化
const initDialog = (row: any) => {
  ruleFormRef.value?.resetFields()
  ruleForm.fileType = row.fileType
  fileTypeName.value = row.fileTypeName
  title.value = row.title
  fileList.value = []
  formDataRow.value = row
  getuser()
  getuser()
  getPubList()
  if (row.title === '新建') {
    // 默认发布人和发布单位
    ruleForm.createUserId = userInfo.$state.id
    ruleForm.publisher = userInfo.$state.deptId
    ruleForm.publishTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  }
  else if (row.title === '详情') {
    ruleForm.createUserId = row.createUserId
    ruleForm.fileNo = row.fileNo
    ruleForm.fileName = row.fileName
    ruleForm.fileCode = row.fileCode
    fileTypeName.value = row.fileTypeName
    ruleForm.publisher = row.publisher
    ruleForm.effectiveTime = row.effectiveTime
    effectiveStatusName.value = row.effectiveStatusName
    ruleForm.remark = row.remark
    ruleForm.publishTime = row.publishTime
    ruleForm.minioFileName = row.minioFileName
    approvalStatusName.value = row.approvalStatusName
  }
}
onMounted(() => {
  initDialog($route.query)
})
// 关闭弹窗
const close = () => {
  ruleForm.fileType = ''
  ruleForm.fileName = ''
  ruleForm.fileCode = ''
  ruleForm.minioFileName = ''
  ruleForm.publishTime = ''
  ruleForm.remark = ''
  ruleForm.publishTime = ''
  ruleForm.effectiveTime = ''
  ruleForm.effectiveStatus = ''
  ruleForm.publishTime = ''
  ruleForm.createUserId = ''
  effectiveStatusName.value = ''
}
// 提交
const submitForm = () => {
  ElMessageBox.confirm(
    '确认提交吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then((res) => {
    console.log('提交')
  })
}
// 编辑
const update = (row) => {
  // $router.push({
  //   name: 'approveDetail',
  //   query: {
  //     ...row,
  //     title: '编辑',
  //   },
  // })
  initDialog({
    ...row,
    title: '编辑',
  })
}
// 删除
const remove = (row) => {
  ElMessageBox.confirm(
    '确认删除吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      console.log('确认删除')
    })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  close()
  $router.go(-1)
}
// 审批结束回调
const approvalSuccess = () => {
  close()
  $router.go(-1)
}
const approvalDialog = ref()
// 审批操作
const approval = (type: string, taskId: string) => {
  approvalDialog.value.initDialog(type, taskId)
}
// 打印
const print = () => {
  printHtml('print')
}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        ruleForm.minioFileName = res.data[0]
        // 重置当前验证
        ruleFormRef.value?.clearValidate('minioFileName')
        ElMessage.success('文件上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
// 实施状态判断
// const statusList = ref([
//   { name: '在使用', id: '1595030082091040769', value: '1' },
//   { name: '未使用', id: '1595030082544025602', value: '2' },
//   { name: '已废止', id: '1595030083114450945', value: '3' },
// ])
watch(() => ruleForm.effectiveTime, (newVal) => {
  if (title.value !== '详情') {
    const diffDat = dayjs(newVal).diff(dayjs().format('YYYY-MM-DD HH:mm:ss'), 'hour')
    if (diffDat < 0) {
    // ruleForm.effectiveStatusName = '已废止'
      effectiveStatusName.value = '在使用'
      ruleForm.effectiveStatus = '1'
    }
    else if (diffDat == 0) {
    // ruleForm.effectiveStatusName = '在使用'
      effectiveStatusName.value = '在使用'
      ruleForm.effectiveStatus = '1'
    }
    else {
    // ruleForm.effectiveStatusName = '未使用'
      effectiveStatusName.value = '未使用'
      ruleForm.effectiveStatus = '2'
    }
  }
})
</script>

<template>
  <app-container style="overflow: hidden;">
    <detail-page :title="`文件审批-${title}`">
      <template #btns>
        <div v-if="approvalStatusName === '草稿箱' || approvalStatusName === '已取消'">
          <el-button type="primary" @click="submitForm">
            提交
          </el-button>
          <el-button v-if="title !== '编辑'" type="primary" @click="update(formDataRow)">
            编辑
          </el-button>
          <el-button type="primary" @click="remove(formDataRow)">
            删除
          </el-button>
          <el-button type="info" @click="resetForm(ruleFormRef)">
            关闭
          </el-button>
        </div>
        <div v-if="approvalStatusName === '待审批' || approvalStatusName === '审批中'">
          <el-button type="primary" @click="approval('agree', formDataRow.taskId)">
            同意
          </el-button>
          <el-button type="primary" @click="approval('reject', formDataRow.taskId)">
            驳回
          </el-button>
          <el-button type="primary" @click="approval('refuse', formDataRow.taskId)">
            拒绝
          </el-button>
          <el-button type="info" @click="resetForm(ruleFormRef)">
            关闭
          </el-button>
        </div>
        <div v-if="approvalStatusName === '已通过' || approvalStatusName === '未通过'">
          <el-button type="primary" @click="print">
            打印
          </el-button>
          <el-button type="info" @click="resetForm(ruleFormRef)">
            关闭
          </el-button>
        </div>
      </template>

      <el-form id="print" ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="right" label-width="110px" class="form" :class="[title === '详情' ? 'isDetail' : '']">
        <el-row :gutter="24" class="marg">
          <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="文件号" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="类别">
              <el-input v-model.trim="fileTypeName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="发布单位" prop="publisher">
              <dept-select v-model="ruleForm.publisher" :data="PubListTree" :placeholder="title === '详情' ? ' ' : '请选择发布单位'" :disabled="title === '详情'" style="width: 100%;" />
            </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" :disabled="title === '详情'"
                placeholder="请选择实施时间"
                class="normal-date"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实施状态">
              <el-input v-model.trim="effectiveStatusName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="创建时间" prop="publishTime">
              <el-date-picker
                v-model="ruleForm.publishTime" type="date" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" :disabled="title === '详情'"
                placeholder="请选择创建时间"
                class="normal-date"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建人" prop="createUserId">
              <el-select v-model="ruleForm.createUserId" placeholder="请选择创建人" :disabled="title === '详情'" style="width: 100%;">
                <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" class="marg">
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-if="title === '详情'" v-model.trim="ruleForm.remark" :disabled="title === '详情'" />
              <el-input v-else v-model.trim="ruleForm.remark" placeholder="请输入备注" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="附件" prop="minioFileName">
              <show-photo :minio-file-name="ruleForm.minioFileName" />
              <input v-show="title === ''" ref="fileRef" type="file" @change="onFileChange">
              <el-button v-if="title !== '详情'" type="primary" :disabled="title === '详情'" :style="{ 'margin-left': ruleForm.minioFileName === '' ? '0px' : '20px' }" @click="upload">
                {{ ruleForm.minioFileName === '' ? '上传' : '更换附件' }}
              </el-button>
              <!-- <el-upload
                v-else
                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-form>
    </detail-page>
    <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
  </app-container>
</template>

<style lang="scss" scoped>
.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>
