<template>
  <div class="create-service-order">
    <div class="w-full bg-white border-ff overflow-hidden rounded-[20px]">
      <div class="w-full h-[48px] flex items-center justify-between bg-[#f0f8f3]">
        <span class="text-[18px] font-medium text-[#171717] text-left ml-[12px]">
          {{ isCallSuccess ? t("home.serviceOrder.created") : t("home.serviceOrder.title") }}
        </span>
        <img class="w-[98px] h-[48px]" src="https://oss.nianxx.cn/mp/static/version_101/home/feedback.png" />
      </div>

      <div v-if="!isCallSuccess" class=" p-[12px]">
        <div class="bg-[#f5f7fa] flex items-center p-[12px] rounded-[10px] text-[14px] text-[#171717] mb-[12px]">
          <span class="font-medium leading-[22px] mr-[20px]">{{ t("home.serviceOrder.position") }}</span>
          <input :placeholder="t('home.serviceOrder.positionPlaceholder')" v-model="roomId" />
        </div>

        <div class="bg-[#f5f7fa] flex items-center p-[12px] rounded-[10px] text-[14px] text-[#171717] mb-[12px]">
          <span class="font-medium leading-[22px] mr-[20px]">{{ t("home.serviceOrder.phone") }}</span>
          <input :placeholder="t('home.serviceOrder.phonePlaceholder')" v-model="contactPhone"
            @input="handleContactPhoneInput" />
        </div>

        <div class="bg-[#f5f7fa] p-[12px] rounded-[10px] text-[14px] font-medium text-[#171717] mb-[12px]">
          <div class="font-medium leading-[22px] mb-[12px]">{{ t("home.serviceOrder.demand") }}</div>
          <textarea class="h-[80px]" :placeholder="t('home.serviceOrder.demandPlaceholder')" maxlength="100"
            v-model="contactText" />
        </div>

        <div class="bg-[#f5f7fa] p-[12px] rounded-[10px] text-[14px] font-medium text-[#171717] mb-[12px]">
          <div class="font-medium leading-[22px] mb-[12px]">{{ t("home.serviceOrder.photos") }}</div>

          <div class="w-[80px] h-[80px] bg-white rounded-[8px] overflow-hidden flex items-center justify-center">
            <div v-if="contentImgUrl" class="w-full h-full relative inline-block">
              <img class="w-full h-full block" :src="contentImgUrl" />
              <van-icon class="top-0 right-0 absolute z-10" name="cross" size="20" color="#6A717F"
                @click="handleDeleteImage">
              </van-icon>
            </div>

            <div v-else class="w-full h-full flex items-center justify-center" @click="handleChooseImage">
              <zn-icon name="zn-camera" size="24" color="#6A717F"></zn-icon>
            </div>
          </div>
        </div>
      </div>

      <div v-else class=" card-content flex items-center p-[12px]">
        <div class=" left flex-1 pr-[20px]">
          <div class="text-[12px] text-ink-600 leading-[20px] mb-[4px]">
            {{ t("home.serviceOrder.positionPreview") }}{{ roomId }}
          </div>
          <div class="text-[12px] text-ink-600 leading-[20px] mb-[4px]">
            {{ t("home.serviceOrder.phonePreview") }} {{ contactPhone }}
          </div>
          <div class="text-[12px] text-ink-600 leading-[20px] ellipsis-2">
            {{ t("home.serviceOrder.demandPreview") }} {{ contactText }}
          </div>
        </div>

        <img v-if="contentImgUrl" class="w-[88px] h-[88px] rounded-[6px]" :src="contentImgUrl" />
      </div>

      <div class="h-[44px] rounded-full text-white bg-[#4de4ff] flex items-center justify-center mx-[12px] mb-[12px]"
        @click="handleCall">
        {{ isCallSuccess ? t("home.serviceOrder.view") : t("home.serviceOrder.callNow") }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, defineProps, watch } from "vue";
