<template>
  <div class="monthly-report-add">
    <el-form
      ref="formRef"
      :model="reportInfo"
      :rules="formRules"
      label-width="auto"
      class="report-form">
      <!-- 1. 基本信息 -->
      <el-card class="form-section" shadow="hover">
        <template #header>
          <div class="section-header">
            <Icon icon="ep:document" class="mr-5px" />
            <span>基本信息</span>
          </div>
        </template>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="部门名称" prop="deptId">
              <el-tree-select
                clearable
                disabled
                v-model="reportInfo.deptId"
                :data="deptList2"
                :props="defaultProps"
                :check-strictly="false"
                node-key="id"
                filterable
                placeholder="请选择所属队伍" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="月报标题" prop="title">
              <el-input disabled v-model="reportInfo.title" placeholder="请输入月报标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="年月" prop="yearMonths">
              <el-date-picker
                disabled
                v-model="reportInfo.yearMonths"
                type="month"
                placeholder="选择年月"
                format="YYYY-MM"
                value-format="YYYY-MM"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 2. 人工时和安全行驶公里数 -->
      <el-card class="form-section" shadow="hover">
        <template #header>
          <div class="section-header">
            <Icon icon="ep:user" class="mr-5px" />
            <span>人工时和安全行驶公里数</span>
          </div>
        </template>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="员工人数" prop="employee">
              <el-input-number
                v-model="reportInfo.employee"
                :min="0"
                disabled
                :precision="0"
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="分包商人数" prop="subcontractors">
              <el-input-number
                v-model="reportInfo.subcontractors"
                :min="0"
                disabled
                :precision="0"
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="安全行驶里程数（公里）" prop="drivingMileage">
              <el-input-number
                v-model="reportInfo.drivingMileage"
                :min="0"
                disabled
                :precision="2"
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="总人工时数（小时）" prop="totalManHours">
              <el-input-number
                v-model="reportInfo.totalManHours"
                :min="0"
                disabled
                :precision="2"
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 3. QHSE被动性指标统计 -->
      <el-card class="form-section" shadow="hover">
        <template #header>
          <div class="section-header">
            <Icon icon="ep:warning" class="mr-5px" />
            <span>QHSE被动性指标统计</span>
          </div>
        </template>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="无事故累计天数" prop="withoutAccident">
              <el-input-number
                v-model="reportInfo.withoutAccident"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="死亡事故（起）" prop="fatality">
              <el-input-number
                v-model="reportInfo.fatality"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="损失工时事故（起）" prop="injury">
              <el-input-number
                v-model="reportInfo.injury"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="工作受限事件（起）" prop="restrictedCase">
              <el-input-number
                v-model="reportInfo.restrictedCase"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="医疗处理事件（起）" prop="medicalCase">
              <el-input-number
                v-model="reportInfo.medicalCase"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="急救箱事件（起）" prop="firstAidCase">
              <el-input-number
                v-model="reportInfo.firstAidCase"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="交通事故（起）" prop="vehicleAccident">
              <el-input-number
                v-model="reportInfo.vehicleAccident"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="未遂事件（起）" prop="nearMiss">
              <el-input-number
                v-model="reportInfo.nearMiss"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="泄漏事件（起）" prop="spill">
              <el-input-number
                v-model="reportInfo.spill"
                :min="0"
                disabled
                :precision="0"
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="违反保命规则的次数（次）" prop="lifeSavingRules">
              <el-input-number
                v-model="reportInfo.lifeSavingRules"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 4. QHSE主动性指标统计 -->
      <el-card class="form-section" shadow="hover">
        <template #header>
          <div class="section-header">
            <Icon icon="ep:checked" class="mr-5px" />
            <span>QHSE主动性指标统计</span>
          </div>
        </template>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="班前会（次）" prop="toolboxTalk">
              <el-input-number
                v-model="reportInfo.toolboxTalk"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="QHSE管理委员会会议（次）" prop="committeeMeeting">
              <el-input-number
                v-model="reportInfo.committeeMeeting"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="QHSE月度例会（次）" prop="monthlyMeeting">
              <el-input-number
                v-model="reportInfo.monthlyMeeting"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="公司级隐患排查（次）" prop="companyHazard">
              <el-input-number
                v-model="reportInfo.companyHazard"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="QHSE检查（次）" prop="qhseInspection">
              <el-input-number
                v-model="reportInfo.qhseInspection"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="安全观察卡（张）" prop="socCards">
              <el-input-number
                v-model="reportInfo.socCards"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="工作许可审核（份）" prop="ptwAudit">
              <el-input-number
                v-model="reportInfo.ptwAudit"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="工作安全分析（次）" prop="jsa">
              <el-input-number
                v-model="reportInfo.jsa"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="演练次数" prop="drills">
              <el-input-number
                v-model="reportInfo.drills"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="QHSE培训次数" prop="training">
              <el-input-number
                v-model="reportInfo.training"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="QHSE培训人次" prop="participantsTraining">
              <el-input-number
                v-model="reportInfo.participantsTraining"
                :min="0"
                :precision="0"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="QHSE培训学时数（小时）" prop="trainingsHours">
              <el-input-number
                v-model="reportInfo.trainingsHours"
                :min="0"
                :precision="2"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 5. 环境数据 -->
      <el-card class="form-section" shadow="hover">
        <template #header>
          <div class="section-header">
            <Icon icon="ep:sunrise" class="mr-5px" />
            <span>环境数据</span>
          </div>
        </template>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="水消耗（吨）" prop="waterConsumption">
              <el-input-number
                v-model="reportInfo.waterConsumption"
                :min="0"
                :precision="2"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="柴油消耗（升）" prop="dieselConsumption">
              <el-input-number
                v-model="reportInfo.dieselConsumption"
                :min="0"
                :precision="2"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="用电量（千瓦·小时）" prop="electricityConsumption">
              <el-input-number
                v-model="reportInfo.electricityConsumption"
                :min="0"
                :precision="2"
                disabled
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="天然气消耗量（立方米）" prop="naturalGasConsumption">
              <el-input-number
                v-model="reportInfo.naturalGasConsumption"
                :min="0"
                disabled
                :precision="2"
                controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 6. 其他信息 -->
      <el-card class="form-section" shadow="hover">
        <template #header>
          <div class="section-header">
            <Icon icon="ep:info-filled" class="mr-5px" />
            <span>其他信息</span>
          </div>
        </template>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="工单填报人" prop="dutyPerson">
              <el-select
                v-model="reportInfo.dutyPerson"
                filterable
                clearable
                disabled
                placeholder="请选择填报人"
                style="width: 100%">
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="reportInfo.remark"
                type="textarea"
                disabled
                :rows="4"
                placeholder="请输入备注信息" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="handleCancel">返 回</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { FormInstance, FormRules } from 'element-plus'
