<script setup lang="ts">
import { ref, onMounted } from 'vue'
import StatusTag from './components/StatusTag.vue'
import WorkOrderInfoCard from './components/WorkOrderInfoCard.vue'
import WorkOrderProcessRecords from './components/WorkOrderProcessRecords.vue'
import HandleForm from './components/HandleForm.vue'
import DelayForm from './components/DelayForm.vue'
import CCForm from './components/CCForm.vue'
import ApproveDelayForm from './components/ApproveDelayForm.vue'
import { 
  getWorkOrderDetail, 
  getWorkOrderRecords, 
  handleWorkOrder, 
  delayWorkOrder, 
  ccWorkOrder, 
  backWorkOrder, 
  editWorkOrder, 
  deleteWorkOrder, 
  submitWorkOrder,
  approveDelayWorkOrder,
  type WorkOrderDetail,
  type WorkOrderRecord
} from './api/workOrderApi'
import { getWorkOrderId, getDelayId, getTaskId, getButton, copyToClipboard, showConfirmModal } from './utils/common'

// 定义页面配置
definePage({
  title: '工单详情'
})

// 页面数据
const workOrderDetail = ref<WorkOrderDetail>({
  id: '',
  orderNo: '',
  statusName: '',
  status: '',
  createBy: '',
  ticketTypeName: '',
  createTime: '',
  stationName: '',
  contact: '',
  phone: '',
  content: '',
  attachments: '',
  attachmentsUrl: []
})

const workOrderRecords = ref<WorkOrderRecord[]>([])
const loading = ref(true)
const recordsLoading = ref(false)
const buttonData = ref<string[]>([])

// 处理表单状态
const showHandleForm = ref(false)
const handleLoading = ref(false)

// 延时表单状态
const showDelayForm = ref(false)
const delayLoading = ref(false)

// 抄送表单状态
const showCCForm = ref(false)
const ccLoading = ref(false)

// 延时审批表单状态
const showApproveDelayForm = ref(false)
const approveDelayLoading = ref(false)

