<template>
  <div class="exp-project-detail">
    <!-- 顶部操作按钮 -->
    <div class="toolbar">
      <el-button
        v-if="!editing && (status==='草稿' || status==='已驳回')"
        @click="handleEdit"
        type="primary"
        size="small">
        编辑
      </el-button>
      <el-button
        v-if="editing"
        @click="handleSave"
        type="primary"
        size="small"
        :loading="saving">
        保存
      </el-button>
      <el-button
        v-if="editing"
        @click="handleCancel"
        size="small">
        取消
      </el-button>
    </div>

    <!-- 项目详情表单 - label在上，input在下 -->
    <el-form
      :model="formData"
      ref="detailForm"
      label-position="top"
      v-loading="loading">

      <el-row :gutter="20">
        <!-- 左侧列 -->
        <el-col :span="10">
          <el-form-item label="试验名称（Name of the experiment）">
            <el-input
              v-model="formData.title"
              :readonly="!editing"
              placeholder="请输入试验名称">
            </el-input>
          </el-form-item>

          <el-form-item label="试验目的（Purpose of the experiment）">
            <el-input
              v-model="formData.purpose"
              :readonly="!editing"
              placeholder="请输入试验目的">
            </el-input>
          </el-form-item>

          <el-form-item label="验证方法及判断标准（Experiment Justification）">
            <el-input
              v-model="formData.justification"
              :readonly="!editing"
              placeholder="请输入验证方法及判断标准">
            </el-input>
          </el-form-item>

          <el-form-item label="试验产品型号（Products'type）">
            <el-input
              v-model="formData.productType"
              :readonly="!editing"
              placeholder="请输入试验产品型号">
            </el-input>
          </el-form-item>

          <el-form-item label="期望完成日期（Desired finish date）">
            <el-date-picker
              v-model="formData.expectedFinishDate"
              :disabled="!editing"
              type="date"
              format="yyyy/MM/dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <!-- 右侧大文本框 -->
        <el-col :span="14">
          <el-form-item label="试验申请数量（Quantity requirement）">
            <el-input
              v-model="formData.quantityReq"
              type="textarea"
              :readonly="!editing"
              :rows="2"
              placeholder="请输入试验申请数量">
            </el-input>
          </el-form-item>
          <el-form-item style="margin-top: 35px" label="工艺、取样、测试要求（PartIII Process,Sampling,and Test Requirement）">
            <el-input
              v-model="formData.processRequirement"
              type="textarea"
              :readonly="!editing"
              :rows="9"
              placeholder="请输入工艺、取样、测试要求">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 底部：试验负责人信息 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="试验负责人（Project leader）">
            <el-input
              v-model="formData.projectLeader"
              :readonly="!editing"
              placeholder="请输入试验负责人">
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="14">
          <el-form-item label="联系方式（Contact method）">
            <el-input
              v-model="formData.contactMethod"
              :readonly="!editing"
              placeholder="请输入联系方式">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { getExpApplyDetail, saveExpApply } from '@/api/erf/erf'

export default {
  name: 'ExpProjectDetail',

  props: {
    applyNo: {
      type: String,
      required: true
    },
    status: {
      type: String,
      required: true
    },
    height: {
      type: String,
      default: '35vh'
    }
  },

  data() {
    return {
      formData: {
        applyNo: '',
        buNo: '',
        experimentType: '',
        projectNo: '',
        title: '',
        purpose: '',
        justification: '',
        productType: '',
        quantityReq: '',
        expectedFinishDate: '',
        projectLeader: '',
        contactMethod: '',
        processRequirement: '',
        status: '',
        creatorUserId: '',
        creatorName: '',
        createTime: '',
        updateTime: '',
        plannerUserId: '',
        plannerName: '',
        workOrderNo: '',
        scheduledDate: ''
      },
      originalData: {}, // 保存原始数据，用于取消时恢复
      loading: false,
      editing: false,
      saving: false
    }
  },

  watch: {
    applyNo: {
      immediate: true,
      handler(val) {
        if (val) {
          this.editing = false
          this.loadDetail()
        }
      }
    }
  },

  methods: {
    /**
     * 加载项目详情
     */
    loadDetail() {
      this.loading = true
      getExpApplyDetail({ applyNo: this.applyNo }).then(({data}) => {
        this.loading = false
        if (data && data.code === 0) {
          this.formData = { ...this.formData, ...data.data }
          this.originalData = JSON.parse(JSON.stringify(this.formData))
        } else {
          this.$message.error(data.msg || '加载详情失败')
        }
      }).catch(error => {
        this.loading = false
        this.$message.error('加载详情异常')
      })
    },

    /**
     * 进入编辑模式
     */
    handleEdit() {
      this.editing = true
      this.originalData = JSON.parse(JSON.stringify(this.formData))
    },

    /**
     * 保存修改
     */
    handleSave() {
      // 数据验证
      if (!this.formData.title) {
        this.$message.warning('请输入试验名称')
        return
      }
      if (!this.formData.expectedFinishDate) {
        this.$message.warning('请选择期望完成日期')
        return
      }

      this.saving = true

      // 准备保存数据
      const saveData = {
        applyNo: this.formData.applyNo,
        buNo: this.formData.buNo,
        experimentType: this.formData.experimentType,
        projectNo: this.formData.projectNo,
        title: this.formData.title,
        purpose: this.formData.purpose,
        justification: this.formData.justification,
        productType: this.formData.productType,
        quantityReq: this.formData.quantityReq,
        expectedFinishDate: this.formData.expectedFinishDate,
        projectLeader: this.formData.projectLeader,
        contactMethod: this.formData.contactMethod,
        processRequirement: this.formData.processRequirement
      }

      saveExpApply(saveData).then(({data}) => {
        this.saving = false
        if (data && data.code === 0) {
          this.$message.success('保存成功')
          this.editing = false
          this.loadDetail()
          // 通知父组件刷新列表
          this.$emit('refresh')
        } else {
          this.$message.error(data.msg || '保存失败')
        }
      }).catch(error => {
        this.saving = false
        this.$message.error('保存异常')
      })
    },

    /**
     * 取消编辑
     */
    handleCancel() {
      this.$confirm('取消编辑将放弃所有修改，确定取消？', '操作提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formData = JSON.parse(JSON.stringify(this.originalData))
        this.editing = false
      }).catch(() => {
        // 用户点击了取消
      })
    }
  }
}
</script>

<style scoped>
.exp-project-detail {
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: #fff;
}

.toolbar {
  margin-bottom: 5px;
  padding-bottom: 5px;
  border-bottom: 1px solid #EBEEF5;
  text-align: left;
}

.el-form-item {
  margin-bottom: 15px;
}

/* 只读状态的input样式 */
.el-input >>> input[readonly] {
  background-color: #F5F7FA;
  border-color: #DCDFE6;
  color: #606266;
  cursor: default;
}

.el-input >>> textarea[readonly] {
  background-color: #F5F7FA;
  border-color: #DCDFE6;
  color: #606266;
  cursor: default;
}

/* 禁用状态的日期选择器样式 */
.el-date-editor.is-disabled >>> .el-input__inner {
  background-color: #F5F7FA;
  border-color: #DCDFE6;
  color: #606266;
  cursor: default;
}

/* 调整label样式 */
.el-form-item >>> .el-form-item__label {
  font-size: 13px;
  color: #606266;
  font-weight: normal;
  padding-bottom: 5px;
}
</style>
