<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="施工队伍" prop="deptName">
        <el-input v-model="displayData.deptName" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="项目" prop="contractName">
        <el-input v-model="displayData.contractName" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="任务" prop="taskName">
        <el-input v-model="displayData.taskName" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="搬迁安装天数(D)" prop="relocationDays">
        <el-input v-model="displayData.relocationDays" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="运行时效" prop="transitTime">
        <el-input v-model="displayTransitTime" placeholder="" disabled
                  :class="{'red-text': isTransitTimeOver}"
                  id="transitTimeInput" />
      </el-form-item>
      <el-form-item label="当日注气量(方)" prop="dailyGasInjection">
        <el-input v-model="formData.dailyGasInjection" placeholder="请输入当日注气量(方)" @change="calculateTransitTime"/>
      </el-form-item>
      <el-form-item label="当日注水量(方)" prop="dailyWaterInjection">
        <el-input v-model="formData.dailyWaterInjection" placeholder="请输入当日注水量(方)" />
      </el-form-item>
      <el-form-item label="当日注气时间(H)" prop="dailyInjectGasTime">
        <el-input v-model="formData.dailyInjectGasTime"
                  placeholder="请输入当日注气时间(H)"
                  :class="{'red-text': isTimeSumInvalid}"
                  @change="validateTimeSum" />
      </el-form-item>
      <el-form-item label="当日注水时间(H)" prop="dailyInjectWaterTime">
        <el-input v-model="formData.dailyInjectWaterTime"
                  placeholder="当日注水时间(H)"
                  :class="{'red-text': isTimeSumInvalid}"
                  @change="validateTimeSum" />
      </el-form-item>
      <el-form-item label="非生产时间(H)" prop="nonProductionTime">
        <el-input v-model="formData.nonProductionTime"
                  placeholder="非生产时间(H)"
                  :class="{'red-text': isTimeSumInvalid}"
                  @change="validateTimeSum" />
      </el-form-item>
      <el-form-item label="非生产时间原因" prop="nptReason">
        <el-select v-model="formData.nptReason" placeholder="请选择" clearable disabled>
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PMS_PROJECT_NPT_REASON)"
            :key="dict.id"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生产动态" prop="productionStatus">
        <el-input v-model="formData.productionStatus" placeholder="请输入生产动态" type="textarea"/>
      </el-form-item>
      <el-form-item label="累计注气量(万方)" prop="totalGasInjection">
        <el-input v-model="formData.totalGasInjection" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="累计注水量(方)" prop="totalWaterInjection">
        <el-input v-model="formData.totalWaterInjection" placeholder="请输入累计注水量(方)" disabled/>
      </el-form-item>
      <el-form-item label="累计完工井次" prop="cumulativeCompletion">
        <el-input v-model="formData.cumulativeCompletion" placeholder="请输入累计完工井次" disabled/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { IotRhDailyReportApi, IotRhDailyReportVO } from '@/api/pms/iotrhdailyreport'
import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";
import { computed, ref, watch, nextTick, reactive } from 'vue'

