<script setup>
import { ref, computed, watch, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getRuiHenReportDetail } from "@/api/ruihen";
import { useDataDictStore } from "@/store/modules/dataDict";

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

const NON_PROD_FIELDS = [
  { key: "repairTime", label: "设备故障" },
  { key: "selfStopTime", label: "设备保养" },
  { key: "accidentTime", label: "工程质量" },
  { key: "complexityTime", label: "技术受限" },
  { key: "rectificationTime", label: "生产组织" },
  { key: "waitingStopTime", label: "不可抗力" },
  { key: "partyaDesign", label: "甲方设计" },
  { key: "partyaPrepare", label: "甲方准备" },
  { key: "partyaResource", label: "甲方资源" },
  { key: "relocationTime", label: "生产配合" },
  { key: "winterBreakTime", label: "待命" },
  { key: "otherNptTime", label: "其他非生产时间" },
];

const FORM_KEYS = [
  "id",
  "deptId",
  "projectId",
  "taskId",
  "deptName",
  "contractName",
  "taskName",
  "dailyGasInjection",
  "dailyWaterInjection",
  "dailyInjectGasTime",
  "dailyInjectWaterTime",
  "productionStatus",
  "remark",
  "relocationDays",
  "capacity",
  "createTime",
  "opinion",
  "repairTime",
  "selfStopTime",
  "accidentTime",
  "complexityTime",
  "rectificationTime",
  "waitingStopTime",
  "partyaDesign",
  "partyaPrepare",
  "partyaResource",
  "relocationTime",
  "winterBreakTime",
  "otherNptTime",
  "otherNptReason",
  "status",
  "auditStatus",
  "location",
];

const formType = ref("edit");

const initFormData = () => {
  const base = {
    dailyGasInjection: 0,
    dailyWaterInjection: 0,
    dailyInjectGasTime: 0,
    dailyInjectWaterTime: 0,
    relocationDays: 0,
    capacity: 0,
  };
  // 初始化所有非生产时间字段为 0
  NON_PROD_FIELDS.forEach((field) => {
    base[field.key] = 0;
  });
  return base;
};

const form = ref(initFormData());

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

    form.value = initFormData();

    FORM_KEYS.forEach((key) => {
      if (
        Object.prototype.hasOwnProperty.call(data, key) &&
        data[key] !== null &&
        data[key] !== undefined
      ) {
        form.value[key] = data[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";
    }

    if (!form.value.capacity) {
      uni.showToast({ title: "请维护增压机产能", icon: "none" });
    }
  } finally {
  }
}

const dictStore = useDataDictStore();

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

const loadOptions = () => {
  nptReasonOptions.value = dictStore
    .getStrDictOptions("nptReason")
    .map((v) => ({
      text: v.label,
      value: v.value,
    }));
  constructionStatusOptions.value = dictStore
    .getStrDictOptions("constructionStatus")
    .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 sumNonProdTimes = () => {
  let sum = 0;
  NON_PROD_FIELDS.forEach((field) => {
    sum += Number(form.value[field.key] || 0);
  });
  return sum;
};

const validateTotalTime = (rule, value, data, callback) => {
  const gasTime = Number(form.value.dailyInjectGasTime || 0);
  const waterTime = Number(form.value.dailyInjectWaterTime || 0);
  const nonProdSum = sumNonProdTimes();

  let total = 0;
  let msg = "";

  if (gasTime === 0 && waterTime > 0) {
    total = parseFloat((waterTime + nonProdSum).toFixed(2));
    msg = `注水(${waterTime})+非生产(${nonProdSum})=${total}H，必须为24H`;
  } else {
    total = parseFloat((gasTime + nonProdSum).toFixed(2));
    msg = `注气(${gasTime})+非生产(${nonProdSum})=${total}H，必须为24H`;
  }

  if (Math.abs(total - 24) > 0.01) {
    callback(msg);
  }
  return true;
};

// uni-forms 规则定义
const rules = ref({
  dailyGasInjection: {
    rules: [{ required: true, errorMessage: "请输入当日注气量" }],
  },
  dailyWaterInjection: {
    rules: [{ required: true, errorMessage: "请输入当日注水量" }],
  },
  productionStatus: {
    rules: [{ required: true, errorMessage: "请输入生产动态" }],
  },
  constructionStatus: {
    rules: [{ required: true, errorMessage: "请选择施工状态" }],
  },
  dailyInjectGasTime: {
    rules: [
      { required: true, errorMessage: "请输入当日注气量时间" },
      { validateFunction: validateTotalTime },
    ],
  },
});

const allTimeKeys = [
  "dailyInjectGasTime",
  "dailyInjectWaterTime",
  ...NON_PROD_FIELDS.map((f) => f.key),
];

watch(
  () => allTimeKeys.map((key) => form.value[key]),
  () => {
    nextTick(() => {
      formRef.value?.validateField("dailyInjectGasTime");
    });
  },
  {
    deep: true,
  }
);

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"> >120% 红色预警 </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="submit"
      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="location">
        <span class="readOnly">{{ form.location }}</span>
      </uni-forms-item>
      <uni-forms-item label="搬迁安装天数(D)" name="relocationDays">
        <span class="readOnly">{{ form.relocationDays }}</span>
      </uni-forms-item>
      <uni-forms-item label="运行时效" name="transitTime">
        <span
          class="readOnly"
          :class="{ 'red-text': transitTime.original > 1.2 }"
          >{{ transitTime.value }}</span
        >
      </uni-forms-item>
      <uni-forms-item label="施工状态" name="constructionStatus" required>
        <uni-data-select
          :clear="true"
          align="right"
          placeholder="请选择"
          :localdata="constructionStatusOptions"
          placement="top"
          :disabled="disabled('edit')"
          v-model="form.constructionStatus" />
      </uni-forms-item>
      <uni-forms-item label="当日注气量(方)" name="dailyGasInjection" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.dailyGasInjection" />
      </uni-forms-item>
      <uni-forms-item
        label="当日注水量(方)"
        name="dailyWaterInjection"
        required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.dailyWaterInjection" />
      </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>
      <uv-divider text="生产时间" textPosition="left"></uv-divider>
      <uni-forms-item label="当日注气时间(H)" name="dailyInjectGasTime">
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.dailyInjectGasTime" />
      </uni-forms-item>
      <uni-forms-item label="当日注水时间(H)" name="dailyInjectWaterTime">
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.dailyInjectWaterTime" />
      </uni-forms-item>
      <uv-divider text="非生产时间" textPosition="left"></uv-divider>
      <uni-forms-item
        v-for="field in NON_PROD_FIELDS"
        :key="field.key"
        :label="field.label + '(H)'"
        :name="field.key">
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form[field.key]" />
      </uni-forms-item>

      <uni-forms-item label="其他非生产原因" name="otherNptReason">
        <uni-easyinput
          type="textarea"
          autoHeight
          v-bind="defaultProps"
          v-model="form.otherNptReason"
          :disabled="disabled('edit')"
          :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);
  }
}
</style>
