<template>
  <view class="page fault">
    <scroll-view scroll-y="true" class="detail">
      <view class="form-content">
        <uni-forms
          ref="faultFormRef"
          labelWidth="140px"
          :modelValue="maintain"
          :rules="maintainRules"
        >
          <!-- 设备 -->
          <uni-forms-item
            class="form-item"
            :label="$t('maintenanceWorkOrder.equipment')"
            name="deviceName"
            :required="true"
          >
            <uni-easyinput
              style="text-align: right"
              :inputBorder="false"
              :clearable="false"
              :styles="{ disableColor: '#fff' }"
              :placeholder="$t('operation.PleaseSelect')"
              v-model="maintain.deviceName"
              @focus="onAddDevice"
            />
          </uni-forms-item>
          <!-- 是否解决 -->
          <uni-forms-item
            class="form-item"
            :label="$t('workOrder.isSolved')"
            name="ifDeal"
            :required="true"
          >
            <uni-data-select
              :clear="false"
              v-model="maintain.ifDeal"
              :localdata="yesOrNoRange"
              @change="ifDealChange"
            >
            </uni-data-select>
          </uni-forms-item>
          <!-- 是否协助 -->
          <uni-forms-item
            class="form-item"
            :label="$t('workOrder.isHelp')"
            name="needHelp"
            :required="true"
          >
            <uni-data-select
              :clear="false"
              v-model="maintain.needHelp"
              :localdata="yesOrNoRange"
              @change="needHelpChange"
            >
            </uni-data-select>
          </uni-forms-item>
          <!-- 故障系统 -->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.faultSystem')"
            name="failureSystem"
            :required="true"
          >
            <uni-easyinput
              style="text-align: right"
              :inputBorder="false"
              :clearable="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.failureSystem"
              :placeholder="$t('operation.PleaseFillIn')"
            />
          </uni-forms-item>
          <!-- 故障时间 -->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.faultTime')"
            name="failureTime"
            :required="true"
          >
            <uni-datetime-picker
              type="datetime"
              :border="false"
              returnType="timestamp"
              :placeholder="$t('operation.PleaseSelect')"
              :style="{
                color: maintain.failureTime ? '#333' : '#999',
                'font-size': maintain.failureTime
                  ? '14px !important'
                  : 'inherit !important',
              }"
              :end="dateMax"
              v-model="maintain.failureTime"
            >
            </uni-datetime-picker>
          </uni-forms-item>
          <!-- 故障解决时间  是否解决为是，是否协助为否时需要填写-->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.faultResolutionTime')"
            name="dealTime"
            :required="true"
            v-if="maintain.ifDeal"
          >
            <!-- :end="dateMax" -->
            <uni-datetime-picker
              type="datetime"
              :border="false"
              returnType="timestamp"
              :placeholder="$t('operation.PleaseSelect')"
              :style="{
                color: maintain.dealTime ? '#333' : '#999',
                'font-size': maintain.dealTime
                  ? '14px !important'
                  : 'inherit !important',
              }"
              :end="dateMax"
              v-model="maintain.dealTime"
            >
            </uni-datetime-picker>
          </uni-forms-item>
          <!-- 审批人 是否解决为否 时需要选择 -->
          <uni-forms-item
            class="form-item"
            :label="$t('workOrder.approver')"
            name="approvalId"
            :required="true"
            v-if="maintain.ifDeal == 0 && deptName !== 'rh'"
          >
            <uni-data-select
              :clear="false"
              :disabled="true"
              v-model="maintain.approvalId"
              :localdata="approvalList"
              @click="
                openLocalSearch(
                  approvalList,
                  'approvalId',
                  $t('workOrder.approver')
                )
              "
            >
            </uni-data-select>
          </uni-forms-item>
          <!-- 是否停机 -->
          <uni-forms-item
            class="form-item"
            :label="$t('equipmentMaintenance.isStop')"
            name="ifStop"
            :required="false"
          >
            <uni-data-select
              :clear="false"
              v-model="maintain.ifStop"
              :localdata="yesOrNoRange"
            >
            </uni-data-select>
          </uni-forms-item>
          <!-- 图片 -->
          <uni-forms-item
            class="form-item"
            :label="$t('general.picture')"
            name="picList"
            :required="false"
          >
            <uni-file-picker
              v-model="maintain.picList"
              file-mediatype="image"
              mode="grid"
              :auto-upload="false"
              :limit="1"
              :imageStyles="{ border: false }"
              :size-type="['compressed']"
              @select="upload"
            >
              <template #default>
                <view
                  class="flex-col align-center justify-center"
                  style="width: 60px; height: 60px; background-color: #f4f4f4"
                >
                  <uni-icons type="plusempty" color="#ACACAC" size="12" />
                </view>
              </template>
            </uni-file-picker>
          </uni-forms-item>
          <!-- 故障影响 -->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.faultImpact')"
            name="failureInfluence"
            :required="false"
          >
            <uni-easyinput
              style="text-align: right"
              :inputBorder="false"
              :clearable="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.failureInfluence"
              :placeholder="$t('operation.PleaseFillIn')"
            />
          </uni-forms-item>
          <!-- 解决办法 是否解决为是，是否协助为否时需要填写 -->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.solution')"
            :required="true"
            name="solution"
            v-if="maintain.ifDeal"
          >
            <uni-easyinput
              style="text-align: right"
              type="textarea"
              :autoHeight="true"
              :inputBorder="false"
              :clearable="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.solution"
              :placeholder="$t('operation.PleaseFillIn')"
            />
          </uni-forms-item>
          <!-- 故障描述 -->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.description')"
            :required="false"
            name="description"
          >
            <uni-easyinput
              style="text-align: right"
              type="textarea"
              :autoHeight="true"
              :inputBorder="false"
              :clearable="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.description"
              :placeholder="$t('operation.PleaseFillIn')"
            />
          </uni-forms-item>
          <!-- 备注 -->
          <uni-forms-item
            class="form-item"
            :label="$t('operation.remark')"
            :required="false"
            name="remark"
          >
            <uni-easyinput
              style="text-align: right"
              type="textarea"
              :autoHeight="true"
              :inputBorder="false"
              :clearable="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.remark"
              :placeholder="$t('operation.PleaseFillIn')"
            />
          </uni-forms-item>
        </uni-forms>
      </view>
    </scroll-view>
    <button class="submit-btn" type="primary" @click="formSubmit(faultFormRef)">
      {{ $t("operation.submit") }}
    </button>
  </view>
  <!-- 选择设备 单选 -->
  <device-single ref="deviceSingleRef" @devide-submit="onChooseDevice" />
  <!-- 本地搜索 （选择审批人） -->
  <local-search ref="localSearchRef" @choosed="onChooseLocalSearch" />