import { useI18n } from "vue-i18n";
import { emitter } from '@/utils/events'
import { SCROLL_TO_BOTTOM } from "@/constants/constant";
import { createWorkOrder } from "@/api/workOrder";
import { uploadFile } from "@/api/upload";
import ZnIcon from "@/components/ZnIcon/index.vue";

const { t } = useI18n();

const props = defineProps({
  toolCall: {
    type: Object,
    default: () => ({}),
  },
});
const workOrderTypeId = ref("");
const roomId = ref("");
const contentImgUrl = ref("");
const isCallSuccess = ref(false); // 呼叫成功状态
const workOrderId = ref(0); // 工单ID
const toolResult = computed(() => {
  if (props.toolCall?.toolResult) {
    return JSON.parse(props.toolCall?.toolResult);
  } else {
    return {};
  }
});
// 原始手机号（未脱敏）
const originalPhone = ref("");
// 展示与输入绑定的手机号（初始为脱敏）
const contactPhone = ref("");
// 是否用户已编辑过手机号（一旦编辑则不再脱敏）
const hasEditedPhone = ref(false);
// 需求信息描述：使用可写的 ref，并从工具结果初始化
const contactText = ref("");

// 手机号脱敏：138****1234（仅对11位数字进行处理）
const maskPhone = (phone) => {
  if (!phone) return "";
  return String(phone).replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
};

// 监听工具返回结果，初始化原始与脱敏显示
watch(
  toolResult,
  (val) => {
    originalPhone.value = val?.userPhone || "";
    hasEditedPhone.value = false;
    contactPhone.value = maskPhone(originalPhone.value);
    contactText.value = val?.callServiceContent || "";
  },
  { immediate: true },
);

// 处理图片上传
const handleChooseImage = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const file = res.tempFilePaths[0];
      updateImagehandle(file);
    },
    fail: () => {
      showToast(t("home.serviceOrder.imageFailed"));
    },
  });
};

// 标记用户已编辑手机号
const handleContactPhoneInput = () => {
  hasEditedPhone.value = true;
};

const handleDeleteImage = () => {
  contentImgUrl.value = "";
};

const updateImagehandle = (file) => {
  if (!file) {
    return;
  }
  uploadFile(file).then((res) => {
    contentImgUrl.value = res.data;
  });
};

const handleCall = async () => {
  if (isCallSuccess.value) {
    // 查看工单
    divWorkOrder();
    return;
  }

  if (!roomId.value.trim()) {
    showToast(t("home.serviceOrder.positionRequired"));
    return;
  }

  const phoneToSubmit = hasEditedPhone.value
    ? contactPhone.value
    : originalPhone.value;
  if (!phoneToSubmit.trim()) {
    showToast(t("home.serviceOrder.phoneRequired"));
    return;
  }

  if (!contactText.value.trim()) {
    showToast(t("home.serviceOrder.demandRequired"));
    return;
  }

  sendCreateWorkOrder(phoneToSubmit);
};

/// 创建工单
const sendCreateWorkOrder = async (phoneToSubmit) => {
  try {
    const params = {
      workOrderTypeId: workOrderTypeId.value,
      roomNo: roomId.value,
      userPhone: phoneToSubmit,
      content: contactText.value,
      contentImgUrl: contentImgUrl.value,
    };
    console.log("🚀 ~ sendCreateWorkOrder ~ params:", params);

    const res = await createWorkOrder(params);

    if (res.code === 0) {
      // 保存工单ID
      workOrderId.value = res.data?.id || "";

      // 设置成功状态
      isCallSuccess.value = true;

      showToast(t("home.serviceOrder.success"));
    } else {
      showToast(res.message || t("home.serviceOrder.failed"));
    }
  } catch (error) {
    showToast(t("common.errors.network"));
  }
};

// 查看工单
const divWorkOrder = () => {
  // 这里可以跳转到工单详情页面
  uni.navigateTo({
    url: `/pages-service/order/list`,
  });
};

onMounted(() => {
  nextTick(() => {
    setTimeout(() => {
      emitter.emit(SCROLL_TO_BOTTOM, true);
    }, 200);
  });
});
</script>
