<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { http } from '@/utils/request'

// 页面配置
uni.setNavigationBarTitle({
  title: '添加隐患台账'
})

// 表单数据
const formData = reactive({
  stationId: '',
  checkName: '',
  isTask:1,
  foundProblem: '',
  tags: '',
  suggestion: '',
  mainHarm: '',
  riskLevel: 0,
  rectifyDeadline: '',
  problemImages: '',
  ccTo: '',
  executorId: ''
})

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

// 下拉框数据
const riskLevelList = ref<Array<{ value: string; label: string }>>([
  { value: '0', label: '低' },
  { value: '1', label: '中' },
  { value: '2', label: '高' }
])
const isTaskList = ref<Array<{ value: string; label: string }>>([
  { value: '1', label: '是' }
])
const tagsList = ref<Array<{ value: string; label: string }>>([])

// 用户列表（用于执行人选择）
const executorList = ref<any[]>([])
// 执行人选择器列
const executorColumns = ref<any[]>([])

// 用户列表（用于抄送人选择）
const userList = ref<any[]>([])
// 抄送人选择器列
const userColumns = ref<any[]>([])
// 选中的用户
const selectedUsers = ref<any[]>([])

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

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

// 获取加油站列表
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 fetchExecutorList() {
  try {
    if (!formData.stationId) {
      return
    }
    const response = await http.get<any[]>('/system/user/stationList', {
      stationId: formData.stationId
    })
    executorList.value = response
    console.log(response)
    
    // 转换为选择器列格式
    executorColumns.value = response.map(item => ({
      value: item.userId,
      label: item.nickName
    }))
     // 转换为选择器列格式
    userColumns.value = response.map(item => ({
      value: item.userId,
      label: item.nickName
    }))
  } catch (error) {
    console.error('获取执行人列表失败:', error)
    uni.showToast({
      title: '获取执行人列表失败',
      icon: 'none'
    })
  }
}



// 获取标签列表
async function fetchTagsList() {
  try {
    const response = await http.get<any[]>('/system/dict/data/type/ledger_tag')
    // 转换为选择器列格式
    tagsList.value = response.map(item => ({
      value: item.dictCode,
      label: item.dictLabel
    }))
  } catch (error) {
    console.error('获取标签列表失败:', error)
    uni.showToast({
      title: '获取标签列表失败',
      icon: 'none'
    })
  }
}

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

// 处理执行人选择
function handleExecutorConfirm({ value }: { value: string }) {
  formData.executorId = value
}

// 处理风险度选择
function handleRiskLevelConfirm({ value }: { value: string }) {
  formData.riskLevel = parseInt(value)
}

// 处理是否转任务选择
function handleIsTaskConfirm({ value }: { value: string }) {
  formData.isTask = parseInt(value)
}

// 处理标签选择
function handleTagsConfirm({ value }: { value: string }) {
  formData.tags = value
}

// 处理时间选择
function handleDateConfirm(date: any) {
  let formattedDate = ''
  if (typeof date === 'object' && date.value) {
    const dateObj = new Date(date.value)
    const year = dateObj.getFullYear()
    const month = String(dateObj.getMonth() + 1).padStart(2, '0')
    const day = String(dateObj.getDate()).padStart(2, '0')
    const hours = String(dateObj.getHours()).padStart(2, '0')
    const minutes = String(dateObj.getMinutes()).padStart(2, '0')
    const seconds = String(dateObj.getSeconds()).padStart(2, '0')
    formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } else if (typeof date === 'number') {
    const dateObj = new Date(date)
    const year = dateObj.getFullYear()
    const month = String(dateObj.getMonth() + 1).padStart(2, '0')
    const day = String(dateObj.getDate()).padStart(2, '0')
    const hours = String(dateObj.getHours()).padStart(2, '0')
    const minutes = String(dateObj.getMinutes()).padStart(2, '0')
    const seconds = String(dateObj.getSeconds()).padStart(2, '0')
    formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  formData.rectifyDeadline = formattedDate
}

// 处理附件上传
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.problemImages = 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.problemImages = fileNames.join(',')
  }
}


