<template>
  <!-- 移动端布局 -->
  <el-drawer
    v-if="isMobile"
    v-model="dialogVisible"
    title="处理审批"
    direction="rtl"
    size="100%"
    :close-on-press-escape="true"
    :destroy-on-close="true"
  >
    <div class="mobile-process-form">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-position="top">
        <el-form-item label="审批记录" prop="approvalRecordId">
          <el-select
            v-model="formData.approvalRecordId"
            placeholder="请选择待处理的审批记录"
            filterable
            clearable
            style="width: 100%"
            @change="handleRecordChange"
          >
            <el-option
              v-for="record in pendingRecords"
              :key="record.id"
              :label="`第${record.approvalLevel}级审批 - ${record.applicantName || record.applicant}`"
              :value="record.id"
            >
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>第{{ record.approvalLevel }}级审批</span>
                <el-tag size="small" type="warning">待处理</el-tag>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="审批结果" prop="approvalResult">
          <el-radio-group v-model="formData.approvalResult">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">驳回</el-radio>
            <el-radio :label="3">转审</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="下一级审批人"
          prop="nextApprover"
          v-if="formData.approvalResult === 1 || formData.approvalResult === 3"
        >
          <el-select
            v-model="formData.nextApprover"
            placeholder="请选择下一级审批人"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.nickname"
              :value="String(user.id)"
            />
          </el-select>
          <div style="color: #909399; font-size: 12px; margin-top: 4px">
            {{ formData.approvalResult === 1 ? '通过时可指定下一级审批人，不指定则流程结束' : '转审时必须指定审批人' }}
          </div>
        </el-form-item>

        <el-form-item
          label="指定原因"
          prop="assignReason"
          v-if="formData.approvalResult === 3"
        >
          <el-input
            v-model="formData.assignReason"
            type="textarea"
            :rows="2"
            placeholder="请输入转审原因"
          />
        </el-form-item>

        <el-form-item label="审批意见" prop="comment">
          <el-input
            v-model="formData.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见"
          />
        </el-form-item>

        <!-- 审批信息卡片 -->
        <div class="mobile-process-info" v-if="selectedRecord">
          <div class="mobile-process-info__title">审批信息</div>
          <div class="mobile-process-info__row">
            <span class="mobile-process-info__label">申请人</span>
            <span>{{ selectedRecord.applicantName || selectedRecord.applicant }}</span>
          </div>
          <div class="mobile-process-info__row">
            <span class="mobile-process-info__label">当前审批人</span>
            <span>{{ selectedRecord.approverName || selectedRecord.approver }}</span>
          </div>
          <div class="mobile-process-info__row">
            <span class="mobile-process-info__label">审批层级</span>
            <span>第{{ selectedRecord.approvalLevel }}级</span>
          </div>
          <div class="mobile-process-info__row">
            <span class="mobile-process-info__label">提交时间</span>
            <span>{{ formatDate(selectedRecord.createTime) }}</span>
          </div>
        </div>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
    </template>
  </el-drawer>

  <!-- PC端布局 -->
  <el-dialog v-else v-model="dialogVisible" title="处理审批" width="600px" :close-on-press-escape="true" :destroy-on-close="true">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
      <el-form-item label="审批记录" prop="approvalRecordId">
        <el-select v-model="formData.approvalRecordId" placeholder="请选择待处理的审批记录" filterable clearable style="width: 100%" @change="handleRecordChange">
          <el-option v-for="record in pendingRecords" :key="record.id" :label="`第${record.approvalLevel}级审批 - ${record.applicantName || record.applicant}`" :value="record.id">
            <div style="display: flex; justify-content: space-between; align-items: center"><span>第{{ record.approvalLevel }}级审批</span><el-tag size="small" type="warning">待处理</el-tag></div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审批结果" prop="approvalResult">
        <el-radio-group v-model="formData.approvalResult">
          <el-radio :label="1">通过</el-radio>
          <el-radio :label="2">驳回</el-radio>
          <el-radio :label="3">转审</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="下一级审批人" prop="nextApprover" v-if="formData.approvalResult === 1 || formData.approvalResult === 3">
        <el-select v-model="formData.nextApprover" placeholder="请选择下一级审批人" filterable clearable style="width: 100%">
          <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="String(user.id)" />
        </el-select>
        <div style="color: #909399; font-size: 12px; margin-top: 4px">{{ formData.approvalResult === 1 ? '通过时可指定下一级审批人，不指定则流程结束' : '转审时必须指定审批人' }}</div>
      </el-form-item>
      <el-form-item label="指定原因" prop="assignReason" v-if="formData.approvalResult === 3">
        <el-input v-model="formData.assignReason" type="textarea" :rows="2" placeholder="请输入转审原因" />
      </el-form-item>
      <el-form-item label="审批意见" prop="comment">
        <el-input v-model="formData.comment" type="textarea" :rows="3" placeholder="请输入审批意见" />
      </el-form-item>
    </el-form>
    <!-- 审批信息卡片 -->
    <div class="pc-process-info" v-if="selectedRecord">
      <div class="pc-process-info__title">审批信息</div>
      <el-descriptions :column="2" border size="small">
        <el-descriptions-item label="申请人">{{ selectedRecord.applicantName || selectedRecord.applicant }}</el-descriptions-item>
        <el-descriptions-item label="当前审批人">{{ selectedRecord.approverName || selectedRecord.approver }}</el-descriptions-item>
        <el-descriptions-item label="审批层级">第{{ selectedRecord.approvalLevel }}级</el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ formatDate(selectedRecord.createTime) }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ApprovalRecordApi } from '@/api/erp/approval'
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'
import { formatDate } from '@/utils/formatTime'
import { useUserStore } from '@/store/modules/user'
import { useWindowSize } from '@vueuse/core'

