<script setup name="ProjectManageList">
import { onMounted, onBeforeUnmount, reactive, ref, toRefs, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import QueryForm from './QueryForm.vue'
import { changeRoute } from '@/utils/switchRoute'
import { useRouter } from 'vue-router'
import { queryBatchOriginalList, delBatchTableColumn, loadingBatchTableParams, loadingProgress, getProcesslog } from '@/api/classification/encryptionManagement.js'
import encryptFlag from '@/constants/encryptFlag.js';
const router = useRouter()
const emit = defineEmits(['page'])
function onReset(formQuery) {
  formQuery.resetFields()
  handleQuery()
}
function onQuery() {
  handleQuery()
}
// 搜索按钮操作
function handleQuery() {
  console.log('queryParams',queryParams.value)
  queryParams.value.page = 1
  getList()
}
const data = reactive({
  queryParams: {
    page: 1,
    rows: 10
  }
})
// 表格数据
const { queryParams } = toRefs(data)
const total = ref(3)
const loading = ref(false)
const tableData = ref([]);
// 查询列表
function getList() {
  loading.value = true
  const params = {
    page: queryParams.value.page,
    rows: queryParams.value.rows,
    projectid: sessionStorage.getItem('projectId'),
    datasystemname: queryParams.value.datasource,
    schema: queryParams.value.schema,
    table_name: queryParams.value.tableName,
    columnname: queryParams.value.fieldName,
    flag: queryParams.value.status
  }
  queryBatchOriginalList(params)
    .then((response) => {
      if (response && response.data) {
        tableData.value = response.data || [];
        total.value = response.totalCount || 0;
      } else {
        tableData.value = [];
        total.value = 0;
      }
    })
    .catch((error) => {
      console.error('Failed to fetch table data:', error);
      ElMessage.error('获取表格数据失败，请稍后重试');
    })
    .finally(() => {
      loading.value = false;
    });
}

function pageProjectManage() {
  changeRoute()
  router.push({
    path: '/project/Project'    
  })
}
/**
 * 删除多余列
 */
const deleteUnnecessaryColumns = async () => {
  
  ElMessageBox.confirm('是否确认删除所有多余列？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 确认删除
      const params = {
        projectid: sessionStorage.getItem('projectId')
      }
      try {
        await delBatchTableColumn(params)
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      // 用户取消操作
    }
  })
}


/**
 * 批量加密
 */
const bulkEncryption = async () => {

  ElMessageBox.confirm('是否确认对所有未加密字段进行加密？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  .then(async () => {
    try {
      const params = {
        projectid: sessionStorage.getItem('projectId'),
        operate: "0"
      }
      loadingBatchTableParams(params)
    } catch (error) {
      ElMessage.error('批量加密失败，请稍后重试')
    }
  })
  .catch(() => {
    // 用户取消操作
  })

 
}

/**
 * 批量解密
 */
const batchDecryption = async() => {

  ElMessageBox.confirm('是否确认对所有已加密字段进行解密？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const params = {
        projectid: sessionStorage.getItem('projectId'),
        operate: "1"
      }
     loadingBatchTableParams(params)
    } catch (error) {
      ElMessage.error('批量解密失败，请稍后重试')
    }
  })


}
// 弹窗控制
const dialogVisible = ref(false);
const detailData = ref({});
const handleDetail = async (val) => {
  console.log('查看详情', val);
  const params = {
    projectId: sessionStorage.getItem('projectId'),
    columnName: val.table_field_id,
    dataSystemId: val.datasystem_id,
    schema: val.tschemas,
    tableName: val.names
  }
  const response = await loadingProgress(params)
  if (response && response.code === 'POP_00014' && response.flag) {
  } else {
    ElMessage.error('加载进度失败')
    return 
  }
  console.log('加载进度成功', response);
  const data = response.data[0] || {};

  // 这里根据实际数据结构调整
  detailData.value = {
    fieldName: data.columnName || '',
    status: data.flag || '',
    startTime: data.startTime || '',
    endTime: data.endTime || '',
    totalRows: data.totalCounts || 0,
    finishCounts: data.finishCounts || 0,
    rejectedRows: data.failCounts || 0,
    params: params || {},
    row: val
  };
  dialogVisible.value = true;
}

// 查看日志
const dialogVisibleLog = ref(false);
const logData = ref()
const showLog = async () => {
  const params = {
    projectId: sessionStorage.getItem('projectId'),
    dataSystemId: detailData.value.params.dataSystemId,
    schema: detailData.value.params.schema,
    tableName: detailData.value.params.tableName
  }
  console.log('查看日志params', params);
  const response = await getProcesslog(params)
  if (response && response.code === 'POP_00014' && response.flag) {
    logData.value = response.data || '';
  } else {
    ElMessage.error('加载日志失败')
  }
  dialogVisibleLog.value = true;
  // 这里可以打开日志弹窗或跳转到日志页面
}; 


const downLoad = () => {
  console.log('下载日志');
  const blob = new Blob([logData.value]);
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `${detailData.value.row.datasystemname}-${detailData.value.row.tschemas}.${detailData.value.row.names}_${new Date().toISOString().slice(0, 10)}.log`
  link.click()
  URL.revokeObjectURL(link.href)
};

/**
 * 加密状态标识
 */
const getFlagName = (flag) => {
  const found = encryptFlag.find(item => item.value === String(flag))
  return found ? found: {}
}

