<!-- 建标管理 基本信息 -->
<script name="standardBuildApproveBasic" lang="ts" setup>
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import dayjs from 'dayjs'
import type { IForm } from '../build-interface'
import SelectFileTemplateDialog from '../dialog/selectFileTemplateDialog.vue'
import showPhoto from '@/components/showPhoto/index.vue'
import { UploadFile } from '@/api/file'
import type { dictType } from '@/global'
import type { IAddress } from '@/components/AddressSelect/address-interface'
import { getDictByCode } from '@/api/system/dict'
import { SCHEDULE } from '@/utils/scheduleDict'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import useUserStore from '@/store/modules/user'
import { addBuildList, failUpdateBuildList, getInfo, submit, updateBuildList } from '@/api/equipment/standard/build'
const props = defineProps({
  pageType: { // 页面类型 add新建 edit编辑 detail详情
    type: String,
    requre: true,
    default: 'detail',
  },
  id: {
    type: String,
    requre: true,
  },
  approvalStatusName: { // 审批状态名称
    type: String,
    requre: true,
  },
})
const emits = defineEmits(['addSuccess', 'submitSuccess'])
const user = useUserStore() // 用户信息
const form = ref<IForm>({
  applyNo: '', // 申请单编号
  applyName: '', // 申请单名称
  createUserId: '', // 申请人id
  createUserName: '', // 申请人
  createTime: '', // 申请时间
  standardName: '', // 标准装置名称
  meterOrganize: '', // 计量机构名称
  standardFileTemplate: '', // 标准文档模板
  examTableFile: '', // 考核表
  buildStandardReportFile: '', // 建标报告
  remark: '', // 备注
  standardCertificateFile: '', // 标准证书
})
const ruleFormRef = ref() // 表单ref
const loading = ref(false) // loading
const infoId = ref('') // id
const formRules = ref<FormRules>({ // 校验规则
  applyName: [{ required: true, message: '申请单名称不能为空', trigger: ['blur', 'change'] }],
  standardName: [{ required: true, message: '标准装置名称不能为空', trigger: ['blur', 'change'] }],
  meterOrganize: [{ required: true, message: '计量机构名称不能为空', trigger: ['blur', 'change'] }],
  standardFileTemplate: [{ required: true, message: '标准文档模板不能为空', trigger: ['blur', 'change'] }],
  buildStandardReportFile: [{ required: true, message: '建标报告不能为空', trigger: ['blur', 'change'] }],
  examTableFile: [{ required: true, message: '考核表不能为空', trigger: ['blur', 'change'] }],
})

// -----------------------------------------------选择标准模板文档-----------------------------------
const selectFileTemplateDialogRef = ref() // 选择模板文档组件ref
// 点击选择标准模板文档
const selectStandardFileTemplate = () => {
  selectFileTemplateDialogRef.value.initDialog()
}

// 确认选择文件
const confirmSelectedFiles = (val: any) => {
  form.value.standardFileTemplate = val[0].minioFileName
}

// -----------------------------------------------保存----------------------------------------------
/**
 * 点击保存
 * @param formEl 基本信息表单ref
 */
const saveForm = async () => {
  await ruleFormRef.value.validate((valid: boolean) => {
    if (valid) { // 基本信息表单通过校验
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        const loading = ElLoading.service({
          lock: true,
          text: '加载中...',
          background: 'rgba(255, 255, 255, 0.8)',
        })
        if (props.pageType === 'add') { // 新建
          addBuildList(form.value).then((res) => {
            loading.close()
            form.value.applyNo = res.data.applyNo // 申请单编号
            infoId.value = res.data.id // id
            emits('addSuccess', infoId.value)
            ElMessage.success('已保存')
          }).catch(() => {
            loading.close()
          })
        }
        else if (props.pageType === 'edit') { // 编辑
          console.log(props.approvalStatusName)
          if (props.approvalStatusName === '草稿箱' || props.approvalStatusName === '全部') {
            updateBuildList(form.value).then((res) => {
              loading.close()
              emits('addSuccess', infoId.value)
              ElMessage.success('已保存')
            }).catch(() => {
              loading.close()
            })
          }
          else { // '未通过' || '已取消'
            failUpdateBuildList(form.value).then((res) => {
              loading.close()
              emits('submitSuccess')
              ElMessage.success('已保存')
            }).catch(() => {
              loading.close()
            })
          }
        }
      })
    }
  })
}
// ---------------------------------文件上传-------------------------------------------
const fileRef = ref()
const examTableFileRef = ref()
const onFileChangeExamTableFile = (event: any) => { // 考核表
  // 原生上传
  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) {
        form.value.examTableFile = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
}
const uploadExamTableFile = () => {
  examTableFileRef.value.click()
}

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) {
        form.value.buildStandardReportFile = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}

