<script setup>
  import { ref, computed, watch, nextTick, reactive } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import { getRuiYingReportDetail } from '@/api/ruiying';
  import { useDataDictStore } from '@/store/modules/dataDict';

  const props = defineProps({
    type: {
      type: String,
      default: 'edit',
    },
  });

  const FORM_KEYS = [
    'id',
    'deptName',
    'contractName',
    'taskName',
    'rigStatus',
    'designWellDepth',
    'currentDepth',
    'dailyPowerUsage',
    'dailyFuel',
    'mudDensity',
    'mudViscosity',
    'lateralLength',
    'wellInclination',
    'azimuth',
    'designWellStruct',
    'productionStatus',
    'remark',
    'createTime',
    'deptId',
    'projectId',
    'taskId',
    'opinion',
    'personnel',
    'accidentTime',
    'repairTime',
    'selfStopTime',
    'complexityTime',
    'relocationTime',
    'rectificationTime',
    'waitingStopTime',
    'winterBreakTime',
    'drillingWorkingTime',
    'otherProductionTime',
    'lastCurrentDepth',
    'opinion',
    'status',
    'auditStatus',
  ];

  const formType = ref('edit');

  const initFormData = () => ({});

  const form = ref(initFormData());

  async function loadDetail(id) {
    try {
      const { data } = await getRuiYingReportDetail({ id });

      FORM_KEYS.forEach(key => {
        form.value[key] = data[key] ?? form.value[key];
      });
      form.value.id = id;

      if (props.type.includes('approval') && data.auditStatus !== 10) {
        formType.value = 'readonly';
      }

      if (props.type.includes('edit') && data.status !== 0) {
        formType.value = 'readonly';
      }

      if (props.type.includes('detail')) {
        formType.value = 'readonly';
      }
    } finally {
    }
  }

  const dictStore = useDataDictStore();

  const nptReasonOptions = ref([]);
  const rigStatusOptions = ref([]);

  const loadOptions = () => {
    nptReasonOptions.value = dictStore.getStrDictOptions('nptReason').map(v => ({
      text: v.label,
      value: v.value,
    }));
    rigStatusOptions.value = dictStore.getStrDictOptions('rigStatus').map(v => ({
      text: v.label,
      value: v.value,
    }));
  };

  onLoad(options => {
    if (dictStore.dataDict.length <= 0) {
      dictStore.loadDataDictList().then(() => {
        loadOptions();
      });
    } else loadOptions();
    loadDetail(options.id);
  });

  const defaultProps = computed(() => ({
    inputBorder: false,
    clearable: false,
    placeholder: '请输入',
    style: {
      'text-align': 'right',
    },
    styles: {
      disableColor: '#fff',
    },
  }));

  const disabled = computed(() => field => {
    if (field === 'edit')
      return formType.value === 'readonly' || props.type.includes('approval') || props.type.includes('detail');
    else return formType.value === 'readonly';
  });

  // const transitTime = computed(() => {
  //   const cap = form.value.capacity;
  //   const gas = form.value.dailyGasInjection ?? 0;

  //   if (!cap) return { original: 0, value: '0%' };

  //   const original = gas / cap;
  //   return { original, value: (original * 100).toFixed(2) + '%' };
  // });

  const formRef = ref(null);

  // 辅助函数：计算总时间
  const sumTimes = () => {
    const {
      drillingWorkingTime = 0,
      otherProductionTime = 0,
      accidentTime = 0,
      repairTime = 0,
      selfStopTime = 0,
      complexityTime = 0,
      relocationTime = 0,
      rectificationTime = 0,
      waitingStopTime = 0,
      winterBreakTime = 0,
    } = form.value;
    return parseFloat(
      (
        Number(drillingWorkingTime) +
        Number(otherProductionTime) +
        Number(accidentTime) +
        Number(repairTime) +
        Number(selfStopTime) +
        Number(complexityTime) +
        Number(relocationTime) +
        Number(rectificationTime) +
        Number(waitingStopTime) +
        Number(winterBreakTime)
      ).toFixed(2)
    );
  };

  // 校验函数：总时间必须为 24
  const validateTotalTime = (rule, value, data, callback) => {
    const total = sumTimes();
    if (total !== 24) {
      callback(`当前合计 ${total} 小时，时间之和必须等于 24`);
    } else {
      callback();
    }
  };

  const validateLastCurrentDepth = (rule, value, data, callback) => {
    if (value && Number(value) < (form.value.lastCurrentDepth ?? 0)) {
      callback(`当前深度需大于等于上一次填报深度${form.value.lastCurrentDepth}m`);
    } else {
      callback();
    }
  };

  // // 校验函数：非生产时间原因
  // const validateNptReason = (rule, value, data, callback) => {
  //   const npt = Number(form.value.nonProductionTime) || 0;
  //   console.log('npt :>> ', npt);
  //   console.log('value :>> ', value);
  //   if (npt > 0 && !value) {
  //     callback('非生产时间大于 0 时，必须选择原因');
  //   }
  //   return true;
  // };

  // 复用的时间规则
  const timeRuleItem = {
    rules: [
      { required: true, errorMessage: '请输入时间' },
      { validateFunction: validateTotalTime }, // 关联自定义校验
    ],
  };

  // uni-forms 规则定义
  const rules = reactive({
    currentDepth: {
      rules: [{ required: true, errorMessage: '请输入当前深度' }, { validateFunction: validateLastCurrentDepth }],
    },

    productionStatus: {
      rules: [{ required: true, errorMessage: '请输入生产动态' }],
    },

    drillingWorkingTime: timeRuleItem,
    otherProductionTime: timeRuleItem,
    accidentTime: timeRuleItem,
    repairTime: timeRuleItem,
    selfStopTime: timeRuleItem,
    complexityTime: timeRuleItem,
    relocationTime: timeRuleItem,
    rectificationTime: timeRuleItem,
    waitingStopTime: timeRuleItem,
    winterBreakTime: timeRuleItem,
  });

  watch(
    [
      () => form.value.drillingWorkingTime,
      () => form.value.otherProductionTime,
      () => form.value.accidentTime,
      () => form.value.repairTime,
      () => form.value.selfStopTime,
      () => form.value.complexityTime,
      () => form.value.relocationTime,
      () => form.value.rectificationTime,
      () => form.value.waitingStopTime,
      () => form.value.winterBreakTime,
    ],
    () => {
      nextTick(() => {
        if (sumTimes() === 24) {
          formRef.value?.clearValidate([
            'drillingWorkingTime',
            'otherProductionTime',
            'accidentTime',
            'repairTime',
            'selfStopTime',
            'complexityTime',
            'relocationTime',
            'rectificationTime',
            'waitingStopTime',
            'winterBreakTime',
          ]);
        }
      });
    }
  );

  defineExpose({ formRef, form, loadDetail });
