<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";
import dayjs from "dayjs";

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",
  "repairStatus",
  "technique",
  "wellCategory",
  "designWellDepth",
  "wellControlLevel",
  "casingPipeSize",
  "dailyFuel",
  "currentOperation",
  "nextPlan",
  "ratedProductionTime",
  "productionTime",
  "totalStaffNum",
  "onDutyStaffNum",
  "leaveStaffNum",
  "daySupervisors",
  "nightSupervisors",
  "reportDetails",
  "constructionBrief",
  "remark",
  "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 = {
    ratedProductionTime: 0,
    productionTime: 0,
    constructionBrief: "",
    reportDetails: [],
    daySupervisors: "",
    nightSupervisors: "",
  };
  // 初始化所有非生产时间字段为 0
  NON_PROD_FIELDS.forEach((field) => {
    base[field.key] = 0;
  });
  return base;
};

const form = ref(initFormData());

const formatT = (arr) =>
  `${arr[0].toString().padStart(2, "0")}:${arr[1].toString().padStart(2, "0")}`;

async function loadDetail(id) {
  try {
    const { data } = await getRuiYingReportDetail({ 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.reportDetails = form.value.reportDetails.map((item) => ({
      reportDate: item.reportDate || form.value.createTime,
      duration: item.duration || 0,
      constructionDetail: item.constructionDetail || "",
      currentOperation: item.currentOperation || "",
      startTime: formatT(item.startTime),
      endTime: formatT(item.endTime),
    }));

    if (!form.value.reportDetails.length) {
      addReportDetailRow();
    }

    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 addReportDetailRow = () => {
  if (!form.value.reportDetails) {
    form.value.reportDetails = [];
  }
  form.value.reportDetails.push({
    reportDate: form.value.createTime ?? dayjs().valueOf(),
    startTime: "08:00",
    endTime: "08:00",
    duration: 0,
    constructionDetail: "",
    currentOperation: "",
  });
};

const removeReportDetailRow = (index) => {
  if (index === 0) {
    uni.showToast({ title: "至少填写一条生产动态", icon: "none" });
    return;
  }

  form.value.reportDetails?.splice(index, 1);
};

const dictStore = useDataDictStore();

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

const loadOptions = () => {
  nptReasonOptions.value = dictStore
    .getStrDictOptions("ryNptReason")
    .map((v) => ({
      text: v.label,
      value: v.value,
    }));
  rigStatusOptions.value = dictStore
    .getStrDictOptions("repairStatus")
    .map((v) => ({
      text: v.label,
      value: v.value,
    }));
  techniqueOptions.value = dictStore
    .getStrDictOptions("rq_iot_project_technology_ry")
    .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.productionTime ?? 0;
  const gas = form.value.ratedProductionTime ?? 0;

  if (!gas) return { original: 0, value: "0%" };

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

const formRef = ref(null);

const onDutyStaffNum = computed(() => {
  return (form.value.totalStaffNum ?? 0) - (form.value.leaveStaffNum ?? 0);
});

// 辅助函数：计算总时间
const sumNonProdTimes = () => {
  let sum = 0;
  NON_PROD_FIELDS.forEach((field) => {
    sum += Number(form.value[field.key] || 0);
  });
  return sum;
};

// 校验函数：总时间必须为 24
const validateTotalTime = (rule, value, data, callback) => {
  const rateTime = Number(form.value.ratedProductionTime || 0);
  const time = Number(form.value.productionTime || 0);

  const nonProdSum = sumNonProdTimes();

  let total = 0;
  let msg = "";

  total = parseFloat((time + nonProdSum).toFixed(2));
  msg = `生产(${time})+非生产(${nonProdSum})=${total}H，必须等于额定${rateTime}H`;

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

const rules = reactive({
  repairStatus: {
    rules: [{ required: true, errorMessage: "请输入施工状态" }],
  },

  ratedProductionTime: {
    rules: [
      { required: true, errorMessage: "请输入额定生产时间" },
      { validateFunction: validateTotalTime },
    ],
  },
  productionTime: {
    rules: [
      { required: true, errorMessage: "请输入生产时间" },
      { validateFunction: validateTotalTime },
    ],
  },
  constructionBrief: {
    rules: [
      {
        required: props.type === "approval",
        errorMessage: `请输入当日施工简报`,
      },
    ],
  },
  daySupervisors: {
    rules: [{ required: true, errorMessage: "请输入白班跟班干部" }],
  },
  nightSupervisors: {
    rules: [{ required: true, errorMessage: "请输入夜班跟班干部" }],
  },
});

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

watch(
  () => allTimeKeys.map((key) => form.value[key]),
  () => {
    nextTick(() => {
      formRef.value?.validateField(["ratedProductionTime", "productionTime"]);
    });
  }
);

defineExpose({ formRef, form, loadDetail });

const orange = computed(() => {
  const rateTime = Number(form.value.ratedProductionTime || 0);
  const time = Number(form.value.productionTime || 0);

  const nonProdSum = sumNonProdTimes();

  let total = 0;
  let msg = "";

  total = parseFloat((time + nonProdSum).toFixed(2));
  msg = `生产(${time})+非生产(${nonProdSum})=${total}H，必须等于额定${rateTime}H`;

  if (Math.abs(total - rateTime) > 0.01) return true;
  return false;
});

const reportDetailsTimeRangeRef = ref(null);

const startTime = ref("00:00");
const startDefaultTime = ref("08:00");
const endTime = ref("24:00");
const endDefaultTime = ref("08:00");

const reportDetailIndex = ref(0);

const handleClickTimeRangeItem = (index) => {
  reportDetailIndex.value = index;
  reportDetailsTimeRangeRef.value.open();
};

const calculateDuration = (row) => {
  if (!row.startTime || !row.endTime) {
    row.duration = 0;
    return;
  }

  const todayStr = dayjs().format("YYYY-MM-DD");
  const start = dayjs(`${todayStr} ${row.startTime}`);
  const end = dayjs(`${todayStr} ${row.endTime}`);

  let diffMinutes = end.diff(start, "minute");

  if (diffMinutes < 0) {
    diffMinutes += 1440;
  }

  row.duration = Number((diffMinutes / 60).toFixed(2));
};

const reportDetailsTimeRange = (data) => {
  form.value.reportDetails[reportDetailIndex.value].startTime = data[0];
  form.value.reportDetails[reportDetailIndex.value].endTime = data[1];

  calculateDuration(form.value.reportDetails[reportDetailIndex.value]);
};
</script>

<template>
  <view class="content">
    <view class="tip">
      <view class="item">
        <view class="left">
          <span>运行时效：</span>
          生产时间/额定生产时间
        </view>
        <span class="right red"> >100% 红色预警 </span>
      </view>
      <view class="item">
        <view class="left">
          <span>时间平衡：</span>
          生产 + 非生产 = 额定生产
        </view>
        <span class="right orange"> ≠额定生产 橙色预警 </span>
      </view>
      <view class="item">
        <view class="left">
          <span>油量消耗：</span>
          当日油耗
        </view>
        <span class="right blue"> >3500升 蓝色预警 </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="location">
        <span class="readOnly">{{ form.location }}</span>
      </uni-forms-item>
      <uni-forms-item label="施工状态" name="repairStatus" required>
        <uni-data-select
          :clear="true"
          align="right"
          placeholder="请选择"
          :localdata="rigStatusOptions"
          placement="top"
          :disabled="disabled('edit')"
          v-model="form.repairStatus" />
      </uni-forms-item>
      <uni-forms-item label="施工工艺" name="technique">
        <uni-data-select
          :clear="true"
          align="right"
          placeholder="请选择"
          :localdata="techniqueOptions"
          placement="top"
          :disabled="disabled('edit')"
          v-model="form.technique" />
      </uni-forms-item>
      <uni-forms-item label="井别" name="wellCategory">
        <uni-easyinput
          v-bind="defaultProps"
          v-model="form.wellCategory"
          :disabled="disabled('edit')" />
      </uni-forms-item>
      <uni-forms-item label="设计井深(m)" name="designWellDepth">
        <uni-easyinput
          v-bind="defaultProps"
          v-model="form.designWellDepth"
          :disabled="disabled('edit')" />
      </uni-forms-item>
      <uni-forms-item label="井控级别" name="wellControlLevel">
        <uni-easyinput
          v-bind="defaultProps"
          v-model="form.wellControlLevel"
          :disabled="disabled('edit')" />
      </uni-forms-item>
      <uni-forms-item label="套生段产管尺寸(mm)" name="casingPipeSize">
        <uni-easyinput
          v-bind="defaultProps"
          v-model="form.casingPipeSize"
          :disabled="disabled('edit')" />
      </uni-forms-item>
      <uni-forms-item label="当日油耗(升)" name="dailyFuel">
        <uni-easyinput
          type="number"
          :class="{ 'blue-text': Number(form.dailyFuel) > 3500 }"
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.dailyFuel" />
      </uni-forms-item>
      <uni-forms-item label="目前工序" name="currentOperation">
        <uni-easyinput
          type="textarea"
          autoHeight
          v-bind="defaultProps"
          v-model="form.currentOperation"
          :disabled="disabled('edit')"
          :maxlength="1000" />
      </uni-forms-item>
      <uni-forms-item label="下步工序" name="nextPlan">
        <uni-easyinput
          type="textarea"
          autoHeight
          v-bind="defaultProps"
          v-model="form.nextPlan"
          :disabled="disabled('edit')"
          :maxlength="1000" />
      </uni-forms-item>
      <uni-forms-item label="运行时效" name="transitTime">
        <span
          class="readOnly"
          :class="{ 'red-text': transitTime.original > 1.0 }"
          >{{ transitTime.value }}</span
        >
      </uni-forms-item>
      <uni-forms-item label="全员数量" name="totalStaffNum">
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.totalStaffNum" />
      </uni-forms-item>
      <uni-forms-item label="在岗人数" name="onDutyStaffNum">
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          disabled
          v-model="onDutyStaffNum" />
      </uni-forms-item>
      <uni-forms-item label="休假人员数量" name="leaveStaffNum">
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.leaveStaffNum" />
      </uni-forms-item>
      <uni-forms-item label="白班跟班干部" name="daySupervisors" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.daySupervisors" />
      </uni-forms-item>
      <uni-forms-item label="夜班跟班干部" name="nightSupervisors" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :disabled="disabled('edit')"
          v-model="form.nightSupervisors" />
      </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="当日施工简报"
        :required="type === 'approval'"
        name="constructionBrief">
        <uni-easyinput
          type="textarea"
          autoHeight
          v-bind="defaultProps"
          :disabled="type !== 'approval'"
          v-model="form.constructionBrief"
          :maxlength="2000" />
      </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="ratedProductionTime"
        required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :class="{ 'orange-text': orange }"
          :disabled="disabled('edit')"
          v-model="form.ratedProductionTime" />
      </uni-forms-item>
      <uni-forms-item label="生产时间(H)" name="productionTime" required>
        <uni-easyinput
          type="number"
          v-bind="defaultProps"
          :class="{ 'orange-text': orange }"
          :disabled="disabled('edit')"
          v-model="form.productionTime" />
      </uni-forms-item>

      <uv-divider text="生产动态" textPosition="left"></uv-divider>
      <uni-forms-item v-if="!disabled('edit')">
        <button
          type="primary"
          size="mini"
          class="detail-btn"
          @click="addReportDetailRow()">
          添加一行
        </button>
      </uni-forms-item>
      <template v-for="(item, index) in form.reportDetails" :key="index">
        <uv-divider v-if="index !== 0" class="divider"></uv-divider>
        <uni-forms-item
          label="日期"
          required
          :name="['reportDetails', index, 'reportDate']"
          :rules="[{ required: true, errorMessage: '请选择日期' }]">
          <uni-datetime-picker
            class="datetime-picker"
            type="date"
            returnType="timestamp"
            v-model="item.reportDate"
            :border="false"
            :disabled="disabled('edit')" />
        </uni-forms-item>
        <uni-forms-item :label="`${$t('ruiDu.timeNode')}:`" required>
          <view
            class="item-content"
            @click="disabled('edit') ? '' : handleClickTimeRangeItem(index)">
            <view class="time-range-item" v-if="item.startTime && item.endTime">
              {{ item.startTime }} 至 {{ item.endTime }}
            </view>
            <view class="time-range-item" v-else>
              {{ selectPlaceholder }}
            </view>
          </view>
        </uni-forms-item>
        <uni-forms-item label="时长(H)">
          <span class="readOnly">{{ item.duration }}</span>
        </uni-forms-item>
        <uni-forms-item
          label="工况"
          required
          :name="['reportDetails', index, 'currentOperation']"
          :rules="[{ required: true, errorMessage: '请输入工况' }]">
          <uni-easyinput
            type="textarea"
            autoHeight
            v-bind="defaultProps"
            :disabled="disabled('edit')"
            v-model="item.currentOperation"
            :maxlength="2000" />
        </uni-forms-item>
        <!-- <uni-forms-item
          label="结束井深(m)"
          required
          :name="['reportDetails', index, 'currentDepth']"
          :rules="[{ required: true, errorMessage: '请输入结束深度' }, { validateFunction: validateLastCurrentDepth }]">
          <uni-easyinput
            type="number"
            v-bind="defaultProps"
            :disabled="disabled('edit')"
            v-model.number="item.currentDepth" />
        </uni-forms-item> -->
        <uni-forms-item
          label="详情"
          required
          :name="['reportDetails', index, 'constructionDetail']"
          :rules="[{ required: true, errorMessage: '请输入详情' }]">
          <uni-easyinput
            type="textarea"
            autoHeight
            v-bind="defaultProps"
            :disabled="disabled('edit')"
            v-model="item.constructionDetail"
            :maxlength="2000" />
        </uni-forms-item>
        <uni-forms-item v-if="!disabled('edit')" label="操作">
          <button
            type="warn"
            size="mini"
            class="detail-btn"
            @click="removeReportDetailRow(index)">
            删除
          </button>
        </uni-forms-item>
      </template>

      <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"
          :class="{ 'orange-text': orange }"
          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>

  <tpf-time-range
    ref="reportDetailsTimeRangeRef"
    :startTime="startTime"
    :startDefaultTime="startDefaultTime"
    :endTime="endTime"
    :endDefaultTime="endDefaultTime"
    @timeRange="reportDetailsTimeRange"></tpf-time-range>
</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;
}

.blue-text {
  color: rgb(59 130 246 / 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);
}

.blue {
  border: 1px solid rgb(219 234 254);
  color: rgb(59 130 246 / 0.8);
  background-color: rgb(240 249 255);
}

.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);
  }
}

.divider {
  margin: 0;
  transform: translateY(-7px);
  :deep(.uv-line) {
    border-width: 2px !important;
    border-color: rgb(41, 121, 255) !important;
  }
}
</style>
