<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      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="t('project.status')" prop="repairStatus">
        <el-select v-model="formData.repairStatus" placeholder="请选择" clearable>
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PMS_PROJECT_TASK_RY_REPAIR_SCHEDULE)"
            :key="dict.id"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('project.technology')" prop="technique">
        <el-select v-model="displayData.technique" placeholder="请选择" >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PMS_PROJECT_RY_TECHNOLOGY)"
            :key="dict.id"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="井别" prop="wellCategory">
        <el-input v-model="displayData.wellCategory" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="设计井深(m)" prop="designWellDepth">
        <el-input v-model="displayData.designWellDepth" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="井控级别" prop="wellControlLevel">
        <el-input v-model="displayData.wellControlLevel" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="套生段产管尺寸(mm)" prop="casingPipeSize">
        <el-input v-model="displayData.casingPipeSize" placeholder="" disabled/>
      </el-form-item>
      <!--
      <el-form-item label="当前井深(m)" prop="currentDepth">
        <el-input v-model="formData.currentDepth" placeholder="请输入当前井深(m)" />
      </el-form-item>
      <el-form-item label="日进尺(m)" prop="dailyFootage">
        <el-input v-model="formData.dailyFootage" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="月进尺(m)" prop="monthlyFootage">
        <el-input v-model="formData.monthlyFootage" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="年累计进尺(m)" prop="annualFootage">
        <el-input v-model="formData.annualFootage" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="当日用电量(kWh)" prop="dailyPowerUsage">
        <el-input v-model="formData.dailyPowerUsage" placeholder="请输入当日用电量(kWh)" />
      </el-form-item>
      <el-form-item label="当日油耗(吨)" prop="dailyFuel">
        <el-input v-model="formData.dailyFuel" placeholder="请输入当日油耗(吨)" />
      </el-form-item> -->
      <el-form-item label="总施工井数" prop="monthlyFuel">
        <el-input v-model="displayData.totalConstructionWells" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="完工井数" prop="completedWells">
        <el-input v-model="displayData.completedWells" placeholder="" disabled/>
      </el-form-item>
      <!--
      <el-form-item label="泥浆密度(g/cm³)" prop="mudDensity">
        <el-input v-model="formData.mudDensity" placeholder="请输入泥浆性能-密度(g/cm³)" />
      </el-form-item>
      <el-form-item label="泥浆粘度(S)" prop="mudViscosity">
        <el-input v-model="formData.mudViscosity" placeholder="请输入泥浆性能-粘度(S)" />
      </el-form-item>
      <el-form-item label="水平段长度(m)" prop="lateralLength">
        <el-input v-model="formData.lateralLength" placeholder="请输入水平段长度(m)" />
      </el-form-item>
      <el-form-item label="井斜(°)" prop="wellInclination">
        <el-input v-model="formData.wellInclination" placeholder="请输入井斜(°)" />
      </el-form-item>
      <el-form-item label="方位(°)" prop="azimuth">
        <el-input v-model="formData.azimuth" placeholder="请输入方位(°)" />
      </el-form-item>
      <el-form-item label="设计井身结构" prop="designWellStruct">
        <el-input v-model="displayData.designWellStruct" placeholder="" type="textarea" disabled/>
      </el-form-item> -->
      <el-form-item :label="t('project.currentOperation')" prop="currentOperation">
        <el-input v-model="formData.currentOperation" placeholder="请输入目前工序" type="textarea"/>
      </el-form-item>
      <el-form-item :label="t('project.nextPlan')" prop="nextPlan">
        <el-input v-model="formData.nextPlan" placeholder="请输入下步工序" type="textarea"/>
      </el-form-item>
      <el-form-item label="生产时间(H)" prop="productionTime">
        <el-input v-model="formData.productionTime" placeholder="请输入生产时间(H)" />
      </el-form-item>
      <el-form-item :label="t('project.transitTime')" prop="transitTime">
        <el-input v-model="displayTransitTime" placeholder="" disabled
                  :class="{'red-text': isTransitTimeOver}"
                  id="transitTimeInput" />
      </el-form-item>
      <el-form-item :label="t('project.nptReason')" prop="ryNptReason">
        <el-select v-model="formData.ryNptReason" placeholder="请选择" disabled>
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PMS_PROJECT_RY_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="totalStaffNum">
        <el-input v-model="formData.totalStaffNum" placeholder="请输入全员数量" @input="calculateOnDutyStaffNum"/>
      </el-form-item>
      <el-form-item label="在岗人数" prop="onDutyStaffNum">
        <el-input v-model="formData.onDutyStaffNum" placeholder="" disabled
                  :class="{'yellow-bg': formData.onDutyStaffNum < 0}"/>
      </el-form-item>
      <el-form-item label="休假人员数量" prop="leaveStaffNum">
        <el-input v-model="formData.leaveStaffNum" placeholder="请输入休假人员数量" @input="calculateOnDutyStaffNum"/>
      </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 { IotRyDailyReportApi, IotRyDailyReportVO } from '@/api/pms/iotrydailyreport'