</script>

<template>
  <view class="content">
    <view class="tip">
      <view class="item">
        <view class="left">
          <span>油量消耗：</span>
          当日油耗
        </view>
        <span class="right red"> >15吨 红色预警 </span>
      </view>
      <view class="item">
        <view class="left">
          <span>时间平衡：</span>
          进尺 + 其它生产 + 非生产 = 24H
        </view>
        <span class="right orange"> ≠24H 橙色预警 </span>
      </view>
    </view>
    <view v-if="!type.includes('approval') && form.opinion" class="opinion">
      <span class="left">审批意见：</span>
      <span class="right"> {{ form.opinion }} </span>
    </view>
    <uni-forms
      ref="formRef"
      labelWidth="auto"
      :model="form"
      :rules="rules"
      validateTrigger="blur"
      err-show-type="toast">
      <uni-forms-item label="施工队伍" name="deptName">
        <span class="readOnly">{{ form.deptName }}</span>
      </uni-forms-item>
      <uni-forms-item label="项目" name="contractName">
        <span class="readOnly">{{ form.contractName }}</span>
      </uni-forms-item>
      <uni-forms-item label="任务" name="taskName">
        <span class="readOnly">{{ form.taskName }}</span>
      </uni-forms-item>
      <uni-forms-item label="施工状态" name="rigStatus">
        <uni-data-select
          :clear="true"
          align="right"
          placeholder="请选择"
          :localdata="rigStatusOptions"
          placement="top"
          :disabled="disabled('edit')"
          v-model="form.rigStatus" />
      </uni-forms-item>
      <uni-forms-item label="设计井深(m)" name="designWellDepth">
        <span class="readOnly">{{ form.designWellDepth }}</span>
      </uni-forms-item>
      <uni-forms-item label="当前井深(m)" name="currentDepth" required>
        <uni-easyinput type="number" v-bind="defaultProps" :disabled="disabled('edit')" v-model="form.currentDepth" />
      </uni-forms-item>
      <uni-forms-item label="当日用电量(kWh)" name="dailyPowerUsage">
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.dailyPowerUsage" />
      </uni-forms-item>
      <uni-forms-item label="当日油耗(吨)" name="dailyFuel">
        <uni-easyinput
          type="number"
          :class="{ 'red-text': Number(form.dailyFuel) > 15 }"
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.dailyFuel" />
      </uni-forms-item>
      <uni-forms-item label="泥浆粘度(S)" name="mudViscosity">
        <uni-easyinput type="number" v-bind="defaultProps" :disabled="disabled('edit')" v-model="form.mudViscosity" />
      </uni-forms-item>
      <uni-forms-item label="泥浆粘度(S)" name="mudViscosity">
        <uni-easyinput type="number" v-bind="defaultProps" :disabled="disabled('edit')" v-model="form.mudViscosity" />
      </uni-forms-item>
      <uni-forms-item label="水平段长度(m)" name="lateralLength">
        <uni-easyinput type="number" v-bind="defaultProps" :disabled="disabled('edit')" v-model="form.lateralLength" />
      </uni-forms-item>
      <uni-forms-item label="井斜(°)" name="wellInclination">
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.wellInclination" />
      </uni-forms-item>
      <uni-forms-item label="方位(°)" name="azimuth">
        <uni-easyinput type="number" v-bind="defaultProps" :disabled="disabled('edit')" v-model="form.azimuth" />
      </uni-forms-item>
      <uni-forms-item label="设计井身结构" name="designWellStruct">
        <uni-easyinput
          type="textarea"
          autoHeight
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.designWellStruct"
          :maxlength="1000" />
      </uni-forms-item>
      <uni-forms-item label="人员情况" name="personnel">
        <uni-easyinput
          type="textarea"
          autoHeight
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.personnel"
          :maxlength="1000" />
      </uni-forms-item>
      <uv-divider text="生产时间" textPosition="left"></uv-divider>
      <uni-forms-item label="进尺工作时间(H)" name="drillingWorkingTime" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :class="{ 'orange-text': sumTimes() !== 24 }"
          :disabled="disabled('edit')"
          v-model="form.drillingWorkingTime" />
      </uni-forms-item>
      <uni-forms-item label="其它生产时间(H)" name="otherProductionTime" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :class="{ 'orange-text': sumTimes() !== 24 }"
          :disabled="disabled('edit')"
          v-model="form.otherProductionTime" />
      </uni-forms-item>
      <uv-divider text="非生产时间" textPosition="left"></uv-divider>
      <uni-forms-item label="事故(H)" name="accidentTime" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :class="{ 'orange-text': sumTimes() !== 24 }"
          :disabled="disabled('edit')"
          v-model="form.accidentTime" />
      </uni-forms-item>
      <uni-forms-item label="修理(H)" name="repairTime" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :class="{ 'orange-text': sumTimes() !== 24 }"
          :disabled="disabled('edit')"
          v-model="form.repairTime" />
      </uni-forms-item>
      <uni-forms-item label="自停(H)" name="selfStopTime" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :class="{ 'orange-text': sumTimes() !== 24 }"
          :disabled="disabled('edit')"
          v-model="form.selfStopTime" />
      </uni-forms-item>
      <uni-forms-item label="复杂(H)" name="complexityTime" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :class="{ 'orange-text': sumTimes() !== 24 }"
          :disabled="disabled('edit')"
          v-model="form.complexityTime" />
      </uni-forms-item>
      <uni-forms-item label="搬迁(H)" name="relocationTime" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :class="{ 'orange-text': sumTimes() !== 24 }"
          :disabled="disabled('edit')"
          v-model="form.relocationTime" />
      </uni-forms-item>
      <uni-forms-item label="整改(H)" name="rectificationTime" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :class="{ 'orange-text': sumTimes() !== 24 }"
          :disabled="disabled('edit')"
          v-model="form.rectificationTime" />
      </uni-forms-item>
      <uni-forms-item label="等停(H)" name="waitingStopTime" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :class="{ 'orange-text': sumTimes() !== 24 }"
          :disabled="disabled('edit')"
          v-model="form.waitingStopTime" />
      </uni-forms-item>
      <uni-forms-item label="冬休(H)" name="winterBreakTime" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :class="{ 'orange-text': sumTimes() !== 24 }"
          :disabled="disabled('edit')"
          v-model="form.waitingStopTime" />
      </uni-forms-item>
      <uni-forms-item label="生产动态" name="productionStatus" required>
        <uni-easyinput
          type="textarea"
          autoHeight
          v-bind="defaultProps"
          v-model="form.productionStatus"
          :disabled="disabled('edit')"
          :maxlength="1000" />
      </uni-forms-item>
      <uni-forms-item label="备注" name="remark">
        <uni-easyinput
          type="textarea"
          autoHeight
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.remark"
          :maxlength="1000" />
      </uni-forms-item>
      <uni-forms-item v-if="type.includes('approval')" label="审批意见" name="opinion">
        <uni-easyinput
          type="textarea"
          autoHeight
          v-bind="defaultProps"
          :disabled="disabled('approval')"
          v-model="form.opinion"
          :maxlength="1000" />
      </uni-forms-item>
    </uni-forms>
  </view>
