<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="visible"
    width="1000px"
    :close-on-click-modal="false"
    @closed="handleClose"
    custom-class="hazard-dialog"
  >
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 上报信息 -->
      <el-tab-pane label="上报信息" name="report">
        <el-form
          ref="reportForm"
          :model="formData"
          :rules="reportRules"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="隐患编号">
                <el-input v-model="formData.no" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="隐患名称" prop="title">
                <el-input
                  v-model="formData.title"
                  placeholder="请输入隐患名称"
                  :disabled="!canEditReport"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="隐患等级" prop="level">
                <el-select
                  v-model="formData.level"
                  placeholder="请选择"
                  style="width: 100%"
                  :disabled="!canEditReport"
                >
                  <el-option
                    v-for="item in levelOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="隐患类别" prop="category">
                <el-select
                  v-model="formData.category"
                  placeholder="请选择"
                  style="width: 100%"
                  :disabled="!canEditReport"
                >
                  <el-option
                    v-for="item in categoryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="来源类型">
                <el-select
                  v-model="formData.chkType"
                  placeholder="请选择"
                  style="width: 100%"
                  :disabled="!canEditReport"
                >
                  <el-option
                    v-for="item in chkTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="来源单据名称">
                <el-input
                  v-model="formData.chkId"
                  placeholder="请输入来源单据名称"
                  :disabled="!canEditReport"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="发现人" prop="foundUserName">
                <el-input
                  v-model="formData.foundUserName"
                  placeholder="请输入发现人"
                  :disabled="!canEditReport"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发现时间" prop="foundTime">
                <el-date-picker
                  v-model="formData.foundTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  :disabled="!canEditReport"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="设备编码" prop="deviceId">
                <el-input
                  v-model="formData.deviceId"
                  :disabled="!canEditReport"
                  placeholder="请输入设备编码"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备名称" prop="deviceName">
                <el-input
                  v-model="formData.deviceName"
                  placeholder="请输入设备名称"
                  :disabled="!canEditReport"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="设备位置" prop="deviceLocation">
                <el-input
                  v-model="formData.deviceLocation"
                  placeholder="请输入设备位置"
                  :disabled="!canEditReport"
                /> </el-form-item></el-col
          ></el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="整改责任人" prop="fixUserName">
                <el-input
                  v-model="formData.fixUserName"
                  placeholder="请输入整改责任人"
                  :disabled="!canEditReport"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划整改时限" prop="fixDeadline">
                <el-date-picker
                  v-model="formData.fixDeadline"
                  type="datetime"
                  placeholder="选择计划整改截止时间"
                  :disabled="!canEditReport"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="隐患描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              :disabled="!canEditReport"
              placeholder="请输入隐患详细描述"
            />
          </el-form-item>

          <el-form-item label="可能导致后果" prop="consequence">
            <el-input
              v-model="formData.consequence"
              type="textarea"
              :disabled="!canEditReport"
              :rows="2"
              placeholder="请输入可能导致的事故后果"
            />
          </el-form-item>

          <el-form-item label="上报附件">
            <fileMain
              v-model="formData.reportAttachments"
              :type="canEditReport ? '' : 'view'"
            ></fileMain>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 整改信息 -->
      <el-tab-pane label="整改信息" name="fix" :disabled="isAdd">
        <el-form
          ref="fixForm"
          :model="formData"
          :rules="fixRules"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="整改资金(元)" prop="fixBudget">
                <el-input-number
                  v-model="formData.fixBudget"
                  :min="0"
                  :precision="2"
                  style="width: 100%"
                  :disabled="!canEditFix"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实际整改开始">
                <el-date-picker
                  v-model="formData.fixStart"
                  type="datetime"
                  placeholder="选择实际开始时间 "
                  style="width: 100%"
                  :disabled="!canEditFix"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="实际整改完成">
                <el-date-picker
                  v-model="formData.fixEnd"
                  type="datetime"
                  placeholder="选择实际完成时间"
                  :disabled="!canEditFix"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="整改措施" prop="fixMeasures">
            <el-input
              v-model="formData.fixMeasures"
              type="textarea"
              :rows="3"
              :disabled="!canEditFix"
              placeholder="请输入具体整改措施"
            />
          </el-form-item>

          <el-form-item label="根因类型" prop="rootCauseType">
            <el-select
              v-model="formData.rootCauseType"
              placeholder="请选择"
              style="width: 100%"
              :disabled="!canEditFix"
            >
              <el-option label="磨损" value="1" />
              <el-option label="松动" value="2" />
              <el-option label="腐蚀" value="3" />
              <el-option label="过载" value="4" />
              <el-option label="操作不当" value="5" />
              <el-option label="外部因素" value="6" />
              <el-option label="未知" value="7" />
            </el-select>
          </el-form-item>

          <el-form-item label="根因分析" prop="rootCauseAnalysis">
            <el-input
              v-model="formData.rootCauseAnalysis"
              type="textarea"
              :rows="3"
              :disabled="!canEditFix"
              placeholder="请输入隐患根因分析"
            />
          </el-form-item>

          <el-form-item label="整改附件">
            <fileMain
              v-model="formData.fixAttachments"
              :type="canEditFix ? '' : 'view'"
            ></fileMain>
          </el-form-item>

          <!-- <el-form-item label="挂牌督办">
            <el-radio-group v-model="formData.superviseFlag" :disabled="!canEditFix">
              <el-radio :label="0">未挂牌</el-radio>
              <el-radio :label="1">已挂牌</el-radio>
            </el-radio-group>
          </el-form-item> -->

          <!-- <el-row :gutter="20" v-if="formData.superviseFlag === 1">
            <el-col :span="12">
              <el-form-item label="督办层级">
                <el-select v-model="formData.superviseLevel" placeholder="请选择" style="width: 100%">
                  <el-option label="企业级" value="ENTERPRISE" />
                  <el-option label="部门级" value="DEPT" />
                  <el-option label="集团级" value="GROUP" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="督办人">
                <el-input v-model="formData.supervisorId" placeholder="请输入督办人" />
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>
      </el-tab-pane>

      <!-- 验收信息 -->
      <el-tab-pane label="验收信息" name="verify" :disabled="isAdd || isFixing">
        <el-form
          ref="verifyForm"
          :model="formData"
          :rules="verifyRules"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="验收人" prop="verifyUserName">
                <el-input
                  v-model="formData.verifyUserName"
                  placeholder="请输入验收人姓名"
                  :disabled="!canEditVerify"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="验收时间" prop="verifyTime">
                <el-date-picker
                  v-model="formData.verifyTime"
                  type="datetime"
                  :disabled="!canEditVerify"
                  placeholder="选择验收时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="验收结果" prop="verifyResult">
                <el-select
                  v-model="formData.verifyResult"
                  placeholder="请选择"
                  style="width: 100%"
                  :disabled="!canEditVerify"
                >
                  <el-option label="合格" value="1" />
                  <el-option label="不合格" value="2" />
                  <el-option label="部分合格" value="3" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- <el-form-item label="验收标准" prop="verifyStandard">
            <el-input
              v-model="formData.verifyStandard"
              type="textarea"
              :rows="2"
              placeholder="请输入验收合格判定标准"
            />
          </el-form-item> -->

          <el-form-item label="验收意见" prop="verifyComment">
            <el-input
              v-model="formData.verifyComment"
              type="textarea"
              :disabled="!canEditVerify"
              :rows="3"
              placeholder="请输入验收人员意见说明"
            />
          </el-form-item>

          <el-form-item label="验收附件">
            <fileMain
              v-model="formData.verifyAttachments"
              :type="canEditVerify ? '' : 'view'"
            ></fileMain>
          </el-form-item>

          <!-- <el-form-item label="销号时间">
            <el-date-picker
              v-model="formData.closeTime"
              type="datetime"
              placeholder="选择销号时间"
              style="width: 100%"
            />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="销号人">
                <el-input v-model="formData.closeUserName" placeholder="请输入销号人姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="政府上报">
                <el-radio-group v-model="formData.govtReportFlag">
                  <el-radio :label="0">不上报</el-radio>
                  <el-radio :label="1">已上报</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <div slot="footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button v-if="canEditReport" type="primary" @click="handleSubmit"
        >保存</el-button
      >
      <el-button
        v-if="dialogType === 'fix'"
        type="success"
        @click="handleSubmitFix"
        >提交整改</el-button
      >
      <el-button
        v-if="dialogType === 'verify'"
        type="success"
        @click="handleSubmitVerify"
        >提交验收</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
  export default {
    data() {
      return {
        visible: false,
        dialogType: 'add',
        activeTab: 'report',
        formData: this.getDefaultForm(),
        levelOptions: [
          { value: '1', label: '轻微' },
          { value: '2', label: '一般' },
          { value: '3', label: '较大' },
          { value: '4', label: '重大' }
        ],
        chkTypeList: [
          { value: '1', label: '设备保养' },
          { value: '2', label: '设备维修' },
          { value: '3', label: '巡点检' },
          { value: '4', label: '量具送检' }
        ],
        categoryOptions: [
          { value: '1', label: '设备设施' },
          { value: '2', label: '作业环境' },
          { value: '3', label: '人员行为' },
          { value: '4', label: '管理缺陷' },
          { value: '5', label: '其他' }
        ],
        reportRules: {
          title: [
            { required: true, message: '请输入隐患名称', trigger: 'blur' }
          ],
          level: [
            { required: true, message: '请选择隐患等级', trigger: 'change' }
          ],
          category: [
            { required: true, message: '请选择隐患类别', trigger: 'change' }
          ],
          foundTime: [
            { required: true, message: '请选择发现时间', trigger: 'change' }
          ],
          // deviceName: [
          //   { required: true, message: '请输入设备名称', trigger: 'blur' }
          // ],
          description: [
            { required: true, message: '请输入隐患描述', trigger: 'blur' }
          ],
          fixUserName: [
            { required: true, message: '请输入整改责任人', trigger: 'blur' }
          ],
          fixDeadline: [
            { required: true, message: '请选择计划整改时限', trigger: 'change' }
          ]
        },
        fixRules: {
          fixMeasures: [
            { required: true, message: '请输入整改措施', trigger: 'blur' }
          ]
        },
        verifyRules: {
          verifyUserName: [
            { required: true, message: '请输入验收人', trigger: 'blur' }
          ],
          verifyTime: [
            { required: true, message: '请选择验收时间', trigger: 'change' }
          ],
          verifyResult: [
            { required: true, message: '请选择验收结果', trigger: 'change' }
          ]
        }
      };
    },

    computed: {
      dialogTitle() {
        const titleMap = {
          add: '新增隐患',
          edit: '编辑隐患',
          view: '查看隐患',
          fix: '隐患整改',
          verify: '隐患验收'
        };
        return titleMap[this.dialogType] || '隐患详情';
      },
      isAdd() {
        return this.dialogType === 'add';
      },
      isFixing() {
        return this.dialogType === 'fix';
      },
      canEditReport() {
        return ['add', 'edit'].includes(this.dialogType);
      },
      canEditFix() {
        return this.dialogType === 'fix';
      },
      canEditVerify() {
        return this.dialogType === 'verify';
      }
    },

    methods: {
      getDefaultForm() {
        return {
          no: '',
          title: '',
          level: '',
          category: '',
          type: '',
          foundTime: '',
          deviceId: '',
          deviceName: '',
          deviceLocation: '',
          description: '',
          foundUserId: '',
          foundUserName: '',
          chkId: '',
          tskId: '',
          abnEventId: '',
          consequence: '',
          reportAttachments: [],
          rootCauseType: '',
          rootCauseAnalysis: '',
          fixUserId: '',
          fixUserName: '',
          fixMeasures: '',
          fixBudget: 0,
          fixDeadline: '',
          fixStart: '',
          fixEnd: '',
          fixProcessLog: null,
          fixAttachments: [],
          superviseFlag: 0,
          superviseLevel: '',
          supervisorId: '',
          verifyUserId: '',
          verifyUserName: '',
          verifyTime: '',
          verifyStandard: '',
          verifyResult: '',
          verifyComment: '',
          verifyAttachments: [],
          closeTime: '',
          closeUserId: '',
          closeUserName: '',
          govtReportFlag: 0,
          govtReportTime: '',
          govtReportNo: '',
          recurFlag: 0,
          prevId: ''
        };
      },

      open(type, row) {
        this.dialogType = type;
        this.activeTab = 'report';

        if (row) {
          this.formData = { ...this.getDefaultForm(), ...row };
        } else {
          this.formData = this.getDefaultForm();
          this.formData.foundTime = new Date();
        }

        this.visible = true;
      },

      handleSubmit() {
        this.$refs.reportForm.validate((valid) => {
          if (valid) {
            this.$message.success('保存成功');
            this.visible = false;
            this.$emit('reload');
          }
        });
      },

      handleSubmitFix() {
        this.$refs.fixForm.validate((valid) => {
          if (valid) {
            this.$confirm(
              '确认提交整改信息吗？提交后将进入待验收状态。',
              '提示',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }
            )
              .then(() => {
                this.formData.status = 'PENDING_VERIFY';
                this.formData.fixEnd = new Date();
                this.$message.success('整改提交成功');
                this.visible = false;
                this.$emit('reload');
              })
              .catch(() => {});
          }
        });
      },

      handleSubmitVerify() {
        this.$refs.verifyForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交验收信息吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                const isPass = this.formData.verifyResult === 'PASS';
                this.formData.status = isPass ? 'VERIFIED' : 'FIXING';
                if (isPass) {
                  this.formData.closeTime = new Date();
                  this.formData.closureDays = this.calculateClosureDays();
                }
                this.$message.success(
                  isPass ? '验收通过' : '验收不通过，退回整改'
                );
                this.visible = false;
                this.$emit('reload');
              })
              .catch(() => {});
          }
        });
      },

      calculateClosureDays() {
        if (!this.formData.foundTime || !this.formData.closeTime) return 0;
        const found = new Date(this.formData.foundTime);
        const close = new Date(this.formData.closeTime);
        return ((close - found) / (1000 * 60 * 60 * 24)).toFixed(1);
      },

      handleClose() {
        this.formData = this.getDefaultForm();
        this.activeTab = 'report';
      }
    }
  };
</script>

<style lang="scss" scoped>
  .hazard-dialog {
    ::v-deep .el-dialog__body {
      padding: 10px 20px;
    }
  }
</style>