const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)

const message = useMessage()
const userStore = useUserStore()
const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref()
const userList = ref<UserVO[]>([])
const bizId = ref<string>()
const bizTableName = ref<string>()
const pendingRecords = ref<any[]>([])
const selectedRecord = ref<any>(null)

const formData = reactive({
  approvalRecordId: undefined,
  approvalResult: 1,
  comment: '通过',
  nextApprover: '',
  assignReason: ''
})

const formRules = computed(() => ({
  approvalRecordId: [{ required: true, message: '请选择审批记录', trigger: 'change' }],
  approvalResult: [{ required: true, message: '请选择审批结果', trigger: 'change' }],
  nextApprover: formData.approvalResult === 3
    ? [{ required: true, message: '转审时必须指定审批人', trigger: 'change' }]
    : [],
  assignReason: formData.approvalResult === 3
    ? [{ required: true, message: '请输入转审原因', trigger: 'blur' }]
    : [],
  comment: [{ required: true, message: '请输入审批意见', trigger: 'blur' }]
}))

const open = async (bizIdParam: string, bizTableNameParam: string) => {
  bizId.value = bizIdParam
  bizTableName.value = bizTableNameParam
  dialogVisible.value = true

  // 重置表单
  formData.approvalRecordId = undefined
  formData.approvalResult = 1
  formData.comment = '通过'
  formData.nextApprover = ''
  formData.assignReason = ''
  selectedRecord.value = null

  try {
    // 获取用户列表
    userList.value = await UserApi.getSimpleUserList()

    // 获取该业务单据的所有审批记录
    const records = await ApprovalRecordApi.getApprovalRecordListByBiz(bizIdParam, bizTableNameParam)

    // 筛选出当前用户的待处理审批记录
    const currentUserId = getCurrentUserId()
    console.log('Current user ID:', currentUserId)
    console.log('All approval records:', records)

    pendingRecords.value = records.filter((record: any) => {
      console.log(`Checking record - approver: ${record.approver}, currentUserId: ${currentUserId}, approvalResult: ${record.approvalResult}, processStatus: ${record.processStatus}`)
      return record.approver === currentUserId &&
             record.approvalResult === 0 &&
             record.processStatus === 1
    })

    console.log('Filtered pending records:', pendingRecords.value)

    if (pendingRecords.value.length === 0) {
      message.warning('没有待处理的审批记录')
      dialogVisible.value = false
      return
    }

    // 如果只有一条待处理记录，自动选中
    if (pendingRecords.value.length === 1) {
      formData.approvalRecordId = pendingRecords.value[0].id
      selectedRecord.value = pendingRecords.value[0]
    }
  } catch (error) {
    console.error('获取审批记录失败', error)
    message.error('获取审批记录失败')
    dialogVisible.value = false
  }
}

const handleRecordChange = () => {
  selectedRecord.value = pendingRecords.value.find(r => r.id === formData.approvalRecordId)
}

// 监听审批结果变化，自动填充审批意见
watch(() => formData.approvalResult, (newResult) => {
  switch (newResult) {
    case 1:
      formData.comment = '通过'
      break
    case 2:
      formData.comment = '驳回'
      break
    case 3:
      formData.comment = '转审'
      break
    default:
      formData.comment = '通过'
  }
})

const getCurrentUserId = () => {
  // 从用户状态管理获取当前用户ID
  const user = userStore.getUser
  console.log('Current user from store:', user)
  return user.id ? String(user.id) : ''
}

const submitForm = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate()
  if (!valid) return

  loading.value = true
  try {
    await ApprovalRecordApi.processApproval({
      id: formData.approvalRecordId!,
      approvalResult: formData.approvalResult,
      comment: formData.comment,
      nextApprover: formData.nextApprover || undefined,
      assignReason: formData.assignReason || undefined
    })

    message.success('审批处理成功')
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('审批处理失败', error)
  } finally {
    loading.value = false
  }
}

const emit = defineEmits(['success'])
defineExpose({ open })
</script>

<style scoped lang="scss">
.mobile-process-form {
  padding: 12px;
}
.mobile-process-info {
  background: #f0f9eb;
  border-radius: 10px;
  padding: 14px;
  border: 1px solid #e1f3d8;
  &__title {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 10px;
    padding-bottom: 8px;
    border-bottom: 1px solid #e1f3d8;
  }
  &__row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 0;
    font-size: 13px;
    color: #606266;
  }
  &__label {
    color: #909399;
    flex-shrink: 0;
    margin-right: 12px;
  }
}
:deep(.el-select-dropdown__item) {
  height: auto;
  padding: 8px 20px;
}
.pc-process-info {
  background: #f0f9eb;
  border-radius: 8px;
  padding: 14px;
  border: 1px solid #e1f3d8;
  margin-top: 16px;
  &__title {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 10px;
  }
}
</style>
