<template>
  <div class="exp-apply-form">
    <el-form
      :model="saveHeaderData"
      :rules="formRules"
      ref="applyForm"
      label-position="top"
      style="margin-left: 5px; margin-top: -5px;">

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="事业部" prop="buNo">
            <el-select
              v-model="saveHeaderData.buNo"
              :disabled="readonly || isEdit"
              placeholder="请选择事业部"
              style="width: 100%">
              <el-option
                v-for="i in buList"
                :key="i.buNo"
                :label="i.buDesc"
                :value="i.buNo">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="试验类型" prop="experimentType">
            <el-select
              v-model="saveHeaderData.experimentType"
              :disabled="readonly"
              placeholder="请选择试验类型"
              style="width: 100%">
              <el-option label="High Risk" value="High Risk"></el-option>
              <el-option label="Low Risk" value="Low Risk"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="试验单号" prop="applyNo">
            <el-input
              v-model="saveHeaderData.applyNo"
              :readonly="readonly || (isEdit && saveHeaderData.status !== '草稿' && saveHeaderData.status !== '已驳回')"
              placeholder="请输入试验单号">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目编号" prop="projectNo">
            <el-input
              v-model="saveHeaderData.projectNo"
              :readonly="readonly"
              placeholder="请输入项目编号">
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="期望完成日期" prop="expectedFinishDate">
            <el-date-picker
              v-model="saveHeaderData.expectedFinishDate"
              :disabled="readonly"
              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="12">
          <el-form-item label="试验名称" prop="title">
            <el-input
              v-model="saveHeaderData.title"
              :readonly="readonly"
              placeholder="请输入试验名称">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="试验负责人">
            <span v-if="!readonly" style="cursor: pointer" slot="label" @click="getBaseList(103)"><a href="#">试验负责人</a></span>
            <el-input v-model="saveHeaderData.projectLeader" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="PJM负责人">
            <el-select
              v-model="saveHeaderData.pjmLeaderUserId"
              :disabled="readonly"
              clearable
              filterable
              placeholder="请选择PJM负责人（非必填）"
              style="width: 100%"
              @change="handlePjmLeaderChange">
              <el-option
                v-for="item in pjmLeaderList"
                :key="item.userId"
                :label="item.userDisplay || item.username"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="试验目的" prop="purpose">
            <el-input
              v-model="saveHeaderData.purpose"
              :readonly="readonly"
              placeholder="请输入试验目的">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
<!--        <el-col :span="24">
          <el-form-item label="验证方法及判断标准" prop="justification">
            <el-input
              v-model="saveHeaderData.justification"
              :readonly="readonly"
              placeholder="请输入验证方法及判断标准">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="试验产品型号">
            <el-input
              v-model="saveHeaderData.productType"
              :readonly="readonly"
              placeholder="请输入产品型号">
            </el-input>
          </el-form-item>
        </el-col>-->

        <el-col :span="24">
          <el-form-item label="申请数量">
            <el-input
              v-model="saveHeaderData.quantityReq"
              :readonly="readonly"
              :rows="3" type="textarea"
              placeholder="请输入申请数量描述">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 45px">
        <el-col :span="24">
          <el-form-item label="工序">
            <el-input
              v-model="saveHeaderData.processRequirement"
              :readonly="readonly"
              type="textarea"
              :rows="3"
              placeholder="工序">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
<!--      <el-row :gutter="20">


&lt;!&ndash;        <el-col :span="12">
          <el-form-item label="联系方式">
            <el-input
              v-model="saveHeaderData.contactMethod"
              :readonly="readonly"
              placeholder="请输入联系方式">
            </el-input>
          </el-form-item>
        </el-col>&ndash;&gt;
      </el-row>-->

