<template>
  <el-dialog draggable :title='title' v-model='planAddition' width='500px' :before-close='cancelFn'>
    <el-form
        :model='form'
        ref='formRef'
        :rules='rules'
        label-width='auto'
        class='form-one'
    >
      <el-form-item  label='普测负责单位:'>
        <el-input v-model='form.deptName' disabled></el-input>
      </el-form-item>
      <el-form-item  label='计划名称:' prop='planName'>
        <el-input v-model='form.planName' disabled></el-input>
      </el-form-item>
      <el-form-item  label='计划开始时间:' prop='planStartTime'>
        <el-input v-model='form.planStartTime' disabled></el-input>
      </el-form-item>
      <el-form-item  label='计划结束时间:' prop='planEndTime'>
        <el-input v-model='form.planEndTime' disabled></el-input>
      </el-form-item>
      <el-form-item for='-' label='测试变电站:' prop='subIds' style='display: flex; align-items: center'>
        <el-input v-model='form.substationName' disabled/>
      </el-form-item>
      <el-form-item  label='实际完成时间:' prop='completeTime'>
        <el-date-picker
            v-model='form.completeTime'
            type='date'
            placeholder='选择实际完成时间'
            value-format='YYYY-MM-DD'
        ></el-date-picker>
      </el-form-item>
      <el-form-item for='-' label='测试负责人:' prop='leader'>
        <el-input v-model='form.completeBy' placeholder='请输入测试负责人'></el-input>
      </el-form-item>
      <el-form-item for='-' class='uploadFile' label='普测报告:' prop='testReport'>
        <el-upload
            ref='uploadRef'
            action=''
            accept='.doc,.docx,.xlsx,.xls,.pdf'
            :limit='1'
            :on-exceed='handleExceed'
            :on-change='choose'
            :auto-upload='false'
            :on-progress="uploadFileName('testReport')"
        >
          <template #trigger>
            <el-button type='primary'>上传文件</el-button>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item for='-' label='测试是否有问题：' prop='problemFlag'>
        <!-- 默认值 否 -->
        <el-radio-group v-model='form.problemFlag'>
          <el-radio value='1'>是</el-radio>
          <el-radio value='0'>否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item style='width: 100%' for='-' label='问题描述:' prop='problemDetail' v-if="form.problemFlag == '1'">
        <el-input type='textarea' v-model='form.problemDetail' placeholder='请输入问题描述'></el-input>
      </el-form-item>
      <!-- </el-form> -->
    </el-form>
    <template #footer>
      <div class='dialog-footer'>
        <el-button @click='cancelFn'>取消</el-button>
        <el-button type='primary' @click='submitFn'>确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang='ts'>
import { ref, inject, nextTick } from 'vue'
import { addSurvey, auditSurvey } from '@/api/process-boot/generalTest'
import TableStore from '@/utils/tableStore' // 若不是列表页面弹框可删除
import { ElMessage, genFileId, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
import { uploadFile, getFileNameAndFilePath } from '@/api/system-boot/file'
import { useDictData } from '@/stores/dictData'
import { addSurveyTest,updateSurveyTest, getTestById } from '@/api/supervision-boot/survey/test'

const tableStore = inject('tableStore') as TableStore
let uploadName = ref('')
// 上传报告
const uploadRef = ref()
const fileList = ref<UploadUserFile[]>([])
const emit = defineEmits(['onsubmit'])
const dictData = useDictData()
const addFlagRef = ref(true)
const title = ref('')
const planAddition = ref(false)
const form: any = ref({
  id:'',
  deptName: '',
  planStartTime: '',
  planEndTime: '',
  planName: '',
  substationName: '',

  completeTime: '',
  completeBy: '',
  testReport: '',
  problemDetail: '', //测试问题
  problemFlag: '0' //是否有问题
})


/**
 * addFlag为true，则为填报测试数据，创建新流程
 * 为false，则为修改测试数据，重新发起流程
 */
const open = async (text: string, id: string, addFlag: boolean) => {
  title.value = text
  formRef.value?.resetFields()
  addFlagRef.value = addFlag
  //根据测试id获取数据
  await getTestById(id).then(res => {
    //如果是新增，则只需将计划的一些信息回显即可
    form.value.id = id
    form.value.deptName = res.data.deptName
    form.value.planStartTime = res.data.planStartTime
    form.value.planEndTime = res.data.planEndTime
    form.value.planName = res.data.planName
    form.value.substationName = res.data.substationName
    //部分清空
    uploadRef.value?.clearFiles()
    form.value.completeTime = ''
    form.value.completeBy = ''
    form.value.testReport = ''
    form.value.problemDetail = ''
    form.value.problemFlag = '0'
    fileList.value = []
    if (!addFlag) {
      //还需回显上次填报的测试数据 todo...,待重新发起的时候去做

    }
  })


  planAddition.value = true
}

//处理成效报告
const testReport = ref('')

const formRef = ref()
const rules = {
  completeTime: [{ required: true, message: '选择实际完成时间	', trigger: 'change' }],
  completeBy: [{ required: true, message: '请输入测试负责人', trigger: 'blur' }],
  fileList: [{ required: true, message: '请上传文件', trigger: 'change' }],
  problemFlag: [{ required: true, message: '请选择测试是否有问题', trigger: 'change' }],
  problemDetail: [{ required: true, message: '请输入测试问题', trigger: 'blur' }]
}
const cancelFn = () => {
  formRef.value.resetFields()
  planAddition.value = false
}

// 提交
const submitFn = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      if (!testReport.value) {
        return ElMessage({
          message: '请上传处理成效报告',
          type: 'warning'
        })
      }
      if(addFlagRef){
        //新增，则组装业务数据提交后台
        await addSurveyTest(form.value)
        //查询进线数据，避免一直处于loading状态
        ElMessage.success('申请成功')
        tableStore.index()
        planAddition.value = false
      }else{
          await updateSurveyTest(form.value)
          //查询进线数据，避免一直处于loading状态
          ElMessage.success('重新申请成功')
          tableStore.index()
          planAddition.value = false
      }
    }
  })
}
const audit = (filePath: any) => {
  if (title.value == '普测计划新增') {
    addSurvey({ ...form.value, filePath: filePath }).then((res: any) => {
      ElMessage.success('新增成功!')
      cancelFn()
      emit('onsubmit')
    })
  } else if (title.value == '重新发起计划') {
    auditSurvey({ ...form.value, filePath: filePath }).then((res: any) => {
      ElMessage.success('重新发起计划成功!')
      cancelFn()
      emit('onsubmit')
    })
  }
}

defineExpose({ open })


const choose = (e: any) => {
  uploadFile(e.raw, '/supervision/').then(res => {
    testReport.value = res.data.name
    form.value.testReport = res.data.name
  })
}


const handleExceed: UploadProps['onExceed'] = files => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}

//上传报告改变
const uploadFileName = val => {
  uploadName.value = val
}

</script>
<style lang='scss' scoped>
// :deep(.el-upload-list__item-info) {
//     width: 250px;
// }
</style>
