<!-- 设备保养验收单详情 -->
<script lang="ts" setup name="ListApprovalAdd">
import { ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadProps, UploadUserFile } from 'element-plus'
import dayjs from 'dayjs'
import type { IColumnsType, IlistApprovalAddTypes, dictType } from '../checkList_interface'
import checkList from './checkList.vue'
import { acceptanceCheckInfo, addAcceptanceCheck, equipmentApplyInfo, failUpdateAcceptanceCheckInfo, submitAcceptanceCheck, updateAcceptanceCheckInfo } from '@/api/device/checkList'
import { UploadFile } from '@/api/measure/file'
import { cancelApproval, fetchApproval, submitApproval } from '@/api/approval'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { getDictByCode } from '@/api/system/dict'
import { SCHEDULE } from '@/utils/scheduleDict'
import useUserStore from '@/store/modules/user'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
const approvalDialog = ref() // 审批对话ref
const infoId = ref('') // id
const approvalStatusName = ref('') // 审批状态名称
const processId = ref('') // 流程审批实例id
const decisionItem = ref('') // 同意、驳回、拒绝按钮权限
const taskId = ref('') // 任务id，用于同意、驳回、拒绝审批
const pageType = ref('add') // 页面类型: add,edit, detail
const user = useUserStore() // 用户信息
const textMap: { [key: string]: string } = {
  add: '新建',
  edit: '编辑',
  detail: '详情',
}// 字典
// 从路由中获取页面类型参数
const $route = useRoute()

// ------------------------------------------- 路由参数 ----------------------------------
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
  if ($route.params.approvalStatusName) {
    approvalStatusName.value = $route.params.approvalStatusName as string
  }
}
const ruleFormRef = ref<FormInstance>()
// 表单-包括表格数据
const formInline = ref<IlistApprovalAddTypes>({
  acceptanceCheckId: '', // 检修申请id
  applyDesc: '', // 申请说明
  applyName: '', // 申请名称
  applyNo: '', // 申请编号
  applyPerson: '', // 申请人
  applyPersonName: '', // 申请人姓名
  applyType: '9', // 申请类型-字典code
  applyTypeName: '', // 申请类型名称
  applyUnit: '', // 申请单位
  applyUnitName: '', // 申请单位名称
  approvalStatus: '', // 审批状态-字典code
  approvalStatusName: '', // 审批状态名称
  createTime: '', // 创建时间
  createUser: '', // 创建人
  equipmentInfoList: [], // 设备详细列表
  equipmentList: [], // 	设备列表
  fileList: [
    {
      applyId: '', // 申请id
      createTime: '', // 创建时间
      createUser: '', // 创建人
      fileName: '', // 文件名
      id: '', // 主键
      isDel: '', // 删除id
      minioFileName: '', // minio存储文件名
      remark: '', // 备注
      updateTime: '',
    }, // 更新时间
  ], // 附件列表
  id: '', // 主键
  isDel: '', // 删除标记
  overhaulPerson: '', // 检修保养人（设备检修保养验收申请）
  processId: '', // 流程实例ID
  processResult: '', // 处理结果（设备领用、借用处理结果）
  remark: '', // 备注
  taskId: '', // 任务id（同意、驳回等操作使用）
  checkDate: new Date(), // 检修日期
  time: '', // 需要传的参数，检修日期
  updateTime: '', // 更新时间
  version: '', // 版本号
})

// 获取到检修申请列表数据
const checkIdObject = ref({
  applyName: '',
  applyPersonName: '',
  checkDate: '',
  applyNo: '',
})

// 设备检修列表
const columns = ref<IColumnsType[]>([
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
    required: false,
  },
  {
    text: '设备编号',
    value: 'equipmentNo',
    align: 'center',
    width: '160',
    required: false,
  },
  {
    text: '检修结果',
    value: 'overhaulResult',
    align: 'center',
    required: true,
  },
  {
    text: '检修意见',
    value: 'overhaulIdea',
    width: '450px',
    align: 'center',
    required: true,
  },
])
const checkListRef = ref()
// 点击选择检修申请编号
const selectPerson = () => {
  checkListRef.value.initDialog()
}

// ------------------------------------------ 字典 --------------------------------------
// 检修结果下拉框
const options = ref<dictType[]>([])
// 获取检修结果
getDictByCode('maintenanceResults').then((response) => {
  options.value = response.data
})
// --------------------------------------------------------------------------------------
// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
// 表单验证规则
const rules = ref({
  applyName: [{ required: true, message: '验收单名称不能为空', trigger: ['blur', 'change'] }],
  acceptanceCheckId: [{ required: true, message: '检修申请编号不能为空', trigger: ['blur', 'change'] }],
  overhaulPerson: [{ required: true, message: '检修保养人不能为空', trigger: ['blur', 'change'] }],
  checkDate: [{ required: true, message: '检修日期不能为空', trigger: ['blur', 'change'] }],
})

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])
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        formInline.value.fileList[0].minioFileName = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}

