<template>
  <div class="system-regulation">
    <a-card title="已发布制度确认" :bordered="false">
      
      
      <a-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #confirmStatus="{ record }">
          <a-tag :color="record.confirmStatus === 'confirmed' ? 'green' : 'orange'">
            {{ record.confirmStatus === 'confirmed' ? '已确认' : '待确认' }}
          </a-tag>
        </template>
        
        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleView(record)">
              查看详情
            </a-button>
            <a-button type="text" size="small" @click="handleDownload(record)">
              下载
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 制度详情弹窗 -->
    <a-modal
      v-model:visible="detailModalVisible"
      title="制度详情"
      width="800px"
      :footer="false"
    >
      <div class="regulation-detail" v-if="currentRegulation">
        <div class="detail-header">
          <h3>{{ currentRegulation.title }}</h3>
          <div class="detail-meta">
            <span>发布人: {{ currentRegulation.createBy }}</span>
            <span>发布时间: {{ currentRegulation.publishTime }}</span>
            <span>生效日期: {{ currentRegulation.effectiveTime }}</span>
          </div>
        </div>
        
        <a-divider />
        
        <div class="detail-content">
          <h4>制度内容</h4>
          <div class="content-text">{{ currentRegulation.content }}</div>
          
          <h4>适用范围</h4>
          <div class="content-text">{{ currentRegulation.scope }}</div>
          
          <h4>实施要求</h4>
          <div class="content-text">{{ currentRegulation.requirements }}</div>
          
          <h4>注意事项</h4>
          <div class="content-text">{{ currentRegulation.notes }}</div>
        </div>
        
        <a-divider />
        
        <div class="detail-footer">
          <a-button type="primary" @click="handleConfirm(currentRegulation)">
            确认知晓并遵守
          </a-button>
          <a-button @click="handleDownload(currentRegulation)">
            下载制度文件
          </a-button>
        </div>
      </div>
    </a-modal>

    <!-- 确认承诺弹窗 -->
    <a-modal
      v-model:visible="confirmModalVisible"
      title="制度确认承诺"
      width="600px"
      @ok="submitConfirm"
      @cancel="confirmModalVisible = false"
    >
      <div class="confirm-content">
        <p>我确认已仔细阅读并理解《{{ currentRegulation?.title }}》的全部内容，承诺：</p>
        <ul>
          <li>严格遵守该制度的各项规定</li>
          <li>认真履行相关职责和义务</li>
          <li>如有违反，愿意承担相应责任</li>
        </ul>
        
        <a-checkbox v-model="agreeTerms">
          我已阅读并同意上述承诺
        </a-checkbox>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { Regulation } from '@/apis/regulation/type'
import { Message } from '@arco-design/web-vue'
import { useRegulationStore } from '@/stores/modules/regulation'
import { regulationApi } from '@/apis/regulation'

defineOptions({ name: 'SystemRegulation' })

// 表格列定义
const columns = [
  { title: '制度名称', dataIndex: 'title', key: 'title' },
  { title: '制度类型', dataIndex: 'regulationType', key: 'regulationType' },
  { title: '发布人', dataIndex: 'createBy', key: 'createBy' },
  { title: '发布时间', dataIndex: 'publishTime', key: 'publishTime' },
  { title: '生效日期', dataIndex: 'effectiveTime', key: 'effectiveTime' },
  { title: '确认状态', dataIndex: 'confirmStatus', key: 'confirmStatus', slotName: 'confirmStatus' },
  { title: '操作', key: 'operations', slotName: 'operations', width: 250 }
]

// 表格数据
const tableData = ref<Regulation[]>([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showJumper: true,
  showPageSize: true
})

// 弹窗相关
const detailModalVisible = ref(false)
const confirmModalVisible = ref(false)
const currentRegulation = ref<Regulation | null>(null)
const agreeTerms = ref(false)

// 制度管理store
const regulationStore = useRegulationStore()

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    const response = await regulationApi.getPublishedRegulationList({
      page: pagination.current,
      size: pagination.pageSize,
      status: "PUBLISHED"
    })
    
    if (response.status === 200) {
      tableData.value = response.data.records
      pagination.pageSize = response.data.size
      pagination.current = response.data.current
      pagination.total = response.data.total
    } else {
      Message.error('获取数据失败')
    }
  } catch (error) {
    console.error('获取已发布制度列表失败:', error)
    Message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 分页事件
const onPageChange = (page: number) => {
  pagination.current = page
  getTableData()
}

const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  getTableData()
}

// 查看详情
const handleView = (record: any) => {
  currentRegulation.value = record
  detailModalVisible.value = true
}

// 确认知晓
const handleConfirm = (record: any) => {
  currentRegulation.value = record
  confirmModalVisible.value = true
  agreeTerms.value = false
}

// 下载
const handleDownload = (record: any) => {
  try {
    // 创建制度文档内容
    const content = `
制度名称：${record.title}
制度类型：${record.regulationType}
发布人：${record.createBy}
发布时间：${record.publishTime}
生效日期：${record.effectiveTime}

制度内容：
${record.content}

适用范围：
${record.scope}

实施要求：
${record.requirements || '请按照制度要求执行'}

注意事项：
${record.notes || '请严格遵守制度规定'}
    `.trim()

    // 创建Blob对象
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })

    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${record.title}.txt`

    // 触发下载
    document.body.appendChild(link)
    link.click()

    // 清理
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    Message.success('制度文件下载成功')
  } catch (error) {
    Message.error('下载失败')
    console.error('下载错误:', error)
  }
}



// 提交确认
const submitConfirm = async () => {
  if (!agreeTerms.value) {
    Message.warning('请先同意承诺条款')
    return
  }
  
  try {
    if (currentRegulation.value) {
      await regulationApi.confirmRegulation(currentRegulation.value.regulationId)
      
      Message.success('确认成功，您已承诺遵守该制度')
      confirmModalVisible.value = false
      
      // 更新本地数据状态
      const index = tableData.value.findIndex(item => item.regulationId === currentRegulation.value.regulationId)
      if (index !== -1) {
        tableData.value[index].confirmStatus = 'confirmed'
      }
    }
  } catch (error) {
    console.error('确认失败:', error)
    Message.error('确认失败')
  }
}

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

<style scoped lang="scss">
.system-regulation {
  .arco-card {
    margin-bottom: 16px;
  }
}

.regulation-detail {
  .detail-header {
    margin-bottom: 16px;
    
    h3 {
      margin-bottom: 12px;
      color: var(--color-text-1);
    }
    
    .detail-meta {
      display: flex;
      gap: 16px;
      color: var(--color-text-3);
      font-size: 14px;
    }
  }
  
  .detail-content {
    h4 {
      margin: 16px 0 8px 0;
      color: var(--color-text-1);
      font-weight: 500;
    }
    
    .content-text {
      color: var(--color-text-2);
      line-height: 1.6;
      margin-bottom: 16px;
      padding: 12px;
      background: var(--color-fill-1);
      border-radius: 6px;
    }
  }
  
  .detail-footer {
    display: flex;
    gap: 12px;
    justify-content: center;
  }
}

.confirm-content {
  p {
    margin-bottom: 16px;
    color: var(--color-text-1);
    line-height: 1.6;
  }
  
  ul {
    margin-bottom: 20px;
    padding-left: 20px;
    
    li {
      margin-bottom: 8px;
      color: var(--color-text-2);
      line-height: 1.5;
    }
  }
}
</style> 