import { QhseMonthReportApi } from '@/api/pms/qhse'
import { handleTree, defaultProps } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import { getUserProfile } from '@/api/system/user/profile'
import { useTagsViewStore } from '@/store/modules/tagsView'
const { delView } = useTagsViewStore()

defineOptions({ name: 'MonthlyReportAdd' })

const router = useRouter()
const route = useRoute()
const message = useMessage()
const deptList2 = ref<Tree[]>([]) // 树形结构
const userList = ref<any[]>([])

// 表单引用
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
let reportInfo = reactive({
  title: '',
  yearMonths: '',
  deptId: 0,
  employee: '0',
  subcontractors: '0',
  drivingMileage: '0',
  totalManHours: '0',
  withoutAccident: '0',
  fatality: '0',
  injury: '0',
  restrictedCase: '0',
  medicalCase: '0',
  firstAidCase: '0',
  vehicleAccident: '0',
  nearMiss: '0',
  spill: '0',
  lifeSavingRules: '0',
  toolboxTalk: '0',
  committeeMeeting: '0',
  monthlyMeeting: '0',
  companyHazard: '0',
  qhseInspection: '0',
  socCards: '0',
  ptwAudit: '0',
  jsa: '0',
  drills: '0',
  training: '0',
  participantsTraining: '0',
  trainingsHours: '0',
  waterConsumption: '0',
  dieselConsumption: '0',
  electricityConsumption: '0',
  naturalGasConsumption: '0',
  dutyPerson: 0,
  remark: ''
})

// 表单校验规则
const formRules = reactive<FormRules>({
  title: [{ required: true, message: '月报标题不能为空', trigger: 'blur' }],
  yearMonth: [{ required: true, message: '年月不能为空', trigger: 'change' }],
  deptId: [{ required: true, message: '部门不能为空', trigger: 'change' }],
  dutyPerson: [{ required: true, message: '工单填报人不能为空', trigger: 'change' }]
})

// 部门名称显示
const deptName = ref('')

