<template>
  <view class="create-service-order">
    <view class="create-service-wrapper">
      <view class="order-header">
        <text>创建服务工单</text>
      </view>
      <view class="order-content">
        <view class="order-item">
            <image src="./images/icon_service.png" class="order-icon"></image>
            <uni-data-select
                v-if="!isCallSuccess && workOrderTypeList.length > 0"
                class="order-select"
                placeholder="请选择服务工单"
                v-model="workOrderTypeName"
                :localdata="workOrderTypeList"
                @change="changeWorkOrderType"
              ></uni-data-select>
            <text v-else class="order-description">{{ workOrderTypeName }}</text>
        </view>
        <view class="order-line"></view>
        <view class="order-details">
          <view class="detail-item">
            <text class="detail-label">房间号：</text>
            <input
              v-if="!isCallSuccess"
              class="detail-input"
              placeholder="请填写房间号"
              v-model="roomId"
            />
            <text v-else class="detail-value">{{ roomId }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">服务时间：</text>
            <text class="detail-value">2025-09-12 12:00</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">联系房客：</text>
            <!-- 呼叫成功后显示为文本，否则显示输入框 -->
            <input
              v-if="!isCallSuccess"
              class="detail-input"
              placeholder="请填写联系人"
              v-model="contactName"
            />
            <text v-else class="detail-value">{{ contactName }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">联系电话：</text>
            <!-- 呼叫成功后显示为文本，否则显示输入框 -->
            <input
              v-if="!isCallSuccess"
              class="detail-input"
              placeholder="请填写联系电话"
              v-model="contactPhone"
            />
            <text v-else class="detail-value">{{ contactPhone }}</text>
          </view>
        </view>

        <!-- 呼叫前显示立即呼叫按钮 -->
        <button v-if="!isCallSuccess" class="order-button" @click="handleCall">
          立即呼叫
        </button>

        <!-- 呼叫成功后显示两个按钮 -->
        <view v-else class="order-buttons">
          <button class="order-button-secondary" @click="viewWorkOrder">
            查看工单
          </button>
          <button class="order-button-primary" @click="markCompleted">
            已完成
          </button>
        </view>
      </view>
    </view>

    <view class="footer-help">
      <image src="./images/icon_volume.png" class="help-icon"></image>
      <text class="help-text">没解决问题？给我打电话吧！</text>
      <text class="help-phone" @click="makePhoneCall">15185111210</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import { SCROLL_TO_BOTTOM } from "@/constant/constant";


import { createWorkOrder, workOrderTypeListForBiz } from "@/request/api/OrderApi";
const workOrderTypeId = ref('')
const workOrderTypeName = ref('')
const roomId = ref('')
const contactName = ref("");
const contactPhone = ref("");
const isCallSuccess = ref(false); // 呼叫成功状态
const workOrderId = ref(0); // 工单ID
const workOrderTypeList = ref([])

const changeWorkOrderType = (item) => {
  console.log(item)
  workOrderTypeId.value = item.value
  workOrderTypeName.value = item.text
}

const handleCall = async () => {
    // 验证输入
    if (!roomId.value.trim()) {
        uni.showToast({
          title: '请填写房间号',
          icon: 'none',
          duration: 2000
        });
        return;
    }

    if (!contactName.value.trim()) {
        uni.showToast({
          title: '请填写联系人',
          icon: 'none',
          duration: 2000
        });
        return;
    }

    if (!contactPhone.value.trim()) {
        uni.showToast({
          title: '请填写联系电话',
          icon: 'none',
          duration: 2000
        });
        return;
    }

    sendCreateWorkOrder()
};

/// 创建工单
const sendCreateWorkOrder = async () => {
    try {
      const res = await createWorkOrder({
        contactName: contactName.value,
        contactPhone: contactPhone.value,
        workOrderTypeId: workOrderTypeId.value,
        roomId: roomId.value,
      });

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

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

        uni.showToast({
          title: '工单创建成功',
          icon: 'success',
          duration: 2000
        });
      } else {
        uni.showToast({
          title: res.message || '创建工单失败',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('创建工单失败:', error);
      uni.showToast({
        title: '网络错误，请重试',
        icon: 'none',
        duration: 2000
      });
    }
}

/// 获取工单类型
const getWorkOrderType = async () => {
	const res = await workOrderTypeListForBiz()
    if(res.code === 0) {
        res.data.forEach((item, index) => {
            workOrderTypeList.value.push({
                value: item.id,
                text: item.workOrderTypeName,
            })
        })

        if (workOrderTypeList.value.length > 0) {
            workOrderTypeId.value = workOrderTypeList.value[0].value
            workOrderTypeName.value = workOrderTypeList.value[0].text
        }
    }
}

// 查看工单
const viewWorkOrder = () => {
  console.log("查看工单:", workOrderId.value);
  // 这里可以跳转到工单详情页面
  uni.navigateTo({
    url: `/pages/order/list?id=${workOrderId.value}`
  });
};

// 标记已完成
const markCompleted = () => {
  console.log("标记工单已完成:", workOrderId.value);
  uni.showModal({
    title: '确认完成',
    content: '确认标记此工单为已完成吗？',
    success: (res) => {
      if (res.confirm) {
        // 这里可以调用API标记工单完成
        uni.showToast({
          title: '工单已完成',
          icon: 'success',
          duration: 2000
        });
      }
    }
  });
};

const makePhoneCall = () => {
  // 使用 uniapp 的 API 拨打电话
  uni.makePhoneCall({
    phoneNumber: "15185111210",
  });
};

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

<style scoped lang="scss">
@import "./styles/index.scss";
</style>