// ----------------------------------------------提交--------------------------------------------
// 提交
/**
 *
 * @param processId 流程实例id
 * @param id
 */
const submitForm = (processId: string, id: string) => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(255, 255, 255, 0.6)',
  })
  submit({ id, formId: SCHEDULE.STANDARD_SETUP_APPROVAL, processId }).then((res) => {
    ElMessage.success('已提交')
    emits('submitSuccess')
    loading.close()
  })
}
// -----------------------------------------获取详情------------------------------------------
// 获取详情
const fetchInfo = () => {
  loading.value = true
  getInfo({ id: infoId.value }).then((res) => {
    loading.value = false
    form.value = res.data
  })
}
// ---------------------------------------------钩子----------------------------------------------
watch(() => props.id, (newValue) => {
  infoId.value = newValue!
  if (infoId.value) {
    fetchInfo() // 获取详情信息
  }
}, { immediate: true })

onMounted(async () => {
  form.value.createUserId = user.id// 申请人id
  form.value.createUserName = user.name // 申请人名字
  form.value.createTime = dayjs().format('YYYY-MM-DD HH-mm:ss')// 申请时间
  if (props.pageType !== 'add' && infoId.value) {
    fetchInfo() // 获取详情信息
  }
})

defineExpose({ saveForm, submitForm })
</script>

<template>
  <detail-block v-loading="loading" title="">
    <el-form
      ref="ruleFormRef"
      :model="form"
      :label-width="120"
      label-position="right"
      :rules="formRules"
    >
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="申请单编号:" prop="applyNo">
            <el-input v-model="form.applyNo" disabled placeholder="系统自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请单名称:" prop="applyName">
            <el-input
              v-model="form.applyName"
              :placeholder="pageType === 'detail' ? '' : '请输入申请单名称'"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请人:">
            <el-input
              v-model="form.createUserName" disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请时间:" prop="createTime">
            <el-date-picker
              v-model="form.createTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标准装置名称:" prop="standardName">
            <el-input
              v-model="form.standardName"
              :placeholder="pageType === 'detail' ? '' : '请输入标准装置名称'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="计量机构名称" prop="meterOrganize">
            <el-input
              v-model="form.meterOrganize"
              :placeholder="pageType === 'detail' ? '' : '请输入计量机构名称'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标准文档模板:" prop="standardFileTemplate">
            <el-input
              v-model="form.standardFileTemplate"
              :placeholder="pageType === 'detail' ? '' : '请选择标准文档模板'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            >
              <template v-if="pageType !== 'detail'" #append>
                <el-button size="small" @click="selectStandardFileTemplate">
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="marg">
        <el-col :span="24">
          <el-form-item label="建标报告:" prop="buildStandardReportFile">
            <show-photo v-if="form.buildStandardReportFile" :minio-file-name="form.buildStandardReportFile" />
            <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': form.buildStandardReportFile === '' ? '0px' : '20px' }" @click="upload">
              {{ form.buildStandardReportFile === '' ? '上传' : '更换附件' }}
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="marg">
        <el-col :span="24">
          <el-form-item label="考核表:" prop="examTableFile">
            <show-photo v-if="form.examTableFile" :minio-file-name="form.examTableFile" />
            <span v-else-if="pageType === 'detail'">无</span>
            <input v-show="pageType === ''" ref="examTableFileRef" type="file" @change="onFileChangeExamTableFile">
            <el-button v-if="pageType !== 'detail'" id="file" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': form.examTableFile === '' ? '0px' : '20px' }" @click="uploadExamTableFile">
              {{ form.examTableFile === '' ? '上传' : '更换附件' }}
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="备注:" prop="remark">
            <el-input
              v-model="form.remark"
              autosize
              type="textarea"
              :placeholder="pageType === 'detail' ? '' : '请输入备注'"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </detail-block>
  <select-file-template-dialog ref="selectFileTemplateDialogRef" @confirm="confirmSelectedFiles" />
</template>
