<!-- 分包验收详情 -->
<script lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ref } from 'vue'
import type { IApplyDetail, ISampleList } from '../subpackage-interface'
import selectSample from '../apply/components/selectSample.vue'
import selectProjectNo from '../apply/components/selectProjectNo.vue'
import type { IForm } from './check-interface'
import selectApply from './components/selectApply.vue'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import { cancelApproval, fetchApproval, submitApproval } from '@/api/approval'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { addCheck, detail, failUpdateCheck, submit, updateCheck } from '@/api/business/subpackage/check'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { UploadFile } from '@/api/measure/file'
import useUserStore from '@/store/modules/user'
const user = useUserStore() // 用户信息
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 字典
const pageType = ref('add') // 页面类型: add, edit, detail
const infoId = ref('') // 列表id
const { proxy } = getCurrentInstance() as any
const $route = useRoute()
const $router = useRouter()
const query = $route.query
const selectApplyVisible = ref(false) // 控制选择已通过的项目申请的显隐
const ruleFormRef = ref<FormInstance>() as any
const submitId = ref('') // 新建提交时所用的id

// 表单
const detailForm = ref<IForm>({
  formId: query.formId as string,
  checkConclusion: '', // 验收结论
  checkMinioFileName: '', // 项目验收文件-minio存储文件名
  checkProcessId: '', // 流程实例id（未通过验收编辑接口入参必传）
  checkRemark: '', // 项目验收备注
  checkTime: '', // 验收时间
  id: '', // 分包项目id
  outsourcerNo: '', // 分包方编号
  projectNo: '', // 分包方项目编号
  projectName: '', // 分包项目名称
  checkerName: '', // 验收人
  outsourcerName: '', // 公司名称
  outsourceReasonName: '', // 分包原因名称
})
// 校验规则
const formRules = ref({
  id: [{ required: true, message: '分包项目编号必填', trigger: 'blur' }],
  projectNo: [{ required: true, message: '分包项目编号必填', trigger: 'blur' }],
  // projectName: [{ required: true, message: '分包项目名称必填', trigger: 'blur' }],
  // outsourcerId: [{ required: true, message: '分包方编号必填', trigger: ['blur', 'change'] }],
  // outsourcerName: [{ required: true, message: '公司名称必填', trigger: ['blur', 'change'] }],
  // outsourceReasonName: [{ required: true, message: '分包原因必填', trigger: ['blur', 'change'] }],
  // preCost: [{ required: true, message: '预计费用必填', trigger: ['blur', 'change'] }],
  checkTime: [{ required: true, message: '验收时间必填', trigger: ['blur', 'change'] }],
  checkConclusion: [{ required: true, message: '验收结论必填', trigger: ['blur', 'change'] }],
})

const list = ref<ISampleList[]>([])// 表格数据
// 表头
const columns = ref<TableColumn[]>([
  { text: '样品编号', value: 'sampleNo', align: 'center', width: '160' },
  { text: '样品名称', value: 'sampleName', align: 'center' },
  { text: '型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '委托书编号', value: 'orderCode', align: 'center', width: '160' },
  { text: '委托单位', value: 'customerName', align: 'center' },
])

// 从路由中获取页面类型参数
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}

// 获取详情
const getDetail = () => {
  detail({ id: $route.params.id }).then((res) => {
    detailForm.value = res.data
    list.value = res.data.sampleList.filter((item: ISampleList) => {
      return item !== null
    })
  })
}

