<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { http } from '@/utils/request'
import FgTree from '@/components/fg-tree/fg-tree.vue'

// 页面配置通过 onLoad 中的 uni.setNavigationBarTitle 设置

// 页面数据
const formData = reactive({
  ticketType: '',
  stationId: '',
  contact: '',
  phone: '',
  content: '',
  attachments: '',
  isSubmit: true,
  urgency: '1'
})

// 紧急程度选项
const urgencyOptions = ref([
  { value: '1', label: '一般' },
  { value: '2', label: '紧急' }
])

// 工单类型树形数据
const ticketTypeTree = ref<any[]>([])
// 选中的工单类型
const selectedTicketType = ref<any>({
  label: '',
  id: ''
})


// 场站列表
const stationList = ref<any[]>([])
// 场站选择器列
const stationColumns = ref<any[]>([])

// 附件上传
const uploadFiles = ref<any[]>([])
const uploadLoading = ref(false)

// 页面状态
const loading = ref(false)
const isEditMode = ref(false)
const orderId = ref('')

// 工单类型弹窗状态
const ticketTypePopupVisible = ref(false)

// 获取页面参数
function getPageParams() {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  if (currentPage.options.id) {
    isEditMode.value = true
    orderId.value = currentPage.options.id as string
    uni.setNavigationBarTitle({
      title: '编辑工单'
    })
    // 加载工单详情
    fetchOrderDetail()
  } else {
    uni.setNavigationBarTitle({
      title: '创建工单'
    })
  }
}

// 获取工单类型树
async function fetchTicketTypeTree() {
  try {
    const response = await http.get<any[]>('/flowCategory/category/categoryTree')
    ticketTypeTree.value = response
  } catch (error) {
    console.error('获取工单类型失败:', error)
    uni.showToast({
      title: '获取工单类型失败',
      icon: 'none'
    })
  }
}

// 获取场站列表
async function fetchStationList() {
  try {
    const response = await http.get<any[]>('/sysStation/station/selectAllSysStationList')
    stationList.value = response
    // 转换为选择器列格式
    stationColumns.value = response.map(item => ({
      value: item.id,
      label: item.stationName
    }))
  } catch (error) {
    console.error('获取场站列表失败:', error)
    uni.showToast({
      title: '获取场站列表失败',
      icon: 'none'
    })
  }
}