// 获取详情信息
const getInfo = () => {
  acceptanceCheckInfo({ id: infoId.value }).then((res) => {
    // Object.keys(res.data).map((item) => {
    //   if (typeof (res.data[item]) === 'number') {
    //     res.data[item] = res.data[item].toString()
    //   }
    // })
    checkIdObject.value.applyNo = res.data.checkApplyNo // 申请编号
    checkIdObject.value.applyName = res.data.checkApplyName // 申请名称
    formInline.value = res.data
    formInline.value.equipmentList = res.data.checkList
    formInline.value.applyType = '9'
    formInline.value.applyUnit = res.data.deptId || user.deptId // 申请单位
    formInline.value.applyUnitName = res.data.deptName || user.deptName // 申请单位名称
  })
}

const fileRef = ref() // 文件上传input

// 点击上传文件按钮
const upload = () => {
  fileRef.value.click()
}

// 检查表格第几行信息未完善
const checkEquipmentList = () => {
  const index = formInline.value.equipmentList.findIndex((item: any) => !item.overhaulResult || !item.overhaulIdea)
  if (index !== -1) {
    return index + 1
  }
  else {
    return 'pass'
  }
}
// 保存后的id
const addId = ref('')
// 保存
const save = async (formEl: FormInstance | undefined) => {
  // 检查表格是否存在增加行信息没有完善的情况
  const result = checkEquipmentList()
  if (result !== 'pass') {
    ElMessage.warning(`表格第${result}行信息未完善`)
    return
  }
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        formInline.value.time = formInline.value.checkDate as string
        if (pageType.value === 'add') { // 新建
          addAcceptanceCheck(formInline.value).then((res) => {
            if (res.code === 200) {
              ElMessage.success('保存成功')
              addId.value = res.data
            }
          })
        }
        else if (pageType.value === 'edit') { // 编辑
          if (approvalStatusName.value === '未通过-驳回') {
            failUpdateAcceptanceCheckInfo(formInline.value).then((res) => {
              if (res.code === 200) {
                ElMessage.success('保存成功')
                close()
              }
            })
          }
          else { // 草稿箱和已取消
            updateAcceptanceCheckInfo(formInline.value).then((res) => {
              if (res.code === 200) {
                ElMessage.success('保存成功')
                close()
              }
            })
          }
        }
      })
    }
  })
}

// 点击提交
const submit = () => {
  if (addId.value === '') {
    ElMessage.warning('请先保存')
  }
  else {
    submitAcceptanceCheck({ id: addId.value, formId: SCHEDULE.DEVICE_FIX_ACCEPTANCE, processId: processId.value }).then((res) => {
      if (res.code === 200) {
        close()
      }
    })
  }
}

// 选择完设备检修列表
const confirmCheckList = (object: any) => {
  formInline.value.acceptanceCheckId = object.id
  checkIdObject.value = object
  // 获取到详情
  equipmentApplyInfo({ id: object.id }).then((res) => {
    if (res.data.equipmentInfoList.length) {
      formInline.value.equipmentList = res.data.equipmentInfoList.map((item: any) => {
        return {
          ...item,
          equipmentId: item.id,
        }
      })
    }
  })
}
// ---------------------------------------------审批-------------------------------------
const approvalRecordData = ref([]) // 审批流程数据
// 查询审批记录
function getApprovalRecord(processId: string) {
  if (pageType.value !== 'add' && approvalStatusName.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: processId.value!,
      comments: '',
    }
    ElMessageBox.confirm(
      '确认取消该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        cancelApproval(params).then((res) => {
          ElMessage({
            type: 'success',
            message: '取消成功',
          })
          close()
        })
      })
  }
  else if (val === '同意') {
    approvalDialog.value.initDialog('agree', taskId.value)
  }
  else if (val === '驳回') {
    approvalDialog.value.initDialog('reject', taskId.value)
  }
  else if (val === '拒绝') {
    approvalDialog.value.initDialog('refuse', taskId.value)
  }
}
// --------------------------------------------------------------------------------------
onMounted(async () => {
  formInline.value.processId = $route.params.processId as string // 任务id
  formInline.value.applyUnit = user.deptId // 申请单位
  formInline.value.applyUnitName = user.deptName // 申请单位名称
  formInline.value.overhaulPerson = user.name
  formInline.value.applyPerson = user.id// 申请人
  formInline.value.applyPersonName = user.name// 申请人姓名
  formInline.value.applyName = '设备检修保养验收单'
  processId.value = $route.query.processId as string // 流程实例id
  decisionItem.value = $route.query.decisionItem as string // 同意、驳回、拒绝按钮权限
  taskId.value = $route.query.taskId as string // 流程实例id
  formInline.value.checkDate = dayjs().format('YYYY-MM-DD')
  // 编辑和详情页面获取详情信息
  if (pageType.value !== 'add') {
    getInfo() // 获取详情信息
    getApprovalRecord(formInline.value.processId) // 获取审批流程
  }
})
</script>