<!--      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="工艺、取样、测试要求">
            <el-input
              v-model="saveHeaderData.processRequirement"
              :readonly="readonly"
              type="textarea"
              :rows="3"
              placeholder="请输入工艺、取样、测试要求">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>-->

      <!-- 只读模式下显示的附加信息 -->
      <template v-if="readonly && saveHeaderData.applyNo">
        <el-divider content-position="left">试验单信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="试验单号">
              <span>{{ saveHeaderData.applyNo }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="状态">
              <el-tag :type="getStatusType(saveHeaderData.status)">
                {{ getStatusText(saveHeaderData.status) }}
              </el-tag>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="申请人">
              <span>{{ saveHeaderData.creatorName }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间">
              <span>{{ saveHeaderData.createTime }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="更新时间">
              <span>{{ saveHeaderData.updateTime }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </el-form>

    <!-- 用户选择弹窗 -->
    <Chooselist ref="baseList" @getBaseData="getBaseData"></Chooselist>
  </div>
</template>

<script>
import { saveExpApply, getPjmLeaderList } from '@/api/erf/erf'
import { getBuList } from '@/api/factory/site'
import Chooselist from '@/views/modules/common/Chooselist'

export default {
  name: 'ExpApplyForm',

  components: { Chooselist },

  props: {
    applyData: {
      type: Object,
      default: () => ({})
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      buList: [],
      pjmLeaderList: [],
      saveHeaderData: {
        applyNo: '',
        originalApplyNo: '',
        buNo: '',
        experimentType: '',
        projectNo: '',
        title: '',
        purpose: '',
        justification: '',
        productType: '',
        quantityReq: '',
        expectedFinishDate: '',
        projectLeaderName: this.$store.state.user.name,
        projectLeader: this.$store.state.user.userDisplay,
        pjmLeaderUserId: null,
        pjmLeaderName: '',
        contactMethod: '',
        processRequirement: '',
        creatorUserId: this.$store.state.user.id,
        creatorName: this.$store.state.user.userDisplay
      },

      formRules: {
        applyNo: [
          { required: true, message: '请输入试验单号', trigger: 'blur' }
        ],
        buNo: [
          { required: true, message: '请选择事业部', trigger: 'change' }
        ],
        experimentType: [
          { required: true, message: '请选择试验类型', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入试验名称', trigger: 'blur' }
        ],
        projectNo: [
          { required: true, message: '请输入项目编号', trigger: 'blur' }
        ],
        expectedFinishDate: [
          { required: true, message: '请选择期望完成日期', trigger: 'change' }
        ]
      },

      isEdit: false,
      tagNo: 0
    }
  },

  watch: {
    'saveHeaderData.buNo'(newVal, oldVal) {
      if (!newVal) {
        this.saveHeaderData.pjmLeaderUserId = null
        this.saveHeaderData.pjmLeaderName = ''
        // BU为空时回退查询全部PJM负责人
        this.loadPjmLeaderList('')
        return
      }
      if (newVal !== oldVal) {
        if (oldVal !== undefined && oldVal !== null && oldVal !== '') {
          this.saveHeaderData.pjmLeaderUserId = null
          this.saveHeaderData.pjmLeaderName = ''
        }
        this.loadPjmLeaderList(newVal)
      }
    }
  },

  mounted() {
    this.loadBuList()
    if (this.applyData && this.applyData.applyNo) {
      this.saveHeaderData = {
        ...this.applyData,
        originalApplyNo: this.applyData.applyNo
      }
      this.isEdit = true
    }
    // 首次打开弹窗时也查询一次PJM负责人（BU为空时查询全量）
    this.loadPjmLeaderList(this.saveHeaderData.buNo || '')
  },

  methods: {
    /**
     * 加载事业部列表
     */
    loadBuList() {
      const tempData = { site: this.$store.state.user.site }
      getBuList(tempData).then(({data}) => {
        if (data.code === 0) {
          this.buList = data.row1
          if (data.row1.length === 1) {
            this.saveHeaderData.buNo = data.row1[0].buNo
          }
        }
      })
    },

    /**
     * 加载PJM负责人列表（产品文档收美-PM角色）
     */
    loadPjmLeaderList(buNo) {
      getPjmLeaderList({ buNo: buNo || '' }).then(({data}) => {
        if (data && data.code === 0) {
          this.pjmLeaderList = data.list || []
          this.ensurePjmLeaderOption()
          if (this.saveHeaderData.pjmLeaderUserId && !this.saveHeaderData.pjmLeaderName) {
            this.handlePjmLeaderChange(this.saveHeaderData.pjmLeaderUserId)
          }
        } else {
          this.pjmLeaderList = []
          this.$message.error(data.msg || '加载PJM负责人失败')
        }
      }).catch(() => {
        this.pjmLeaderList = []
        this.$message.error('加载PJM负责人异常')
      })
    },

    /**
     * 处理PJM负责人变更
     */
    handlePjmLeaderChange(userId) {
      if (!userId) {
        this.saveHeaderData.pjmLeaderName = ''
        return
      }
      const selected = this.pjmLeaderList.find(item => item.userId === userId)
      this.saveHeaderData.pjmLeaderName = selected
        ? (selected.userDisplay || selected.username || '')
        : (this.saveHeaderData.pjmLeaderName || '')
    },

    /**
     * 编辑场景兜底：已选PJM负责人不在当前下拉项时补充显示
     */
    ensurePjmLeaderOption() {
      if (!this.saveHeaderData.pjmLeaderUserId) {
        return
      }
      const exist = this.pjmLeaderList.some(item => item.userId === this.saveHeaderData.pjmLeaderUserId)
      if (!exist && this.saveHeaderData.pjmLeaderName) {
        this.pjmLeaderList.push({
          userId: this.saveHeaderData.pjmLeaderUserId,
          username: this.saveHeaderData.pjmLeaderName,
          userDisplay: this.saveHeaderData.pjmLeaderName
        })
      }
    },

    /**
     * 获取表单数据（用于验证）
     */
    getFormData() {
      let valid = false
      this.$refs.applyForm.validate(v => {
        valid = v
      })
      return valid ? this.saveHeaderData : null
    },

    /**
     * 保存表单
     */
    save() {
      return new Promise((resolve, reject) => {
        this.$refs.applyForm.validate(valid => {
          if (!valid) {
            reject('表单验证失败')
            return
          }

          saveExpApply(this.saveHeaderData).then(({data}) => {
            if (data && data.code === 0) {
              resolve(data)
            } else {
              this.$message.error(data.msg || '保存失败')
              reject(data.msg)
            }
          }).catch(error => {
            reject(error)
          })
        })
      })
    },

    /**
     * 打开用户选择弹窗
     * @param val tagNo标识
     */
    getBaseList(val) {
      this.tagNo = val
      this.$nextTick(() => {
        let strVal = ''
        this.$refs.baseList.init(val, strVal, '')
      })
    },

    /**
     * 用户选择弹窗回调
     * @param val 选中的用户数据
     */
    getBaseData(val) {
      if (this.tagNo === 103) {
        this.saveHeaderData.projectLeaderName = val.username
        this.saveHeaderData.projectLeader = val.user_display
      }
    },

    /**
     * 获取状态类型
     */
    getStatusType(status) {
      const types = {
        '草稿': 'info',
        '已提交': 'warning',
        '已批准': 'success',
        '生产中': '',
        '已完成': 'success',
        '已取消': 'danger',
        '已驳回': 'danger'
      }
      return types[status] || 'info'
    },

    /**
     * 获取状态文本（直接返回中文状态）
     */
    getStatusText(status) {
      return status || ''
    }
  }
}
</script>

<style scoped>
.exp-apply-form {
  padding: 10px;
}
</style>