// 获取工单详情
async function fetchOrderDetail() {
  if (!orderId.value) return
  
  try {
    loading.value = true
    const response = await http.get<any>(`/workOrder/order/${orderId.value}`)
    // 填充表单数据
    formData.ticketType = response.ticketType || ''
    selectedTicketType.value.label  = response.ticketTypeName || ''
    selectedTicketType.value.id = response.ticketType || ''
    formData.stationId = response.stationId || ''
    formData.contact = response.contact || ''
    formData.phone = response.phone || ''
    formData.content = response.content || ''
    formData.attachments = response.attachments || ''
    formData.isSubmit = false
    formData.urgency = response.urgency || '1'
    
    // 处理附件
    if (response.attachmentsUrl) {
      uploadFiles.value = response.attachmentsUrl.map((url,index) => ({
        url: url,
        name: response.attachments.split(',')[index] || '',
        status: 'success'
      }))
    }
    console.log('uploadFiles:', uploadFiles.value)
  } catch (error) {
    console.error('获取工单详情失败:', error)
    uni.showToast({
      title: '获取工单详情失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 处理工单类型选择
function handleTicketTypeSelect(node: any) {
  selectedTicketType.value = node
  formData.ticketType = node.id
  // 选择后自动关闭弹窗
  ticketTypePopupVisible.value = false
}

// 处理场站选择
function handleStationConfirm({ value }: { value: string }) {
  formData.stationId = value
}

// 处理附件上传
async function handleSuccess(data: any) {
    console.log('上传成功:', data.fileList)

    // 更新上传文件列表
    uploadFiles.value = data.fileList
    // 更新附件字段，取 fileName
    const fileNames = uploadFiles.value.map(f => {
      try {
        const response = JSON.parse(f.response)
        return response.data.fileName
      } catch (error) {
        console.error('解析文件响应失败:', error)
        return ''
      }
    }).filter(Boolean)
    console.log('fileNames:', fileNames)
    formData.attachments = fileNames.join(',')
}

// 处理附件删除
function handleRemoveFile(file: any) {
  const index = uploadFiles.value.findIndex(f => f.url === file.url)
  if (index !== -1) {
    uploadFiles.value.splice(index, 1)
    // 更新附件字段，取 fileName
    const fileNames = uploadFiles.value.map(f => {
      try {
        const response = JSON.parse(f.response)
        return response.data.fileName
      } catch (error) {
        console.error('解析文件响应失败:', error)
        return ''
      }
    }).filter(Boolean)
    
    formData.attachments = fileNames.join(',')
  }
}

// 提交表单
async function submitForm() {
  // 验证表单
  if (!formData.ticketType) {
    uni.showToast({ title: '请选择工单类型', icon: 'none' })
    return
  }
  if (!formData.stationId) {
    uni.showToast({ title: '请选择场站', icon: 'none' })
    return
  }
  if (!formData.contact) {
    uni.showToast({ title: '请填写联系人', icon: 'none' })
    return
  }
  if (!formData.phone) {
    uni.showToast({ title: '请填写联系电话', icon: 'none' })
    return
  }
  if (!formData.content) {
    uni.showToast({ title: '请填写提报内容', icon: 'none' })
    return
  }
  
  loading.value = true
  try {
    if (isEditMode.value) {
      // 编辑工单
      await http.put(`/workOrder/order/${orderId.value}`, formData)
      uni.showToast({
        title: '编辑工单成功',
        icon: 'success'
      })
    } else {
      // 添加工单
      await http.post('/workOrder/order', formData)
      uni.showToast({
        title: '创建工单成功',
        icon: 'success'
      })
    }
    
    // 跳转回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (error) {
    console.error('提交工单失败:', error)
    uni.showToast({
      title: '提交工单失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}
onLoad((options) => {
 console.log('options:', options)
 if (options.id) {
  orderId.value = options.id
  uni.setNavigationBarTitle({
    title: '编辑工单'
  })
  // 加载工单详情
  fetchOrderDetail()
 }

})
// 页面加载时获取数据
onMounted(() => {
  getPageParams()
  console.log('orderId:', orderId.value)
  fetchTicketTypeTree()
  fetchStationList()
})
</script>

<template>
  <view class="page min-h-screen bg-gray-100">
    <view class="bg-white rounded-lg p-4 shadow-sm">
      <!-- 工单类型 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">
          <text class="text-red-500">*</text> 工单类型
        </text>
        <view @click="ticketTypePopupVisible = true" class="relative" style="border-bottom: 1px solid rgba(0, 0, 0, 0.1);">
          <text v-if="selectedTicketType" class="block w-full py-3 px-4 border border-gray-300 rounded-md border-b-2 border-blue-500">
            {{ selectedTicketType.label }}
          </text>
          <text v-else class="block w-full py-3 px-4 border border-gray-300 rounded-md border-b-2 border-blue-500 text-gray-400">
            请选择工单类型
          </text>
          <wd-icon name="arrow-right" class="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400" />
        </view>
        
        <!-- 工单类型选择弹窗 -->
        <wd-popup v-model="ticketTypePopupVisible" position="bottom" round>
          <view class="h-96 w-full bg-white">
            <view class="flex justify-between items-center p-4 border-b">
              <text class="text-lg font-medium">
                <text class="text-red-500">*</text> 选择工单类型
              </text>
              <wd-button size="small" @click="ticketTypePopupVisible = false">取消</wd-button>
            </view>
            <view class="h-[calc(100%-80px)] overflow-auto">
              <fg-tree 
                :data="ticketTypeTree" 
                @node-click="handleTicketTypeSelect"
              />
            </view>
          </view>
        </wd-popup>
      </view>
      
      <!-- 场站 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">
          <text class="text-red-500">*</text> 场站
        </text>
        <wd-picker 
          :columns="[stationColumns]" 
          v-model="formData.stationId" 
          @confirm="handleStationConfirm"
           style="border-bottom: 1px solid rgba(0, 0, 0, 0.1);"
        />
      </view>
      
      <!-- 联系人 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">
          <text class="text-red-500">*</text> 联系人
        </text>
        <wd-input v-model="formData.contact" placeholder="请输入联系人" />
      </view>
      
      <!-- 联系电话 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">
          <text class="text-red-500">*</text> 联系电话
        </text>
        <wd-input v-model="formData.phone" placeholder="请输入联系电话" />
      </view>
      
      <!-- 提报内容 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">
          <text class="text-red-500">*</text> 提报内容
        </text>
        <wd-input 
          v-model="formData.content" 
          placeholder="请输入提报内容" 
          type="textarea" 
          rows="4"
        />
      </view>
      
      <!-- 提报附件 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">提报附件</text>
        <wd-upload 
          v-model:file-list="uploadFiles" 
          action="/common/upload"
          @success="handleSuccess" 
          @remove="handleRemoveFile"
          :loading="uploadLoading"
          multiple
          accept="image/*"
        />
      </view>
      
      <!-- 紧急程度 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">紧急程度</text>
        <wd-picker 
          :columns="[urgencyOptions]" 
          v-model="formData.urgency" 
          style="border-bottom: 1px solid rgba(0, 0, 0, 0.1);"
        />
      </view>
      
      <!-- 是否提交 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">是否提交</text>
        <wd-switch v-model="formData.isSubmit" />
      </view>
      
      <!-- 提交按钮 -->
      <view class="mt-8 flex justify-center">
        <wd-button 
          type="primary" 
          size="large" 
          @click="submitForm"
          :loading="loading"
        >
          {{ isEditMode ? '保存修改' : '创建工单' }}
        </wd-button>
      </view>
    </view>
  </view>
</template>

<style scoped>
.page {
  padding-bottom: 100rpx;
}
</style>