// 关闭新增页面的回调
const close = () => {
  $router.back()
}
// -------------------------------------审批----------------------------------------
const approvalRecordData = ref([]) // 审批流程数据
const approvalDialog = ref() // 审批对话ref
const getApprovalRecord = (processId: string) => {
  if (pageType.value !== 'add') {
    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: detailForm.value.checkProcessId!,
      comments: '',
    }
    ElMessageBox.confirm(
      '确认取消该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        cancelApproval(params).then((res) => {
          ElMessage({
            type: 'success',
            message: '取消成功',
          })
          close()
        })
      })
  }
  else if (val === '同意') {
    approvalDialog.value.initDialog('agree', query.taskId)
  }
  else if (val === '驳回') {
    approvalDialog.value.initDialog('reject', query.taskId)
  }
  else if (val === '拒绝') {
    approvalDialog.value.initDialog('refuse', query.taskId)
  }
}
// ------------------------------------------------------------------------------------

// 保存
const handleSave = () => {
  if (!list.value.length) {
    ElMessage.warning('样品信息不能为空')
    return false
  }
  ruleFormRef.value.validate((valid: boolean) => {
    console.log('0000', query.applyApprovalStatusName)

    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        background: 'rgba(255, 255, 255, 0.8)',
      })
      if (pageType.value === 'add') { // 新建
        addCheck(detailForm.value).then((res) => {
          submitId.value = res.data.id
          ElMessage.success('保存成功')
          loading.close()
        })
      }
      else if (pageType.value === 'edit') { // 编辑
        if (query.approvalStatusName === '未通过-驳回') { // 未通过-驳回
          failUpdateCheck(detailForm.value).then((res) => {
            ElMessage.success('保存成功')
            loading.close()
            close()
          })
        }
        else { // 草稿箱和已取消
          updateCheck(detailForm.value).then((res) => {
            ElMessage.success('保存成功')
            loading.close()
            close()
          })
        }
      }
    }
    else {
      console.log('表单校验不通过')
    }
  })
}

// 提交
const handleSubmit = () => {
  console.log(detailForm.value.id)
  if (detailForm.value.id) {
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    const params = {
      id: submitId.value,
      formId: query.formId, // 表单id
    }
    submit(params).then(() => {
      ElMessage.success('已提交')
      loading.close()
      close()
    })
  }
  else {
    ElMessage.warning('请先保存！')
  }
}

