<template>
  <el-dialog
    title="完成任务"
    :visible="visible"
    width="600px"
    @close="handleClose"
    @update:visible="$emit('update:visible', $event)">
    <el-form ref="form" label-position="right" label-width="140px" :model="form" :rules="rules" size="medium">
      <el-form-item label="实际工作量 (小时)" prop="actualWorkHour">
        <div class="actual-hour-row">
          <el-input-number
            v-model="form.actualWorkHour"
            controls-position="right"
            :min="0"
            :precision="1"
            :step="0.5" />
          <el-button size="mini" @click="addActualWorkHour(0.5)">+0.5</el-button>
          <el-button size="mini" @click="addActualWorkHour(2)">+2</el-button>
        </div>
      </el-form-item>

      <el-form-item label="完成时间" prop="completionDate">
        <el-date-picker
          v-model="form.completionDate"
          placeholder="选择完成日期"
          style="width: 100%"
          type="date"
          value-format="yyyy-MM-dd" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" placeholder="请输入完成备注..." :rows="4" type="textarea" />
      </el-form-item>

      <el-form-item label="附件上传" prop="attachments">
        <el-upload
          ref="uploadRef"
          action=""
          :auto-upload="false"
          :before-upload="beforeUpload"
          class="upload-demo"
          :file-list="fileList"
          :limit="5"
          :multiple="true"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button slot="tip" size="mini">最多5个文件，每个不超过20MB</el-button>
        </el-upload>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button :loading="submitLoading" type="primary" @click="handleSubmit">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import attachmentUploadMixin from '@/mixins/attachmentUpload'
  import opsEventTaskApi from '@/api/devops/opsEventTask'

  export default {
    name: 'CompleteDialog',
    mixins: [attachmentUploadMixin],
    props: {
      visible: { type: Boolean, default: false },
      taskId: { type: Number, default: null },
      taskData: { type: Object, default: null },
      testResult: { type: String, default: '' },
    },
    data() {
      return {
        form: {
          actualWorkHour: null,
          remark: '',
          completionDate: '',
          attachments: [],
        },
        rules: {
          actualWorkHour: [{ required: true, message: '请输入实际工作量', trigger: 'blur' }],
        },
        submitLoading: false,
      }
    },
    watch: {
      async visible(val) {
        if (!val || !this.taskId) return
        // set default completion date to today
        if (!this.form.completionDate) {
          const today = new Date()
          const y = today.getFullYear()
          const m = String(today.getMonth() + 1).padStart(2, '0')
          const d = String(today.getDate()).padStart(2, '0')
          this.form.completionDate = `${y}-${m}-${d}`
        }
        // pre-fill actualWorkHour from registered work hours
        try {
          const res = await opsEventTaskApi.getWorkHourList(this.taskId)
          const workHourList = res.data?.list || res.data || []
          const totalRegisteredHours = workHourList.reduce((sum, row) => sum + (Number(row.actualHour) || 0), 0)
          if (totalRegisteredHours > 0) {
            this.form.actualWorkHour = Math.round(totalRegisteredHours * 10) / 10
            return
          }
        } catch (e) {
          // fallback to taskData if query fails
        }
        // fallback: use taskData.actualWorkHour
        if (this.taskData && this.taskData.actualWorkHour != null) {
          this.form.actualWorkHour = this.taskData.actualWorkHour
        }
      },
    },
    methods: {
      addActualWorkHour(hours) {
        const current = Number(this.form.actualWorkHour) || 0
        this.form.actualWorkHour = Math.round((current + hours) * 10) / 10
      },
      formatRemark(remark) {
        if (!remark) return remark
        // 将内容按句子或逻辑段落分段，增加换行符以便阅读
        return remark
          .replace(/([。！？])/g, '$1\n') // 在句号、感叹号、问号后添加换行
          .replace(/(\d+\.[\s]*)/g, '\n$1') // 在数字编号前添加换行
          .replace(/(\n{2,})/g, '\n') // 去除多余连续换行
          .trim()
      },
      handleSubmit() {
        this.$refs.form.validate(async (valid) => {
          if (!valid) return
          if (!this.taskId) {
            this.$message.error('任务ID不能为空')
            return
          }
          this.submitLoading = true
          try {
            // 上传附件，后端 complete 接口会自动创建过程记录
            const attachments = await this.uploadAttachments()

            // 完成任务（后端会自动创建过程记录并将附件信息记录到任务附件中）
            const testResult = this.testResult || (this.taskData && this.taskData.testResult) || ''
            const payload = {
              id: this.taskId,
              actualWorkHour: this.form.actualWorkHour,
              remark: this.formatRemark(this.form.remark),
              attachments,
              testResult,
              completeDate: this.form.completionDate,
            }
            await opsEventTaskApi.complete(payload)

            this.$emit('refresh')
            this.$emit('success')
            this.$message.success('任务完成已提交')
            this.handleClose()
          } catch (err) {
            this.$message.error('提交失败: ' + (err.message || err))
          } finally {
            this.submitLoading = false
          }
        })
      },
      handleClose() {
        // reset form and close
        this.form.actualWorkHour = null
        this.form.remark = ''
        this.form.completionDate = ''
        this.resetAttachmentFiles()
        this.$emit('update:visible', false)
      },
    },
  }
</script>

<style scoped>
  .actual-hour-row {
    display: flex;
    gap: 4px;
    align-items: center;

    .el-button--mini {
      flex-shrink: 0;
    }
  }
  .upload-demo {
    display: block;
  }
</style>