<template>
  <app-container>
    <detail-page :title="`${$route.meta.title}-${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="pageType === 'detail' && approvalStatusName === '待审批'" type="primary" @click="handleApprove('同意')">
          同意
        </el-button>
        <el-button v-if="pageType === 'detail' && approvalStatusName === '待审批' && decisionItem !== '3'" type="primary" @click="handleApprove('驳回')">
          驳回
        </el-button>
        <el-button v-if="pageType === 'detail' && approvalStatusName === '待审批' && decisionItem !== '2'" type="danger" @click="handleApprove('拒绝')">
          拒绝
        </el-button>
        <el-button v-if="pageType === 'detail' && approvalStatusName === '审批中'" type="info" @click="handleApprove('取消')">
          取消
        </el-button>
        <el-button v-if="pageType === 'add'" type="primary" @click="submit">
          提交
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="save(ruleFormRef)">
          保存
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="formInline"
        label-position="right"
        label-width="110px"
        :rules="rules"
      >
        <el-row :gutter="20" class="marg">
          <el-col :span="6">
            <el-form-item label="验收单编号:">
              <el-input
                v-model.trim="formInline.applyNo"
                :placeholder="pageType === 'detail' ? '' : '系统自动生成'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="验收单名称:">
              <el-input
                v-model.trim="formInline.applyName"
                :placeholder="pageType === 'detail' ? '' : '请输入验收单名称'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请单位:">
              <el-input
                v-model="formInline.applyUnitName"
                :class="{ 'detail-input': pageType === 'detail' }"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检修申请编号:" prop="acceptanceCheckId">
              <el-input
                v-model="checkIdObject.applyNo"
                :placeholder="pageType === 'detail' ? '无' : '请选择检修申请编号'"
                disabled
              >
                <template v-if="pageType !== 'detail'" #append>
                  <el-button
                    size="small"
                    @click="selectPerson"
                  >
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检修申请名称:" prop="constructionStandardProject">
              <el-input
                v-model.trim="checkIdObject.applyName"
                :placeholder="pageType === 'detail' ? '' : '请填写检修申请名称'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检修保养人:" prop="overhaulPerson">
              <el-input
                v-model.trim="formInline.overhaulPerson"
                :placeholder="pageType === 'detail' ? '' : '请填写检修保养人'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="检修日期:"
              prop="checkDate"
            >
              <el-date-picker
                v-model="formInline.checkDate"
                style="width: 100%;"
                type="date"
                :placeholder="pageType === 'detail' ? '' : '请选择检修日期'"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="marg">
          <el-col :span="12">
            <el-form-item label="备注:">
              <el-input
                v-model.trim="formInline.remark"
                :placeholder="pageType === 'detail' ? '' : '请填写备注'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="marg">
          <el-col :span="14">
            <el-form-item label="附件:">
              <show-photo v-if="formInline.fileList[0].minioFileName" :minio-file-name="formInline.fileList.length && formInline.fileList[0].minioFileName ? formInline.fileList[0].minioFileName : ''" />
              <span v-else-if="pageType === 'detail'">无</span>
              <input v-show="pageType === ''" ref="fileRef" type="file" @change="onFileChange">
              <el-button v-if="pageType !== 'detail'" id="file" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': formInline.fileList.length && formInline.fileList[0].minioFileName === '' ? '0px' : '20px' }" @click="upload">
                {{ formInline.fileList.length && formInline.fileList[0].minioFileName ? '更换附件' : '上传' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block title="检修设备列表">
      <el-table
        :data="formInline.equipmentList ? formInline.equipmentList : formInline.checkList"
        border
        style="width: 100%;"
      >
        <el-table-column align="center" label="序号" width="60" type="index" />
        <el-table-column v-for="(item, index) in columns" :key="index" align="center" :label="item.text" :width="item.width" :prop="item.value">
          <template #header>
            <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
          </template>
          <template #default="scope">
            <el-input v-if="item.text === '检修意见' && pageType !== 'detail'" v-model="scope.row[item.value]" :placeholder="`${item.text}`" class="input" />
            <el-select
              v-if="item.text === '检修结果'"
              v-model="scope.row[item.value]"
              clearable
              placeholder="请选择检修结果"
              size="default"
              :disabled="pageType === 'detail'"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </detail-block>
    <detail-block v-if="approvalStatusName !== '草稿箱' && pageType !== 'add'" title="审批流程">
      <!-- 审批流程 -->
      <approval-record ref="approvalRecord" :approval-record-data="approvalRecordData" />
    </detail-block>
    <!-- 审批弹窗 -->
    <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
    <!-- 选择设备检修列表 -->
    <check-list ref="checkListRef" @add="confirmCheckList" />
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
.top-info {
  width: 100%;
  height: 50px;
  padding-right: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 10px;
  background-color: #fff;

  .title {
    width: 75%;
    text-align: center;
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px;
  width: 100%;
  height: 6vh;
  margin-top: 10px;
  background-color: rgb(255 253 253);
}

.info-content {
  padding: 15px;
  border-radius: 10px;
  background-color: #fff;
}

.dialog-buts {
  width: 100%;
  display: flex;
  justify-content: space-around;
}
</style>