import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";
import { computed, ref, watch, nextTick, reactive } from 'vue'

/** 瑞鹰日报 表单 */
defineOptions({ name: 'IotRyXjDailyReportForm' })

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


const formData = ref({
  id: undefined,
  deptId: undefined,
  projectId: undefined,
  taskId: undefined,
  projectClassification: undefined,
  relocationDays: undefined,
  latestWellDoneTime: undefined,
  technique: undefined,
  designWellDepth: undefined,
  currentDepth: undefined,
  dailyFootage: undefined,
  monthlyFootage: undefined,
  annualFootage: undefined,
  totalConstructionWells: undefined,
  completedWells: undefined,
  dailyPowerUsage: undefined,
  monthlyPowerUsage: undefined,
  dailyFuel: undefined,
  monthlyFuel: undefined,
  nonProductionTime: undefined,
  ryNptReason: undefined,
  constructionStartDate: undefined,
  constructionEndDate: undefined,
  productionStatus: undefined,
  nextPlan: undefined,
  rigStatus: undefined,
  repairStatus: undefined,
  personnel: undefined,
  totalStaffNum: undefined,
  leaveStaffNum: undefined,
  onDutyStaffNum: undefined,
  mudDensity: undefined,
  mudViscosity: undefined,
  lateralLength: undefined,
  wellInclination: undefined,
  azimuth: undefined,
  designWellStruct: undefined,
  extProperty: undefined,
  sort: undefined,
  remark: undefined,
  status: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
})

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

/** 计算在岗人数 */
const calculateOnDutyStaffNum = () => {
  // 转换为数字进行计算，处理空值情况
  const total = formData.value.totalStaffNum ? Number(formData.value.totalStaffNum) : 0
  const leave = formData.value.leaveStaffNum ? Number(formData.value.leaveStaffNum) : 0
  formData.value.onDutyStaffNum = total - leave
}

// 监听 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.designWellDepth = newVal.designWellDepth || ''
    displayData.value.technique = newVal.technique || ''
    displayData.value.wellCategory = newVal.wellCategory || ''
    displayData.value.wellControlLevel = newVal.wellControlLevel || ''
    displayData.value.casingPipeSize = newVal.casingPipeSize || ''
  }
  // 初始化时计算在岗人数
  calculateOnDutyStaffNum()
}, { immediate: true })

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

// 添加显示数据对象
const displayData = ref({
  deptName: '',
  contractName: '',
  taskName: '',
  designWellDepth: '',
  technique: '',
  wellCategory: '',
  wellControlLevel: '',
  casingPipeSize: ''
})

const formRules = reactive({
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
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.designWellDepth = props.rowData.designWellDepth || ''
    displayData.value.technique = props.rowData.technique || ''
    displayData.value.wellCategory = props.rowData.wellCategory || ''
    displayData.value.wellControlLevel = props.rowData.wellControlLevel || ''
    displayData.value.casingPipeSize = props.rowData.casingPipeSize || ''
  }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await IotRyDailyReportApi.getIotRyDailyReport(id)
      // 数据加载后计算在岗人数
      calculateOnDutyStaffNum()
    } finally {
      formLoading.value = false
    }
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as IotRyDailyReportVO
    if (formType.value === 'create') {
      await IotRyDailyReportApi.createIotRyDailyReport(data)
      message.success(t('common.createSuccess'))
    } else {
      await IotRyDailyReportApi.updateIotRyDailyReport(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,
    latestWellDoneTime: undefined,
    designWellDepth: undefined,
    currentDepth: undefined,
    dailyFootage: undefined,
    monthlyFootage: undefined,
    annualFootage: undefined,
    totalConstructionWells: undefined,
    completedWells: undefined,
    dailyPowerUsage: undefined,
    monthlyPowerUsage: undefined,
    dailyFuel: undefined,
    monthlyFuel: undefined,
    nonProductionTime: undefined,
    nptReason: undefined,
    constructionStartDate: undefined,
    constructionEndDate: undefined,
    productionStatus: undefined,
    nextPlan: undefined,
    rigStatus: undefined,
    personnel: undefined,
    mudDensity: undefined,
    mudViscosity: undefined,
    lateralLength: undefined,
    wellInclination: undefined,
    azimuth: undefined,
    designWellStruct: undefined,
    extProperty: undefined,
    sort: undefined,
    remark: undefined,
    status: undefined,
    processInstanceId: undefined,
    auditStatus: undefined,
  }

  displayData.value = {
    deptName: '',
    contractName: '',
    taskName: '',
    designWellDepth: '',
    technique: '',
    wellCategory: '',
    wellControlLevel: '',
    casingPipeSize: ''
  }

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