</template>

<style lang="scss" scoped>
  .content {
    background-color: white;
    padding: 16px 16px;
    border-radius: 8px;
    box-sizing: border-box;
  }

  .uni-forms {
    margin-top: 10px;
    height: 100%;

    .uni-form {
      height: 100%;
    }

    .uni-forms-item {
      display: flex;
      align-items: center;
      flex: 1;
      margin-bottom: 6px;
      border-bottom: 1px dashed #cacccf;
    }

    :deep(.uni-forms-item__content) {
      text-align: right;
      .readOnly {
        padding-right: 10px;
      }
    }

    :deep(.uni-forms-item__label) {
      height: 44px;
      font-weight: 500;
      font-size: 14px;
      color: #333333 !important;
      width: max-content !important;
    }

    :deep(.uni-select) {
      border: none;
      text-align: right;
      padding-right: 0;
      .uniui-bottom:before {
        content: '\e6b5' !important;
        font-size: 16px !important;
      }
    }

    :deep(.uni-easyinput__content-textarea) {
      min-height: inherit;
      margin: 10px;
    }

    :deep(.is-disabled) {
      color: #333333 !important;
    }

    :deep(.red-text > .is-disabled) {
      color: rgb(220 38 38 / 0.8) !important;
    }

    :deep(.orange-text > .is-disabled) {
      color: rgb(234 88 12 / 0.8) !important;
    }

    :deep(.uni-select--disabled) {
      background-color: #fff;
    }
  }

  .red-text {
    color: rgb(220 38 38 / 0.8) !important;
  }

  .orange-text {
    color: rgb(234 88 12 / 0.8) !important;
  }

  .red {
    border: 1px solid rgb(254 226 226);
    color: rgb(220 38 38 / 0.8);
    background-color: rgb(254 226 226);
  }

  .orange {
    border: 1px solid rgb(254 215 170);
    color: rgb(234 88 12 / 0.8);
    background-color: rgb(254 215 170);
  }

  .tip {
    border-radius: 8px;
    border: 1px solid #e5e5e5;
    background-color: rgba(239, 246, 255, 0.8);
    box-sizing: border-box;
    padding: 10px;
    display: flex;
    flex-direction: column;
    gap: 6px;

    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 12px;

      .left {
        color: rgb(75 85 99);

        span {
          color: rgb(31 41 55);
          font-weight: 600;
        }
      }

      .right {
        display: inline-flex;
        align-items: center;
        border-radius: 4px;
        padding: 2px 4px;
        font-weight: 500;
      }
    }
  }

  .opinion {
    border-radius: 8px;
    border: 1px solid rgb(254 240 138);
    background-color: rgb(254 252 232);
    box-sizing: border-box;
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 12px;
    margin-top: 10px;

    .left {
      font-weight: 600;
      color: rgb(133 77 14);
    }

    .right {
      font-weight: 500;
      color: rgb(75 85 99);
    }
  }

  :deep(.uv-divider__text) {
    color: #333 !important;
  }
</style>