</template>

<script setup>
import { onLoad, onReady, onBackPress } from "@dcloudio/uni-app";
import {
  reactive,
  ref,
  watch,
  computed,
  watchEffect,
  onMounted,
  onBeforeUnmount,
  nextTick,
  getCurrentInstance,
} from "vue";
import {
  createFault,
  getFailureApprovalList,
  getDeptName,
} from "@/api/fault.js";
import dayjs from "dayjs";
import { uploadFile } from "@/api";

import deviceSingle from "@/components/device/single.vue";
import LocalSearch from "@/components/local-search.vue";

import { useDataDictStore } from "@/store/modules/dataDict";
const { getDataDictList } = useDataDictStore();

// 引用全局变量$t
const { appContext } = getCurrentInstance();
const t = appContext.config.globalProperties.$t;

const yesOrNoRange = ref([
  {
    value: 1,
    text: t("operation.yes"),
  },
  {
    value: 0,
    text: t("operation.no"),
  },
]);
// 获取当前时间
const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
const dateMax = ref(now);

//故障详情
const maintain = ref({
  deviceId: "",
  deviceName: "",
  picList: [], //用于上传照片 提交时删除
});
// 选择设备
const deviceSingleRef = ref(null);
const selectedDevices = ref([]);
const onAddDevice = () => {
  deviceSingleRef.value.open();
};

let deptName = ref("");
const onChooseDevice = (data) => {
  console.log("onChooseDevice", data);
  maintain.value.deviceId = data.id;
  maintain.value.deptId = data.deptId;
  maintain.value.deviceCode = data.deviceCode;
  maintain.value.deviceName = data.deviceName;
  console.log("onChooseDevice-maintain", maintain.value);

  getDeptName(data.id).then((res) => {
    console.log("🚀 ~ getDeptName>>>>>>>>>>>>>>>>>>>> ~ res:", res);
    deptName.value = res.data;
  });
};
// 上传图片
const upload = async (event) => {
  for (const path of event.tempFilePaths) {
    maintain.value.pic = (await uploadFile(path)).data;
  }
};
// 是否解决
const ifDealChange = (value) => {
  console.log("ifDealChange", value);
  maintain.value.ifDeal = value;
  if (value == 0) {
    maintain.value.needHelp = 1;
  } else {
    maintain.value.needHelp = 0;
  }
};
// 是否协助
const needHelpChange = (value) => {
  maintain.value.needHelp = value;
  if (value == 1) {
    maintain.value.ifDeal = 0;
  } else {
    maintain.value.ifDeal = 1;
  }
};
// 审批人列表
const approvalList = ref([]);
const getApprovalList = async () => {
  const res = await getFailureApprovalList();
  approvalList.value = res.data.map((item) => ({
    value: item.id,
    text: item.nickname,
  }));
};

// 本地搜索
const localSearchRef = ref(null);
// 打开本地搜索
const openLocalSearch = (list, propKey, title) => {
  localSearchRef.value.open({
    list,
    propKey,
    title,
    choosed: maintain.value[propKey],
  });
};
// 本地搜索确认选择
const onChooseLocalSearch = (propKey, item) => {
  console.log("🚀 ~ onChooseLocalSearch ~ propKey, item:", propKey, item);
  // 根据propKey设置maintain的值
  maintain.value[propKey] = item.value;
};

