<!-- 新增或详情弹窗 -->
<script lang="ts" setup>
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { deptType } from '../../file-interface'
import type { TableRow } from './approve-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, approvalDelete, confirmDrafts, deleteApi, submitFile, updateDrafts, updateFail } 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'
import { cancelApproval, fetchApproval } from '@/api/approval'

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()
  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 === '详情' || row.title === '编辑') {
    ruleForm.createUserId = row.createUserId
    ruleForm.fileNo = row.fileNo
    ruleForm.id = row.id
    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 // 审批状态名称
    if (approvalStatusName.value !== '草稿箱') {
      getApprovalRecord($route.query.processId as string) // 查询审批记录
    }
  }
}

// 关闭弹窗
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 = ''
  $router.back()
}
// 保存
const saveForm = () => {
  ElMessageBox.confirm(
    '确认保存吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then((res) => {
    if (title.value === '新建') {
      confirmDrafts(ruleForm).then((res) => {
        if (res.code === 200) {
          console.log(res.data, '保存成功')
          submitFile({ id: res.data.id, formId: SCHEDULE.FILE_APPROVAL }).then((res) => {
            ElMessage.success('提交成功')
            close()
          })
        }
      })
    }
    else if (title.value === '编辑') {
      if (approvalStatusName.value === '未通过-驳回') {
        const params = {
          ...ruleForm,
          processId: $route.query.processId,
        }
        updateFail(params).then((res) => {
          ElMessage.success('保存成功')
          close()
        })
      }
      else { // 草稿箱、已取消
        // 保存（草稿箱）
        updateDrafts(ruleForm).then((res) => {
          ElMessage.success('保存成功')
          close()
        })
      }
    }
  })
}

// -----------------------------------------审批--------------------------------------
const approvalDialog = ref()
const approvalRecordData = ref([]) // 审批流程数据
// 查询审批记录
function getApprovalRecord(processId: string) {
  if (title.value !== '新建') {
    if (processId) {
      fetchApproval(processId).then((res) => {
        approvalRecordData.value = res.data
      })
    }
    else {
      ElMessage.warning('流程实例id为空')
    }
  }
}
// 审批结束回调
const approvalSuccess = () => {
  close()
}
// 审批
const handleApprove = (val: string, title = '') => {
  if (val === '取消') {
    const params = {
      processInstanceId: $route.query.processId! as string,
      comments: '',
    }
    ElMessageBox.confirm(
      '确认取消该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        cancelApproval(params).then((res) => {
          ElMessage({
            type: 'success',
            message: '取消成功',
          })
          close()
        })
      })
  }
  else if (val === '同意') {
    approvalDialog.value.initDialog('agree', $route.query.taskId)
  }
  else if (val === '驳回') {
    approvalDialog.value.initDialog('reject', $route.query.taskId)
  }
  else if (val === '拒绝') {
    approvalDialog.value.initDialog('refuse', $route.query.taskId)
  }
}
// -----------------------------------------------------------------------------------

const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    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('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
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'
    }
  }
})

onMounted(() => {
  initDialog($route.query)
})
</script>

<template>
  <app-container>
    <detail-page :title="`文件审批-${title}`">
      <template #btns>
        <el-button v-if="title === '详情' && approvalStatusName === '待审批'" type="primary" @click="handleApprove('同意')">
          同意
        </el-button>
        <el-button v-if="title === '详情' && approvalStatusName === '待审批' && $route.query.decisionItem !== '3'" type="primary" @click="handleApprove('驳回')">
          驳回
        </el-button>
        <el-button v-if="title === '详情' && approvalStatusName === '待审批' && $route.query.decisionItem !== '2'" type="danger" @click="handleApprove('拒绝')">
          拒绝
        </el-button>
        <el-button v-if="title === '详情' && approvalStatusName === '审批中'" type="info" @click="handleApprove('取消')">
          取消
        </el-button>
        <el-button v-if="title === '新建' || title === '编辑'" type="primary" @click="saveForm">
          保存
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </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"
                placeholder="请选择创建时间"
                class="normal-date"
                style="width: 100%;"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建人" prop="createUserId">
              <el-select v-model="ruleForm.createUserId" placeholder="请选择创建人" disabled 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>
    <detail-block v-if="approvalStatusName !== '草稿箱' && title !== '新建'" title="审批流程">
      <!-- 审批流程 -->
      <approval-record ref="approvalRecord" :approval-record-data="approvalRecordData" />
    </detail-block>
    <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>
