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

const props = defineProps<{
  visible: boolean
  loading: boolean
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'submit', data: { ccUserIds: string[] }): void
}>()

const ccFormData = ref({
  ccUserIds: []
})

// 部门树
const deptTree = ref([])
// 选中的部门
const selectedDept = ref('')
// 部门选择器显示状态
const showDeptPicker = ref(false)
// 人员列表
const userList = ref([])
// 人员选择器列
const userColumns = ref([])

function handleCancel() {
  emit('update:visible', false)
  resetForm()
}

function resetForm() {
  ccFormData.value = {
    ccUserIds: []
  }
  selectedDept.value = ''
  userList.value = []
  userColumns.value = []
  showDeptPicker.value = false
}

function submitForm() {
  if (ccFormData.value.ccUserIds.length === 0) {
    uni.showToast({ title: '请选择抄送人员', icon: 'none' })
    return
  }
  
  emit('submit', { ...ccFormData.value })
  resetForm()
}

// 获取部门树
async function fetchDeptTree() {
  try {
    const response = await http.get('/system/user/deptTree')
    deptTree.value = response || []
  } catch (error) {
    console.error('获取部门树失败:', error)
  }
}

// 获取人员列表
async function fetchUserList(deptId: string) {
  if (!deptId) return
  
  try {
    const response = await http.get('/system/user/list', {
      deptId: deptId,
      pageNum: 1,
      pageSize: 999
    })
    userList.value = response.rows || []
    // 转换为选择器列格式
    userColumns.value = userList.value.map(user => ({
      value: user.userId,
      label: user.userName
    }))
  } catch (error) {
    console.error('获取人员列表失败:', error)
  }
}

// 处理部门选择
function handleDeptSelect(node: any) {
  selectedDept.value = node.id
  showDeptPicker.value = false
  fetchUserList(node.id)
}


onMounted(() => {
   fetchDeptTree()
})
</script>

<template>
  <wd-popup
    v-model="props.visible"
    position="bottom"
    round
    :overlay="true"
    :close-on-click-overlay="true"
    overlay-class="popup-overlay"
    class="filter-popup-container">
    <view class="filter-popup" style="min-height: 500rpx;">
      <view class="p-4">
        <view class="text-lg font-medium mb-4">抄送工单</view>
        
        <!-- 部门选择 -->
        <view class="mb-4">
          <text class="block mb-2 font-medium">
            <text class="text-red-500">*</text> 部门
          </text>
          <view @click="showDeptPicker = true" class="relative" style="border-bottom: 1px solid rgba(0, 0, 0, 0.1);">
            <text v-if="selectedDept" class="block w-full py-3 px-4 rounded-md ">
              {{ deptTree.find(dept => dept.id === selectedDept)?.deptName || '' }}
            </text>
            <text v-else class="block w-full py-3 px-4  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="showDeptPicker"
            position="bottom"
            round
            :overlay="true"
            :close-on-click-overlay="true"
            overlay-class="popup-overlay"
            class="filter-popup-container">
            <view class="filter-popup" style="min-height:600rpx;">
              <view class="flex justify-between items-center p-4 border-b">
                <text class="text-lg font-medium">选择部门</text>
                <wd-button size="small" @click="showDeptPicker = false">取消</wd-button>
              </view>
              <view class="h-[calc(100vh-300px)] overflow-auto">
                <fg-tree 
                  :data="deptTree" 
                  @node-click="handleDeptSelect"
                />
              </view>
            </view>
          </wd-popup>
        </view>
        
        <!-- 人员选择 -->
        <view class="mb-4">
          <text class="block mb-2 font-medium">
            <text class="text-red-500">*</text> 人员
          </text>
          <wd-select-picker 
            v-model="ccFormData.ccUserIds" 
            :columns="userColumns" 
            placeholder="请选择人员"
          />
        </view>
      </view>
      <view class="flex justify-end m-6">
        <wd-button size="large" type="info" @click="handleCancel" style="margin-right: 16rpx;">取消</wd-button>
        <wd-button size="large" type="primary" @click="submitForm" :loading="props.loading">确定</wd-button>
      </view>
    </view>
  </wd-popup>
</template>

<style scoped>
.p-4 {
  padding: 32rpx;
}

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

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

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

.block {
  display: block;
}

.text-red-500 {
  color: #ff4d4f;
}

.flex {
  display: flex;
}

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

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

.m-6 {
  margin: 48rpx;
}

.border-b {
  border-bottom: 1px solid #e5e7eb;
}

.filter-popup-container {
  z-index: 9999;
}

.filter-popup {
  background-color: #fff;
  border-radius: 16rpx 16rpx 0 0;
}

.py-3 {
  padding-top: 24rpx;
  padding-bottom: 24rpx;
}

.px-4 {
  padding-left: 32rpx;
  padding-right: 32rpx;
}

.border {
  border: 1px solid #d1d5db;
}

.border-gray-300 {
  border-color: #d1d5db;
}

.rounded-md {
  border-radius: 8rpx;
}

.border-b-2 {
  border-bottom-width: 2px;
}

.border-blue-500 {
  border-bottom-color: #3b82f6;
}

.text-gray-400 {
  color: #9ca3af;
}

.absolute {
  position: absolute;
}

.right-4 {
  right: 32rpx;
}

.top-12 {
  top: 50%;
}

.transform {
  transform: translateY(-50%);
}

</style>