const faultFormRef = ref(null);
const maintainBaseRules = ref({
  deviceName: {
    rules: [
      {
        required: true,
        errorMessage: `${t("operation.PleaseSelect")}${t("device.deviceName")}`,
      },
    ],
  },
  ifDeal: {
    rules: [
      {
        required: true,
        errorMessage: `${t("operation.PleaseSelect")}${t(
          "workOrder.isSolved"
        )}`,
      },
    ],
  },
  needHelp: {
    rules: [
      {
        required: true,
        errorMessage: `${t("operation.PleaseSelect")}${t(
          "workOrder.Needassistance"
        )}`,
      },
    ],
  },
  failureSystem: {
    rules: [
      {
        required: true,
        errorMessage: `${t("operation.PleaseFillIn")}${t("fault.faultSystem")}`,
      },
    ],
  },
  failureTime: {
    rules: [
      {
        required: true,
        errorMessage: `${t("operation.PleaseSelect")}${t("fault.faultTime")}`,
      },
    ],
  },
  dealTime: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseSelect")}${t(
          "fault.faultResolutionTime"
        )}`,
      },
    ],
  },
  solution: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseFillIn")}${t("fault.solution")}`,
      },
    ],
  },
  approvalId: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseSelect")}${t(
          "workOrder.approver"
        )}`,
      },
    ],
  },
});

// 动态计算校验规则
const maintainRules = computed(() => {
  const rules = JSON.parse(JSON.stringify(maintainBaseRules.value));

  // 根据是否解决动态调整规则
  if (maintain.value.ifDeal === 0) {
    // 未解决：解决时间 解决办法非必填
    rules.dealTime.rules[0].required = false;
    rules.solution.rules[0].required = false;
    // 未解决：审批人必填
    rules.approvalId.rules[0].required = true;
  } else {
    // 已解决：故障时间 解决时间 解决办法必填
    rules.dealTime.rules[0].required = true;
    rules.solution.rules[0].required = true;
    // 已解决：审批人非必填
    rules.approvalId.rules[0].required = false;
  }

  return rules;
});

// 监听是否解决数据变化，触发规则更新和校验重置
watch(
  () => maintain.value.ifDeal,
  (newVal, oldVal) => {
    console.log("是否解决变更：", oldVal, "->", newVal);
    // 是否解决为否， 获取审批人列表
    if (newVal == 0) {
      getApprovalList();
    }

    // 重置相关字段的值和校验状态
    resetFieldsByTypeChange(newVal, oldVal);
  }
);
// 根据是否解决变更重置字段
const resetFieldsByTypeChange = (newType, oldType) => {
  // 如果是否解决没有变化或不是初始化阶段，则不执行重置
  if (newType === oldType && oldType !== undefined) return;
  // 清空故障解决时间和解决办法
  if (newType == 0) {
    maintain.value.dealTime = "";
    maintain.value.solution = "";
    // 重置审批人
    maintain.value.approvalId = "";
  }
  // 重置表单校验状态
  faultFormRef.value.clearValidate(["dealTime", "solution", "approvalId"]);
};

const formSubmit = async (formEl) => {
  if (!formEl) return;
  await formEl
    .validate()
    .then((res) => {
      console.log("success", res);
      // 当是否解决为是时，故障解决时间不能早于故障时间
      if (maintain.value.ifDeal === 1) {
        if (maintain.value.dealTime < maintain.value.failureTime) {
          uni.showToast({
            title: t("fault.timeNotBeEarlier"),
            icon: "none",
          });
          return;
        }
      }
      // 新建参数用于提交
      const submitMaintain = {
        ...maintain.value,
        // 是否解决,是否协助,是否停机更换成true/false
        ifDeal: maintain.value.ifDeal ? true : false,
        needHelp: maintain.value.needHelp ? true : false,
        ifStop: maintain.value.ifStop ? true : false,
      };
      // 删picList
      delete submitMaintain.picList;
      console.log("submitMaintain", submitMaintain);

      createFault({
        ...submitMaintain,
      })
        .then((res) => {
          console.log("createFault", res);
          if (res.code == 0) {
            uni.showToast({
              title: t("operation.success"),
              icon: "success",
            });
            uni.navigateBack();
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
          }
        })
        .catch((err) => {
          console.log("err", err);
        });
    })
    .catch((err) => {
      console.log("err", err);
    });
};
onMounted(() => {
  // 监听子页面提交的事件
  console.log("onMounted");
  uni.$on("inspection-falut", (data) => {
    console.log("接收到子页面数据:", data);
    onChooseDevice(data);
  });
});
onBeforeUnmount(() => {
  // 移除监听
  console.log("onBeforeUnmount");
  uni.$off("inspection-fault");
});

onLoad((option) => {
  console.log("falut-create-onLoad", option);
});
onReady(() => {
  // 设置自定义表单校验规则，必须在节点渲染完毕后执行
  // this.$refs.customForm.setRules(this.customRules)
});
onBackPress((options) => {
  // options.from 值为 'navigateBack' 时，表示返回是由 uni.navigateBack() 方法调用触发的
  // options.from 值为 'navigator' 时，表示返回是由导航栏返回按钮或物理返回键触发的
  console.log("返回触发来源:", options.from);
});
</script>

<style lang="scss" scoped>
@import "@/style/work-order-detail.scss";
</style>