// 获取工单详情
async function fetchWorkOrderDetail() {
  const id = getWorkOrderId()
  if (!id) return
  
  try {
    loading.value = true
    const response = await getWorkOrderDetail(id)
    workOrderDetail.value = response || workOrderDetail.value
    buttonData.value = getButton().split(',')
    // 获取工单流程记录
    await fetchWorkOrderRecords(id)
  } catch (error) {
    console.error('获取工单详情失败:', error)
    uni.showToast({
      title: '获取工单详情失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 获取工单流程记录
async function fetchWorkOrderRecords(orderId: string) {
  try {
    recordsLoading.value = true
    const response = await getWorkOrderRecords(orderId)
    workOrderRecords.value = response || []
  } catch (error) {
    console.error('获取工单流程记录失败:', error)
    uni.showToast({
      title: '获取工单流程记录失败',
      icon: 'none'
    })
  } finally {
    recordsLoading.value = false
  }
}

// 处理按钮
function handleHandle() {
  showHandleForm.value = true
}

// 处理表单提交
async function submitHandleForm(data: { processContent: string; attachments: string }) {
  try {
    handleLoading.value = true
    await handleWorkOrder({
      taskId: getTaskId(),
      processContent: data.processContent,
      attachments: data.attachments
    })
    uni.showToast({ title: '处理成功', icon: 'success' })
    showHandleForm.value = false
    uni.navigateBack()
  } catch (error) {
    console.error('处理工单失败:', error)
    uni.showToast({ title: '处理失败', icon: 'none' })
  } finally {
    handleLoading.value = false
  }
}

// 延时按钮
function handleDelay() {
  showDelayForm.value = true
}

// 延时表单提交
async function submitDelayForm(data: { delayDuration: string; delayReason: string; applyFile: string }) {
  try {
    delayLoading.value = true
    await delayWorkOrder({
      taskId: getTaskId(),
      delayDuration: data.delayDuration,
      delayReason: data.delayReason,
      applyFile: data.applyFile
    })
    uni.showToast({ title: '延时申请成功', icon: 'success' })
    showDelayForm.value = false
    uni.navigateBack()
  } catch (error) {
    console.error('延时申请失败:', error)
    uni.showToast({ title: '延时申请失败', icon: 'none' })
  } finally {
    delayLoading.value = false
  }
}

// 抄送按钮
function handleCC() {
  showCCForm.value = true
}

// 抄送表单提交
async function submitCCForm(data: { ccUserIds: string[] }) {
  try {
    ccLoading.value = true
    await ccWorkOrder({
      taskId: getTaskId(),
      ccUserIds: data.ccUserIds.join(',')
    })
    uni.showToast({ title: '抄送成功', icon: 'success' })
    showCCForm.value = false
    uni.navigateBack({
      delta: 1
    })
  } catch (error) {
    console.error('抄送失败:', error)
    uni.showToast({ title: '抄送失败', icon: 'none' })
  } finally {
    ccLoading.value = false
  }
}

// 退回按钮
function handleBack() {
  showConfirmModal(
    '确认退回',
    '确定要退回工单吗？',
    async () => {
      try {
        await backWorkOrder(getTaskId())
        uni.showToast({
          title: '退回成功',
          icon: 'success'
        })
        uni.navigateBack({
          delta: 1
        })
      } catch (error) {
        console.error('退回失败:', error)
        uni.showToast({
          title: '退回失败',
          icon: 'none'
        })
      }
    }
  )
}

// 编辑按钮
function handleEdit() {
  editWorkOrder(getWorkOrderId())
}

// 删除按钮
function handleDelete() {
  showConfirmModal(
    '确认删除',
    '确定删除工单吗？',
    async () => {
      try {
        await deleteWorkOrder(getWorkOrderId())
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        uni.navigateBack({
          delta: 1
        })
      } catch (error) {
        console.error('删除失败:', error)
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        })
      }
    }
  )
}

// 提交按钮
function handleSubmit() {
  showConfirmModal(
    '确认提交',
    '确定提交工单吗？',
    async () => {
      try {
        await submitWorkOrder(getWorkOrderId())
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        })
        uni.navigateBack({
          delta: 1
        })
      } catch (error) {
        console.error('提交失败:', error)
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        })
      }
    }
  )
}

// 延时审批按钮
function handleApproveDelay() {
  showApproveDelayForm.value = true
}

// 延时审批表单提交
async function submitApproveDelayForm(data: {
  approveStatus: number
  approveRemark: string
  newDeadline: string
}) {
  try {
    approveDelayLoading.value = true
    await approveDelayWorkOrder({
      delayId: getDelayId(),
      approveStatus: Number(data.approveStatus),
      approveRemark: data.approveRemark,
      newDeadline: data.newDeadline
    })
    
    uni.showToast({ title: '审批成功', icon: 'success' })
    showApproveDelayForm.value = false
    uni.navigateBack()
  } catch (error) {
    console.error('审批失败:', error)
    uni.showToast({ title: '审批失败', icon: 'none' })
  } finally {
    approveDelayLoading.value = false
  }
}