let pollingInterval = null;
onMounted(() => {
  getList()
  pollingInterval = setInterval(() => {
    getList();
  }, 5000); // Poll every 5 seconds
});

onBeforeUnmount(() => {
  if (pollingInterval) {
    clearInterval(pollingInterval);
  }
});


/**
 * 详情弹窗轮询
 */
let detailPollingInterval = null;
watch(dialogVisible, (newVal) => {
  if (newVal) {
    detailPollingInterval = setInterval(() => {
      if (detailData.value.params) {
        handleDetail(detailData.value.row);
      }
    }, 5000); // Poll every 5 seconds
  } else {
    if (detailPollingInterval) {
      clearInterval(detailPollingInterval);
      detailPollingInterval = null;
    }
  }
});

</script>

<template>
  <div class="app-container scroller">
    <PageTitle :back="true" @back="pageProjectManage">
      <template #title>
        返回项目管理
      </template>
      <template #buttons>
        <el-button
          type="primary"
          @click="deleteUnnecessaryColumns"
        > 
          删除多余列
        </el-button>
        <el-button
          type="primary"
          @click="bulkEncryption"
        > 
          批量加密
        </el-button>
        <el-button
          type="primary"
          @click="batchDecryption"
        > 
          批量解密
        </el-button>
      </template>
    </PageTitle>
    
    <div class="app-container__body">
      <div>
        <QueryForm
          ref="QueryFormRef"
          v-model="queryParams"
          @query="onQuery"
          @reset="onReset"/>

          <div class="warning-alert">
            <div class="warning-content flex-container align-center">
              <el-icon color="#f33"><WarnTriangleFilled /></el-icon>
              <span class="warning-text">警告：存在未加密字段，请完成历史数据加密操作，否则无法正常使用插件！</span>
            </div>
          </div>
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          >
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="datasystemname" label="数据源名" width="120" show-overflow-tooltip />
            <el-table-column prop="tschemas" label="SCHEMA" align="center" />
            <el-table-column prop="names" label="表名" width="120" show-overflow-tooltip />
            <el-table-column prop="table_field_id" label="字段名" width="120" show-overflow-tooltip />
            <el-table-column prop="column_type" label="字段类型" width="120" show-overflow-tooltip />
            <el-table-column prop="note" label="注释" min-width="120" show-overflow-tooltip />
            <el-table-column prop="encryptiontypename" label="加密算法" min-width="150" show-overflow-tooltip />
            <el-table-column prop="secretkeyname" label="密钥" width="120" show-overflow-tooltip />
            <el-table-column prop="describe_info" label="描述信息" width="120" show-overflow-tooltip />
            <el-table-column prop="flag" label="执行状态" width="120" align="center">
              <template #default="scope">
                <el-tag :type="getFlagName(scope.row.flag).type">
                  {{ getFlagName(scope.row.flag).label }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center" fixed="right">
              <template #default="scope">
                <el-button type="primary" size="small" @click="handleDetail(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.page"
          v-model:limit="queryParams.rows"
          @pagination="getList"
        />
      </div>
    </div>
  <!-- 详情弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    title="数据详情"
    width="50%"
  >
    <el-descriptions 
      border
      :column="1"
      size="large"
      class="detail-container"
    >
      <el-descriptions-item label="字段名">
        {{ detailData.fieldName }}
      </el-descriptions-item>
      
      <el-descriptions-item label="状态">
        <el-tag :type="getFlagName(detailData.status).type">
          {{ getFlagName(detailData.status).label }}
        </el-tag>
      </el-descriptions-item>
      
      <el-descriptions-item label="开始时间">
        {{ detailData.startTime }}
      </el-descriptions-item>
      
      <el-descriptions-item label="结束时间">
        {{ detailData.endTime }}
      </el-descriptions-item>
      
      <el-descriptions-item label="加密/解密总行数">
        {{ detailData.totalRows}}
      </el-descriptions-item>
      
      <el-descriptions-item label="已加密/解密行数">
        {{ detailData.finishCounts}}
      </el-descriptions-item>
      
      <el-descriptions-item label="拒绝条数">
        {{ detailData.rejectedRows}}
      </el-descriptions-item>
    </el-descriptions>
    
    <template #footer>
      <el-button type="primary" @click="showLog">查看日志</el-button>
    </template>
  </el-dialog>


    <el-dialog
      v-model="dialogVisibleLog"
      title="日志"
      width="50%"
    >
    <div class="flex-container flex-wrap">
        <textarea style="width: -webkit-fill-available;" v-model="logData" disabled></textarea>
    </div>
    <template #footer>
      <el-button type="primary" @click="downLoad">下载</el-button>
    </template>
  </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.table-item {
  margin-top: var(--container-pd);
  margin-bottom: 20px;
}

.item-content {
  margin: 8px 0;
  .label {
    width: 80px;
    color: #888;
  }
}

.flex-container { 
  display: flex;
}

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

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

.flex1 {
  flex: 1;
}
.flex-wrap {
  flex-direction: wrap;
  height: 500px;
  overflow-y: scroll;
}
.warning-alert {
  width: 100%;
  padding: 5px 16px;
  margin: 10px 0;
  border: 0.5px solid #f56c6c;
  border-radius: 4px;
  background-color: #fef0f0;
  display: flex;
  align-items: center;
}
.warning-text {
  color: #606266;
  font-size: 14px;
  margin-left: 10px;
}
</style>