<template>
  <ele-modal
    :title="dialogTitle"
    :visible.sync="visible"
    width="70%"
    :close-on-click-modal="false"
    :maxable="true"
    @closed="handleClose"
    custom-class="hazard-dialog"
    append-to-body
  >
    <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.code" 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
                  @change="categoryChange"
                >
                  <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.sourceType"
                  placeholder="请选择"
                  style="width: 100%"
                  disabled
                  clearable
                  @change="sourceTypeChange"
                >
                  <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.sourceName"
                  placeholder="请输入来源单据名称"
                  disabled
                  @click.native="addSource"
                  readonly
                />
              </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"
                  readonly
                  @click.native="userOpen('found')"
                  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"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="formData.category == 2">
            <el-col :span="12">
              <el-form-item label="区域" prop="areaId">
                <area-select
                  v-model="formData.areaId"
                  @checkedKeys="getAreaInfo"
                  :data="areaTreeList"
                  ref="tree"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="formData.category == 1">
            <el-col :span="12">
              <el-form-item label="设备名称" prop="deviceName">
                <el-input
                  v-model="formData.deviceName"
                  readonly
                  :disabled="!canEditReport || this.formData.sourceCode"
                  @click.native="$refs.MaterialAddRef.open()"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备编号" prop="deviceCode">
                <el-input
                  v-model="formData.deviceCode"
                  disabled
                  placeholder="自动带出"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="formData.category == 1">
            <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="请输入整改责任人"
                  @click.native="userOpen('fix')"
                  readonly
                  :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="选择计划整改截止时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :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
                  v-model="formData.fixBudget"
                  type="number"
                  :min="0"
                  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"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                />
              </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%"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                />
              </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">
            <DictSelection
              dictName="根因类型"
              clearable
              :disabled="!canEditFix"
              v-model="formData.rootCauseType"
            ></DictSelection>
            <!-- <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.fixPhotos"
              :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"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  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.verifyPhotos"
              :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 || dialogType == 'fix'"
        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>
    <userSelect ref="userSelectRef" @changeParent="changePersonel"></userSelect>
  </ele-modal>
</template>

<script>
  import userSelect from '@/components/user-select/user-select.vue';
  import { basicAreaPageAPI } from '@/api/factoryModel';

  import { save, getById } from '@/api/hazardManagement/index.js';
  export default {
    components: { userSelect },
    data() {
      return {
        visible: false,
        userKey: '',
        dialogType: 'add',
        activeTab: 'report',
        formData: this.getDefaultForm(),
        areaTreeList: [],
        levelOptions: [
          { value: 4, label: '轻微' },
          { value: 3, label: '一般' },
          { value: 2, label: '较大' },
          { value: 1, label: '重大' }
        ],
        chkTypeList: [
          { value: 1, label: '巡点检' },
          { value: 2, label: '设备保养' },
          { value: 3, label: '设备维修' },

          { value: 5, 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' },
            { required: true, message: '请输入整改责任人', trigger: 'change' }
          ],
          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';
      }
    },
    created() {
      this.getBasicAreaList();
    },
    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: '',
          fixPhotos: [],
          superviseFlag: 0,
          superviseLevel: '',
          supervisorId: '',
          verifyUserId: '',
          verifyUserName: '',
          verifyTime: '',
          verifyStandard: '',
          verifyResult: '',
          verifyComment: '',
          verifyPhotos: [],
          closeTime: '',
          closeUserId: '',
          closeUserName: '',
          govtReportFlag: 0,
          govtReportTime: '',
          govtReportNo: '',
          recurFlag: 0,
          prevId: '',
          suspendFlag: 0,
          areaName: '',
          areaId: null,
          areaCode: '',
          sourceName: '',
          sourceType: '',
          sourceId: '',
          sourceCode: ''
        };
      },
      categoryChange() {
        this.formData.deviceId = '';
        this.formData.deviceLocation = '';
        this.formData.deviceName = '';
        this.formData.deviceCode = '';
        this.formData.areaId = null;
        this.formData.areaName = '';
        this.formData.areaCode = '';
      },
      sourceTypeChange() {
        this.categoryChange();
        this.formData.sourceName = '';
        this.formData.sourceId = '';
        this.formData.sourceCode = '';
      },
      getAreaInfo(nodeInfo) {
        this.formData.areaName = nodeInfo[0]?.pathLabels.join('/') || '';
        this.formData.areaCode = nodeInfo[0]?.data.areaCode;
      },

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

        if (row && type != 'add') {
          this.formData = await getById(row.id);
          if (activeTab == 'verify') {
            this.formData.verifyUserName = this.$store.state.user.info.name;
            this.formData.verifyUserId = this.$store.state.user.info.userId;
          }
        } else {
          this.formData = this.getDefaultForm();

          this.formData.foundUserName = this.$store.state.user.info.name;
          this.formData.foundUserId = this.$store.state.user.info.userId;
          if (row) {
            console.log(row, 'dsds');
            this.formData.sourceType = row.sourceType;
            this.onPatrolConfirm(row);
          }
        }

        this.visible = true;
      },
      userOpen(key) {
        this.userKey = key;
        this.$refs.userSelectRef.open();
      },
      /* 获取区域集合 */
      async getBasicAreaList() {
        this.areaList = await basicAreaPageAPI({
          pageNum: 1,
          size: 9999
        });
        this.areaTreeList = this.$util.toTreeData({
          data: this.areaList,
          idField: 'id',
          parentIdField: 'parentId'
        });
      },
      changePersonel(data) {
        this.formData[this.userKey + 'UserName'] = data.name;
        this.formData[this.userKey + 'UserId'] = data.id;
      },
      handleSubmit() {
        this.$refs.reportForm.validate((valid) => {
          if (valid) {
            if (this.dialogType == 'fix') {
              this.formData.status = 2;
            }
            save(this.formData).then((res) => {
              this.$message.success('保存成功');
              this.visible = false;
              this.$emit('reload');
            });
          }
        });
      },

      handleSubmitFix() {
        this.$refs.fixForm.validate((valid) => {
          if (valid) {
            this.$confirm(
              '确认提交整改信息吗？提交后将进入待验收状态。',
              '提示',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }
            )
              .then(() => {
                rectify(this.formData).then((res) => {
                  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(() => {
                accept(this.formData).then((res) => {
                  this.$message.success('验收成功');
                  this.visible = false;
                  this.$emit('reload');
                });
              })
              .catch(() => {});
          }
        });
      },
      //设备回调
      chooseEquipment(data) {
        console.log(data, 'data');
        this.formData.deviceId = data.id;
        this.formData.deviceLocation = data.pathName;
        this.formData.deviceName = data.category.name;
        this.formData.deviceCode = data.codeNumber;
      },

      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);
      },

      addSource() {
        if (!this.formData.sourceType) {
          this.$message.error('请先选择来源类型');
          return;
        }
        this.$refs.patrolSelectRef.open(this.formData.sourceType);
      },
      onPatrolConfirm(data) {
        this.formData.category = 1;
        this.formData.sourceCode = data.sourceCode;
        this.formData.sourceId = data.sourceId;
        this.formData.sourceName = data.sourceName;
        const device = data.deviceList;
        if (device && device.substance) {
          this.formData.deviceId = device.substance.id || '';
          this.formData.deviceName = device.substance.name || '';
          this.formData.deviceCode = device.substance.codeNumber || '';
          this.formData.deviceLocation = device.substance.positionNames || '';
        }
      },
      handleClose() {
        this.formData = this.getDefaultForm();
        this.activeTab = 'report';
      }
    }
  };
</script>

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