// 提交表单
async function submitForm() {
  // 验证表单
  if (!formData.stationId) {
    uni.showToast({ title: '请选择检查油站', icon: 'none' })
    return
  }
  if (!formData.checkName) {
    uni.showToast({ title: '请填写检查名称', icon: 'none' })
    return
  }
  if (!formData.foundProblem) {
    uni.showToast({ title: '请填写发现问题描述', icon: 'none' })
    return
  }
  if (!formData.rectifyDeadline) {
    uni.showToast({ title: '请选择整改截止时间', icon: 'none' })
    return
  }
  
  loading.value = true
  formData.ccTo = formData.ccTo.join(',')
  try {
    // 提交表单数据
    await http.post('/formHiddenDangerRegister/register', formData)
    uni.showToast({
      title: '添加隐患台账成功',
      icon: 'success'
    })
    
    // 跳转回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (error) {
    console.error('提交表单失败:', error)
    uni.showToast({
      title: '提交表单失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchStationList()
  fetchTagsList()
})</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>
        <wd-picker 
          :columns="[stationColumns]" 
          v-model="formData.stationId" 
          @confirm="handleStationConfirm"
        />
      </view>
      
      <!-- 检查名称 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">
          <text class="text-red-500">*</text> 检查名称
        </text>
        <wd-input v-model="formData.checkName" placeholder="请输入检查名称" />
      </view>
      
      <!-- 执行人 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">执行人</text>
        <wd-picker 
          :columns="[executorColumns]" 
          v-model="formData.executorId" 
          @confirm="handleExecutorConfirm"
        />
      </view>
      
      <!-- 是否转任务 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">是否转任务</text>
        <wd-picker 
          :columns="[isTaskList]" 
          v-model="formData.isTask" 
          @confirm="handleIsTaskConfirm"
        />
      </view>
      
      <!-- 发现问题描述 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">
          <text class="text-red-500">*</text> 发现问题描述
        </text>
        <wd-input 
          v-model="formData.foundProblem" 
          placeholder="请输入发现问题描述" 
          type="textarea" 
          rows="4"
        />
      </view>
      
      <!-- 标签 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">标签</text>
        <wd-picker 
          :columns="[tagsList]" 
          v-model="formData.tags" 
          @confirm="handleTagsConfirm"
        />
      </view>
      
      <!-- 处理建议 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">处理建议</text>
        <wd-input 
          v-model="formData.suggestion" 
          placeholder="请输入处理建议" 
          type="textarea" 
          rows="3"
        />
      </view>
      
      <!-- 主要危害描述 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">主要危害描述</text>
        <wd-input 
          v-model="formData.mainHarm" 
          placeholder="请输入主要危害描述" 
          type="textarea" 
          rows="3"
        />
      </view>
      
      <!-- 风险度 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">风险度</text>
        <wd-picker 
          :columns="[riskLevelList]" 
          v-model="formData.riskLevel" 
          @confirm="handleRiskLevelConfirm"
        />
      </view>
      
      <!-- 整改截止时间 -->
      <view class="mb-6">
        <text class="block mb-2 font-medium">
          <text class="text-red-500">*</text> 整改截止时间
        </text>
        <wd-calendar 
          v-model="formData.rectifyDeadline" 
          @confirm="handleDateConfirm" 
        />
      </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-select-picker 
          v-model="formData.ccTo" 
          :columns="userColumns" 
          placeholder="请选择人员"
        />
      </view>
      
      <!-- 提交按钮 -->
      <view class="mt-8 flex justify-center">
        <wd-button 
          type="primary" 
          size="large" 
          @click="submitForm"
          :loading="loading"
        >
          添加隐患台账
        </wd-button>
      </view>
    </view>
  </view>
</template>

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