// 页面加载时获取工单详情
onMounted(() => {
  fetchWorkOrderDetail()
})
</script>
<template>
  <view class="work-order-detail">
    <!-- 标题区域 -->
    <view class="detail-header">
      <view class="flex justify-between items-center mb-3">
        <view class="flex items-center gap-2">
          <text class="text-2xl font-bold">{{ workOrderDetail.orderNo }}</text>
          <wd-icon name="copy" size="20px" @click="copyToClipboard(workOrderDetail.orderNo)"></wd-icon>
          <StatusTag :status-name="workOrderDetail.statusName" />
        </view>
      </view>
      
      <view class="flex items-center gap-2 mb-4">
        <view class="flex flex-col gap-2">
          <view class="flex items-center gap-1 text-gray-500">
            <wd-icon name="user" size="16px"></wd-icon>
            创建人: {{ workOrderDetail.createBy + '/' + (workOrderDetail.stationName || '无') }}
          </view>
          <view class="flex items-center gap-1 text-gray-500">  
            <wd-icon name="transfer" size="16px"></wd-icon>
            流程分类: {{ workOrderDetail.ticketTypeName }}
          </view>
          <view class="flex items-center gap-1 text-gray-500">
            <wd-icon name="time" size="16px"></wd-icon>
            提交时间: {{ workOrderDetail.createTime }}
          </view>
        </view>
      </view>
    </view>
    
    <!-- 工单详情内容 -->
    <view class="detail-content">
      <view class="detail-title">
        <text class="text-lg font-medium">工单详情</text>
      </view>

      <!-- 基本信息 -->
      <WorkOrderInfoCard :work-order="workOrderDetail" />
      
      <view class="detail-title">
        <text class="text-lg font-medium">工单流程</text>
      </view>
      
      <!-- 审批流程 -->
      <WorkOrderProcessRecords :records="workOrderRecords" />
    </view>
    
    <!-- 底部悬浮按钮 -->
    <view v-if="workOrderDetail.status === 'new'" class="bottom-actions">
      <wd-button size="medium" custom-class="action-btn" @click="handleEdit">
        编辑
      </wd-button>
      <wd-button type="error" size="medium" custom-class="action-btn" @click="handleDelete">
        删除
      </wd-button>
      <wd-button size="medium" custom-class="action-btn" @click="handleSubmit">
        提交
      </wd-button>
    </view>
    
    <!-- 底部悬浮按钮 -->
    <view class="bottom-actions" v-if="buttonData.includes('handle') || buttonData.includes('delay') || buttonData.includes('cc') || buttonData.includes('back') || buttonData.includes('approve_delay')">
      <wd-button v-if="buttonData.includes('handle')" size="medium" custom-class="action-btn" @click="handleHandle">
        处理
      </wd-button>
      <wd-button v-if="buttonData.includes('delay')" type="error" size="medium" custom-class="action-btn" @click="handleDelay">
        延时
      </wd-button>
      <wd-button v-if="buttonData.includes('cc')" type="primary" size="medium" custom-class="action-btn" @click="handleCC">
        抄送
      </wd-button>
      <wd-button v-if="buttonData.includes('back')" size="medium" custom-class="action-btn" @click="handleBack">
        退回
      </wd-button>
      <wd-button v-if="buttonData.includes('approve_delay')" size="medium" custom-class="action-btn" @click="handleApproveDelay">
        延时审批
      </wd-button>
    </view>
    
    <!-- 处理工单表单 -->
    <HandleForm 
      v-model:visible="showHandleForm" 
      :loading="handleLoading" 
      @submit="submitHandleForm" 
    />
    
    <!-- 延时工单表单 -->
    <DelayForm 
      v-model:visible="showDelayForm" 
      :loading="delayLoading" 
      @submit="submitDelayForm" 
    />
    
    <!-- 抄送工单表单 -->
    <CCForm 
      v-model:visible="showCCForm" 
      :loading="ccLoading" 
      @submit="submitCCForm" 
    />
    
    <!-- 延时审批表单 -->
    <ApproveDelayForm 
      v-model:visible="showApproveDelayForm" 
      :loading="approveDelayLoading" 
      @submit="submitApproveDelayForm" 
    />
  </view>
</template>

<style scoped>
.work-order-detail {
  padding: 20rpx;
  padding-bottom: 160rpx;
  background-color: #ffffff;
  min-height: 100vh;
}

.detail-header {
  background-color: #fff;
  padding: 20rpx;
}

.detail-content {
  background-color: #fff;
  padding: 20rpx;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.gap-2 {
  gap: 16rpx;
}

.mb-3 {
  margin-bottom: 24rpx;
}

.mb-4 {
  margin-bottom: 32rpx;
}

.text-2xl {
  font-size: 36rpx;
}

.font-bold {
  font-weight: bold;
}

.text-gray-500 {
  color: #999;
  font-size: 24rpx;
}

.detail-title {
  margin: 0 0 16rpx 0;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #e5e7eb;
}

.text-lg {
  font-size: 32rpx;
}

.font-medium {
  font-weight: 500;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx;
  display: flex;
  gap: 20rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
  z-index: 9;
}

.action-btn {
  flex: 1;
}
</style>