<script setup>
import { ref, defineProps, watch, inject } from "vue";
import dayjs from "dayjs";
import {
  postOperationRecord,
} from "@/apis/alert";
import * as yup from "yup";
import "yup-phone-lite";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";

const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;

const props = defineProps({
  editRecord: Object,
});

const form = ref(null);

const dateItem = ref([
  {
    key: "start_time",
    name: "start_time",
    value: dayjs(),
    dateFormat: "yyyy-MM-dd",
    placeholder: "請輸入預計開始日期",
  },
]);

const formState = ref(
  {
    formId: null,
    alarm_guid: "",
    work_type: 2,
    fix_do: "",
    fix_do_code: "",
    fix_firm: "",
    status: 0,
    device_number: "",
    work_person_id: "",
    start_time: dayjs().format("YYYY-MM-DD"),
    notice: "",
    description: "",
    lorf: [],
  }
);

const { model_data, updateEditRecord, search } = inject("alert_modal") || {
  model_data: [],
  updateEditRecord: null,
  search: null,
};

let alertSchema = yup.object({
  start_time: yup.date().required("必填"),
  fix_do: yup.string().required("必填"),
  fix_do_code: yup.string().required("必填"),
  fix_firm: yup.string().required("必填"),
  status: yup.number().required("必填"),
  work_person_id: yup.string().required("必填"),
  notice: yup.string().nullable(true),
  description: yup.string().nullable(true),
});

const { formErrorMsg, handleSubmit, handleErrorReset } =
  useFormErrorMessage(alertSchema);

const updateFileList = (files) => {
  formState.value.lorf = files;
};

const onOk = async () => {
  const formData = new FormData(form.value);
  formData.delete("oriFile");

  formState.value?.lorf.forEach(
    (file, index) => {
      formData.append(`lorf[${index}].id`, file.id ? file.id : "");
      formData.append(`lorf[${index}].file`, file.id ? null : file);
      formData.append(`lorf[${index}].save_file_name`,file.id ? file.save_file_name : "");
      formData.append(`lorf[${index}].ori_file_name`, file.name);
    }
  );
  
  formData.append(
    "start_time",
    dayjs(dateItem.value[0].value).format("YYYY-MM-DD")
  );

  props.editRecord.id && formData.append("id", props.editRecord.id);

  props.editRecord.alarm_guid && formData.append("error_code", props.editRecord.alarm_guid);

  formData.append("work_type", 2);

  if (props.editRecord.device_number) {
    formData.append("fix_do_code", props.editRecord.device_number);
  } else if (props.editRecord.fix_do_code) {
    formData.append("fix_do_code", props.editRecord.fix_do_code);
  }

  try {
    const value = await handleSubmit(alertSchema, formState.value);
    const res = await postOperationRecord(formData);
    if (res.isSuccess) {
      search?.();
      onCancel();
    }
  } catch (err) {
    console.error("Form submission failed:", err);
  }
};

const onCancel = () => {
  formState.value = {
    formId: null,
    alarm_guid: "",
    work_type: 2,
    fix_do: "",
    fix_do_code: "",
    fix_firm: "",
    status: 0,
    device_number: "",
    work_person_id: "",
    start_time: dayjs().format("YYYY-MM-DD"),
    notice: "",
    description: "",
    lorf: [],
  };
  handleErrorReset();
  updateEditRecord?.(null);
  alert_action_item.close();
};

watch(
  () => props.editRecord,
  (newVal) => {
    if (newVal) {
      for (let [key, value] of Object.entries(newVal)) {
        // 僅更新 formState 中已有的屬性
        if (key in formState.value) {
          formState.value[key] = value;
        }
        // 處理 start_time
        if (key === "start_time") {
          formState.value.start_time = value ? dayjs(value).format("YYYY-MM-DD") : dayjs().format("YYYY-MM-DD");
          dateItem.value[0].value = value;
        }
        // 維修項目代碼
        if (key === "device_number" || key === "fix_do_code") {
          formState.value.fix_do_code = value;
        }
      }
    }
  },
  { immediate: true }
);
</script>