// ----------------------------------------文件上传----------------------------------
const fileRef = ref()
const onFileChange = (event: any) => {
  // 原生上传
  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) {
        detailForm.value.checkMinioFileName = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
// -----------------------------------------------------------------------------------
// --------------------------------------选择分包项目编号------------------------------
// 点击选择
const clickChoose = () => {
  selectApplyVisible.value = true
}
// 点击对话框取消
const changeVisible = () => {
  selectApplyVisible.value = false
}
// 点击对话框确定
const clickConfirm = (val: any) => {
  console.log('any', val)
  detail({ id: val[0].id }).then((res) => { // 获取样品信息
    list.value = res.data.sampleList.filter((item: ISampleList) => {
      return item !== null
    })
  })
  detailForm.value.outsourcerName = val[0].outsourcerName // 公司名称
  detailForm.value.outsourcerNo = val[0].outsourcerNo // 分包方编号
  detailForm.value.projectNo = val[0].projectNo // 分包方项目编号
  detailForm.value.projectName = val[0].projectName // 分包项目名称
  detailForm.value.id = val[0].id // 分包项目id
  detailForm.value.outsourceReasonName = val[0].outsourceReasonName // 分包原因名称
}
// --------------------------------------------------------------------------------------
onMounted(() => {
  console.log('00000', query.approvalStatusName)

  detailForm.value.checkProcessId = query.checkProcessId as string // 流程实例
  if (pageType.value !== 'add') { // 编辑、详情
    getDetail()
    if (query.approvalStatusName !== '草稿箱') {
      getApprovalRecord(detailForm.value.checkProcessId) // 获取审批流程
    }
  }
  else {
    detailForm.value.checkerName = user.name // 验收人默认登陆用户
  }
})
</script>

<template>
  <app-container style="overflow: hidden;">
    <detail-page :title="`分包项目验收-${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="pageType === 'detail' && query.approvalStatusName === '待审批'" type="primary" @click="handleApprove('同意')">
          同意
        </el-button>
        <el-button v-if="pageType === 'detail' && query.approvalStatusName === '待审批' && query.decisionItem !== '3'" type="primary" @click="handleApprove('驳回')">
          驳回
        </el-button>
        <el-button v-if="pageType === 'detail' && query.approvalStatusName === '待审批' && query.decisionItem !== '2'" type="danger" @click="handleApprove('拒绝')">
          拒绝
        </el-button>
        <el-button v-if="pageType === 'add'" type="primary" @click="handleSubmit">
          提交
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="handleSave">
          保存
        </el-button>
        <!-- <el-button v-if="pageType === 'detail'" type="primary">
          打印
        </el-button> -->
        <el-button v-if="pageType === 'detail' && query.approvalStatusName === '审批中'" type="info" @click="handleApprove('取消')">
          取消
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form ref="ruleFormRef" :model="detailForm" label-width="140" label-position="right" :rules="formRules">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="分包项目编号:" prop="projectNo">
              <el-input v-model="detailForm.projectNo" :placeholder="pageType === 'detail' ? '' : '请选择分包项目编号'" disabled>
                <template v-if="pageType !== 'detail'" #append>
                  <el-button
                    size="small"
                    @click="clickChoose"
                  >
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分包项目名称:" prop="projectName">
              <el-input v-model="detailForm.projectName" :placeholder="pageType === 'detail' ? '' : '分包项目名称'" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分包方编号:">
              <el-input v-model="detailForm.outsourcerNo" :placeholder="pageType === 'detail' ? '' : '分包方编号'" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="公司名称:">
              <el-input v-model="detailForm.outsourcerName" :placeholder="pageType === 'detail' ? '' : '公司名称'" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分包原因:" prop="outsourceReasonName">
              <el-input v-model="detailForm.outsourceReasonName" :placeholder="pageType === 'detail' ? '' : '分包原因'" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="验收人:" prop="checkerName">
              <el-input v-model="detailForm.checkerName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="验收时间:" prop="checkTime">
              <el-date-picker
                v-model="detailForm.checkTime" type="datetime" placeholder="请选择验收时间"
                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="验收结论:" prop="checkConclusion">
              <el-input v-model="detailForm.checkConclusion" :disabled="pageType === 'detail'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="备注:" prop="checkRemark">
              <el-input v-model="detailForm.checkRemark" type="textarea" autosize :disabled="pageType === 'detail'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="附件:" prop="applyMinioFileName">
              <input v-show="pageType === ''" ref="fileRef" multiple type="file" @change="onFileChange">
              <span v-if="pageType === 'detail' && !detailForm.checkMinioFileName">无</span>
              <div v-else style="display: flex;">
                <show-photo :minio-file-name="detailForm.checkMinioFileName || ''" style="display: inline-block;" />
              </div>
              <el-button v-if="pageType !== 'detail'" type="primary" :disabled="pageType === 'detail'" @click="upload">
                {{ detailForm.checkMinioFileName ? '更换' : '上传' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block title="样品信息">
      <el-table :data="list" border style="width: 100%;" max-height="600">
        <el-table-column align="center" label="序号" width="80" type="index" />
        <el-table-column
          v-for="item in columns" :key="item.value" :prop="item.value" :label="item.text"
          :width="item.width" show-overflow-tooltip align="center"
        />
      </el-table>
    </detail-block>
    <detail-block v-if="query.approvalStatusName !== '草稿箱' && pageType !== 'add'" title="审批流程">
      <!-- 审批流程 -->
      <approval-record ref="approvalRecord" :approval-record-data="approvalRecordData" />
    </detail-block>
    <!-- 项目选择 -->
    <select-apply :visible="selectApplyVisible" @changeVisible="changeVisible" @clickConfirm="clickConfirm" />
    <!-- 审批弹窗 -->
    <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
</style>