/** 提交表单 */
const handleSubmit = async () => {
  if (!formRef.value) return

  // 校验表单
  const valid = await formRef.value.validate()
  if (!valid) return

  submitLoading.value = true
  try {
    await QhseMonthReportApi.createQhseMonthReport(reportInfo)
    message.success('新增成功')
    // 返回列表页或上一页
    router.back()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

/** 取消 */
const handleCancel = () => {
  delView(unref(router.currentRoute))
  router.push({ name: 'QhseMonthlyReport', params: {} })
}

const userInfo = ref<any>({})
onMounted(async () => {
  const users = await getUserProfile()
  userInfo.value = users
  deptList2.value = handleTree(await DeptApi.getSimpleDeptList())
  userList.value = await UserApi.selectedDeptsEmployee({
    deptIds: userInfo.value.dept.id
  })
  const res = await QhseMonthReportApi.getQhseMonthReport(route.params.id)
  const data = (res as any)?.data ?? res ?? {}

  Object.assign(reportInfo, data)
})
</script>
<style scoped lang="scss">
.monthly-report-add {
  padding: 12px;
  min-height: 100vh;
  background-color: #f5f7fa;

  .report-form {
    max-width: 1400px;
    margin: 0 auto;

    .form-section {
      margin-bottom: 16px;
      border-radius: 8px;

      :deep(.el-card__header) {
        padding: 12px 16px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 8px 8px 0 0;
      }

      :deep(.el-card__body) {
        padding: 16px;
      }

      .section-header {
        display: flex;
        align-items: center;
        font-size: 15px;
        font-weight: 600;
      }

      :deep(.el-form-item) {
        margin-bottom: 16px;
      }

      :deep(.el-form-item__label) {
        font-size: 14px;
        line-height: 1.5;
      }

      :deep(.el-input),
      :deep(.el-input-number),
      :deep(.el-date-editor) {
        width: 100%;
      }

      :deep(.el-input-number) {
        .el-input__inner {
          text-align: left;
        }
      }
    }

    .form-actions {
      display: flex;
      justify-content: center;
      gap: 12px;
      padding: 16px 0;
      margin-top: 16px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      position: sticky;
      bottom: 0;
      z-index: 10;

      .el-button {
        min-width: 100px;
        flex: 1;
        max-width: 150px;
        height: 44px;
        font-size: 15px;
      }
    }
  }
}

// 移动端优化
@media screen and (max-width: 768px) {
  .monthly-report-add {
    padding: 8px;

    .report-form {
      .form-section {
        margin-bottom: 12px;

        :deep(.el-card__header) {
          padding: 10px 12px;
        }

        :deep(.el-card__body) {
          padding: 12px;
        }

        .section-header {
          font-size: 14px;
        }

        :deep(.el-form-item__label) {
          font-size: 13px;
          padding-right: 8px;
        }

        :deep(.el-input__inner),
        :deep(.el-textarea__inner) {
          font-size: 14px;
          min-height: 40px;
        }

        :deep(.el-input-number) {
          .el-input-number__decrease,
          .el-input-number__increase {
            width: 32px;
            height: 40px;
            line-height: 40px;
          }

          .el-input__inner {
            height: 40px;
            line-height: 40px;
          }
        }

        :deep(.el-date-editor) {
          .el-input__inner {
            height: 40px;
            line-height: 40px;
          }
        }
      }

      .form-actions {
        padding: 12px;
        gap: 10px;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        margin: 0;
        border-radius: 0;
        box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);

        .el-button {
          height: 44px;
          font-size: 15px;
        }
      }
    }
  }
}

// 超小屏幕优化
@media screen and (max-width: 480px) {
  .monthly-report-add {
    padding: 6px;

    .report-form {
      .form-section {
        :deep(.el-card__body) {
          padding: 10px;
        }

        :deep(.el-form-item) {
          margin-bottom: 12px;
        }

        :deep(.el-form-item__label) {
          font-size: 12px;
        }

        :deep(.el-input__inner),
        :deep(.el-textarea__inner) {
          font-size: 13px;
        }
      }
    }
  }
}

:deep(.el-input.is-disabled) {
  .el-input__inner {
    color: #606266 !important;
    -webkit-text-fill-color: #606266 !important;
  }
}

:deep(.el-textarea.is-disabled) {
  .el-textarea__inner {
    color: #606266 !important;
    -webkit-text-fill-color: #606266 !important;
  }
}
</style>