/** 瑞恒日报 表单 */
defineOptions({ name: 'IotRhDailyReportForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// 添加 props 接收行数据
const props = defineProps({
  rowData: {
    type: Object,
    default: () => ({})
  }
})

// 监听 props.rowData 的变化
watch(() => props.rowData, (newVal) => {
  if (newVal) {
    displayData.value.deptName = newVal.deptName || ''
    displayData.value.contractName = newVal.contractName || ''
    displayData.value.taskName = newVal.taskName || ''
    displayData.value.relocationDays = newVal.relocationDays || ''
  }
}, { immediate: true })

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

const isTimeSumInvalid = ref(false) // 时间总和的校验状态

// 添加显示数据对象
const displayData = ref({
  deptName: '',
  contractName: '',
  taskName: '',
  relocationDays: ''
})

const formData = ref({
  id: undefined,
  deptId: undefined,
  projectId: undefined,
  taskId: undefined,
  projectClassification: undefined,
  relocationDays: undefined,
  transitTime: undefined,
  dailyGasInjection: undefined,
  dailyWaterInjection: undefined,
  dailyInjectGasTime: undefined,
  dailyInjectWaterTime: undefined,
  nonProductionTime: undefined,
  nptReason: undefined,
  constructionStartDate: undefined,
  constructionEndDate: undefined,
  productionStatus: undefined,
  nextPlan: undefined,
  constructionStatus: undefined,
  personnel: undefined,
  totalGasInjection: undefined,
  totalWaterInjection: undefined,
  cumulativeCompletion: undefined,
  extProperty: undefined,
  sort: undefined,
  remark: undefined,
  status: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
  capacity: undefined
})
const formRules = reactive({
  dailyInjectGasTime: [
    { validator: validateTimeField, trigger: 'change' }
  ],
  dailyInjectWaterTime: [
    { validator: validateTimeField, trigger: 'change' }
  ],
  nonProductionTime: [
    { validator: validateTimeField, trigger: 'change' }
  ]
})

// 时间字段校验器
function validateTimeField(rule: any, value: any, callback: any) {
  if (value === undefined || value === null || value === '') {
    callback()
    return
  }

  const numValue = Number(value)
  if (isNaN(numValue)) {
    callback(new Error('请输入有效的数字'))
  } else if (numValue < 0) {
    callback(new Error('时间不能为负数'))
  } else {
    callback()
  }
}

const formRef = ref() // 表单 Ref

// 计算运行时效的显示值和颜色
const displayTransitTime = computed(() => {
  if (!formData.value.transitTime) return ''
  return `${(formData.value.transitTime * 100).toFixed(2)}%`
})

const transitTimeColor = computed(() => {
  console.log('当前运行时效的值是否大于1.2：' + (parseFloat(formData.value.transitTime) > 1.2))
  return formData.value.transitTime && parseFloat(formData.value.transitTime) > 1.2 ? 'red' : ''
})

// 修改为返回布尔值的计算属性，便于在模板中使用class绑定
const isTransitTimeOver = computed(() => {
  const transitTime = Number(formData.value.transitTime)
  console.log('运行时效值:', transitTime, '是否大于1.2:', transitTime > 1.2)
  return transitTime > 1.2
})

// 计算运行时效的方法
const calculateTransitTime = () => {
  if (!formData.value.capacity) {
    message.error('请维护增压机产能')
    return
  }

  if (formData.value.dailyGasInjection) {
    const dailyGas = parseFloat(formData.value.dailyGasInjection)
    const capacity = parseFloat(formData.value.capacity)
    formData.value.transitTime = dailyGas / capacity
  } else {
    formData.value.transitTime = 0
  }
}

// 验证三个时间字段的总和
const validateTimeSum = () => {
  const gasTime = Number(formData.value.dailyInjectGasTime) || 0
  const waterTime = Number(formData.value.dailyInjectWaterTime) || 0
  const nonProdTime = Number(formData.value.nonProductionTime) || 0

  const total = gasTime + waterTime + nonProdTime
  isTimeSumInvalid.value = total !== 24

  return total === 24
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 设置显示数据
  if (props.rowData) {
    displayData.value.deptName = props.rowData.deptName || ''
    displayData.value.contractName = props.rowData.contractName || ''
    displayData.value.taskName = props.rowData.taskName || ''
    displayData.value.relocationDays = props.rowData.relocationDays || ''
  }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await IotRhDailyReportApi.getIotRhDailyReport(id)
      // 检查产能是否存在
      if (!formData.value.capacity) {
        message.error('请维护增压机产能')
      } else {
        // 计算运行时效
        calculateTransitTime()
      }
      // 验证时间总和
      validateTimeSum()
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 检查产能
  if (!formData.value.capacity) {
    message.error('请维护增压机产能')
    return
  }

  // 检查时间总和
  if (!validateTimeSum()) {
    message.error('当日注气时间、注水时间和非生产时间之和必须等于24小时')
    return
  }

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as IotRhDailyReportVO
    if (formType.value === 'create') {
      await IotRhDailyReportApi.createIotRhDailyReport(data)
      message.success(t('common.createSuccess'))
    } else {
      await IotRhDailyReportApi.updateIotRhDailyReport(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deptId: undefined,
    projectId: undefined,
    taskId: undefined,
    projectClassification: undefined,
    relocationDays: undefined,
    transitTime: undefined,
    dailyGasInjection: undefined,
    dailyWaterInjection: undefined,
    dailyInjectGasTime: undefined,
    dailyInjectWaterTime: undefined,
    nonProductionTime: undefined,
    nptReason: undefined,
    constructionStartDate: undefined,
    constructionEndDate: undefined,
    productionStatus: undefined,
    nextPlan: undefined,
    constructionStatus: undefined,
    personnel: undefined,
    totalGasInjection: undefined,
    totalWaterInjection: undefined,
    cumulativeCompletion: undefined,
    extProperty: undefined,
    sort: undefined,
    remark: undefined,
    status: undefined,
    processInstanceId: undefined,
    auditStatus: undefined,
    capacity: undefined
  }

  displayData.value = {
    deptName: '',
    contractName: '',
    taskName: '',
    relocationDays: ''
  }

  isTimeSumInvalid.value = false

  formRef.value?.resetFields()
}
</script>

<style scoped>
/* 添加红色文本样式，使用深度选择器覆盖Element UI的disabled状态样式 */
:deep(.red-text .el-input__inner) {
  color: red !important;
  -webkit-text-fill-color: red !important;
}
</style>