<template>
  <Modal id="alert_action_item" title="維修單" :onCancel="onCancel" width="710">
    <template #modalContent>
      <form ref="form" class="mt-5 w-full flex flex-wrap justify-between">
        <Input v-if="formState.value && formState.value.formId" class="my-2" :value="formState" name="formId" readonly>
        <template #topLeft>表單編號</template>
        </Input>
        <Input :value="formState" class="my-2" name="alarm_guid" readonly>
        <template #topLeft>異常ID</template>
        </Input>
        <DateGroup class="my-2" :items="dateItem" inputClass="w-full shadow-none" :required="true">
          <template #topLeft>預計開始時間</template>
          <template #bottomLeft>
            <span class="text-error text-base">
              {{ formErrorMsg.start_time }}
            </span>
          </template>
        </DateGroup>
        <Select :value="formState" class="my-2" selectClass="border-info focus-within:border-info" name="work_type"
          Attribute="title" :options="[
            {
              key: 1,
              value: 1,
              title: '保養',
            },
            {
              key: 2,
              value: 2,
              title: '維修',
            },
          ]" :required="true" :disabled="true">
          <template #topLeft>項目</template>
        </Select>
        <Input class="my-2" :value="formState" name="fix_do" :required="true">
        <template #topLeft>維修項目</template>
        <template #bottomLeft><span class="text-error text-base">
            {{ formErrorMsg.fix_do }}
          </span>
        </template>
        </Input>
         <Input
          class="my-2"
          :value="formState"
          name="device_number"
          :required="true"
          :disabled="true"
        >
          <template #topLeft>設備名稱</template>
          <template #bottomLeft><span class="text-error text-base">
              {{ formErrorMsg.fix_do_code }}
            </span></template>
        </Input>
        <Select :value="formState" class="my-2" selectClass="border-info  focus-within:border-info" name="fix_firm"
          Attribute="name" :options="model_data.model_companyList" :required="true">
          <template #topLeft>負責廠商</template>
          <template #bottomLeft><span class="text-error text-base">
              {{ formErrorMsg.fix_firm }}
            </span></template>
        </Select>
        <RadioGroup class="my-2" name="status" :value="formState" :items="[
          {
            key: 0,
            value: 0,
            title: '未完成',
          },
          {
            key: 1,
            value: 1,
            title: '已完成',
          },
        ]" :required="true">
          <template #topLeft>狀態</template>
        </RadioGroup>
        <Select :value="formState" class="my-2" selectClass="border-info focus-within:border-info" name="work_person_id"
          Attribute="full_name" :options="model_data.model_userList" :required="true">
          <template #topLeft>工作人員編號</template>
          <template #bottomLeft><span class="text-error text-base">
              {{ formErrorMsg.work_person_id }}
            </span></template>
        </Select>
        <Textarea :value="formState" name="notice" class="w-full my-2">
  <template #topLeft>注意事項</template>
</Textarea>
        <Textarea :value="formState" name="description" class="w-full my-2">
  <template #topLeft>結果描述</template>
</Textarea>
        <Upload 
        class="my-2" 
        name="oriFile" 
        :fileList="formState?.lorf" 
        :getFileList="updateFileList" 
        :multiple="true"
        :baseUrl="`${FILE_BASEURL}/upload/operation`"
        >
          <template #topLeft>上傳檔案</template>
        </Upload>
      </form>
    </template>
    <template #modalAction>
      <button type="reset" class="btn btn-outline-success mr-2" @click.prevent="onCancel">
        取消
      </button>
      <button type="submit" class="btn btn-outline-success" @click.stop.prevent="onOk">
        確定
      </button>
    </template>
  </Modal>
</template>

<style lang="scss" scoped></style>