<template>
  <div style="height: 100%;padding: 10px;">
    <a-row style="height: 100%;" :gutter="[8, 8]">
      <a-col :span="5">
        <a-card title="" :bordered="true" style="width:100%;height:100%;">
         <Left @searchData="setDataList"></Left>
        </a-card>
      </a-col>
      <a-col :span="19">
        <!-- 时间搜索表单 -->
        <div style="margin-bottom: 16px; padding: 12px; background: #f9f9f9; border-radius: 4px;">
          <a-row :gutter="16" align="middle">
            <a-col :span="14">
              <div style="display: flex; align-items: center; gap: 16px;">
                <div style="display: flex; align-items: center;">
                  <span style="margin-right: 8px;">开始日期：</span>
                  <a-date-picker v-model:value="searchForm.stFillTime" style="width: 150px;" />
                </div>
                <div style="display: flex; align-items: center;">
                  <span style="margin-right: 8px;">结束日期：</span>
                  <a-date-picker v-model:value="searchForm.endFillTime" style="width: 150px;" />
                </div>
              </div>
            </a-col>
            <a-col :span="10">
              <a-space :size="5" style="margin-left:0px;">
                <a-button type="primary" @click="handleSearch">查询</a-button>
                <a-button @click="resetSearch">重置</a-button>
              </a-space>
            </a-col>
          </a-row>
        </div>
        
        <vxe-grid v-bind="gridOptions" ref="tableRef">
          <template #toolbarButtons>
            <div style="margin:2px 20px;size:15px">指标填报列表：</div>
            <vxe-button size="small"  @click="handleApproval(1)">审批通过</vxe-button>
            <vxe-button size="small"  @click="handleApproval(2)">审批未通过</vxe-button>

            <div style="margin:auto">
              共搜索到 <span class="count-number">{{ totalRecords }}</span> 条记录
            </div>
           
          </template>
          <template #active="{ row }">
              <vxe-button mode="text" status="primary" @click="saveApproval(row.reportId,1)">通过</vxe-button>
              <vxe-button mode="text" status="error"  @click="saveApproval(row.reportId,2)">退回</vxe-button>
          </template>
          <template #mtrcName="{ row }">
            <a @click="showChartModal(row)" style="color: #409eff; cursor: pointer;">
              {{ row.mtrcName }}
            </a>
          </template>
        </vxe-grid>
      </a-col>
  </a-row>
  
  <!-- 图表弹窗组件 -->
  <MetricChartModal
    v-model:visible="chartModalVisible"
    :title="chartModalTitle"
    :row="currentRow"
    @cancel="handleModalClose"
  />
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import type { VxeGridProps } from 'vxe-table'
import { dataApprovalList,batchSaveApproval } from '../MetricReport.api';
import Left from './left.vue'
import MetricChartModal from './components/MetricChartModal.vue'

interface RowVO {
  id: number
  name: string
  role: string
  sex: string
  age: number
  address: string
}

const tableRef = ref()
const totalRecords = ref()

// 图表弹窗
const chartModalVisible = ref(false)
const chartModalTitle = ref('')
const currentRow = ref<any>(null)

// 搜索表单
const searchForm = reactive({
  stFillTime: null,
  endFillTime: null
})

// 左侧筛选条件
const formData = reactive({})

const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: true,
  showOverflow: true,
  keepSource: true,
  height: "auto",
  exportConfig: {},
  columnConfig: {
    resizable: true
  },

  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true
  },
  cellStyle ({ row, column }) {
    if (column.field === 'appSta') {
      if (row.appSta == '通过') {
        return {
          color: 'blue'
        }
      } else if (row.appSta == '未通过') {
        return {
          color: 'red'
        }
      } else if (row.appSta == '未审批') {
        return {
          backgroundColor: ''
        }
      }
    } else if (column.field === 'riskLevel') {
      if (row.riskLevel == '低风险') {
        return {
          color: '#73D13D'
        }
      } else if (row.riskLevel == '中风险') {
        return {
          color: '#FA8C16'
        }
      } else if (row.riskLevel == '高风险') {
        return {
          color: '#CF1322'
        }
      }
    }
  },
  columns: [
    { type: 'seq', width: 50 },
    { type: 'checkbox', width: 50 },
    
    { field: 'reportId', title: 'id', visible:false },
    { field: 'mtrcNo', title: '指标编码', sortable: true },
    { field: 'mtrcName', title: '指标名称', showOverflow: true, slots: { default: 'mtrcName' } },
    { field: 'collFreq', title: '采集频率', },
    { field: 'timeName', title: '填报时间' },
    { field: 'riskLevel', title: '风险等级' },
    { field: 'domainName', title: '所属领域', showOverflow: true },
    { field: 'mtrcCtp', title: '指标类型' },
    { field: 'fillVals', title: '填报值' },
    { field: 'appSta', title: '状态', },
    { field: 'active', title: '审批', width: 150, fixed: 'right', slots: { default: 'active' } }
  ],
  toolbarConfig: {
    refresh: true,
    export: true,
    zoom: true,
    custom: true,
    slots: {
      buttons: 'toolbarButtons',
    },
  },
  data: []
})

async function setDataList(params = {}) {
  // 存储左侧筛选条件
  Object.assign(formData, params)
  
  // 合并时间搜索条件
  const searchParams = {
    ...params,
    stFillTime: searchForm.stFillTime,
    endFillTime: searchForm.endFillTime
  }
  
  gridOptions.loading = true
  try {
    const res = await dataApprovalList(searchParams);
    gridOptions.data = res || []
    totalRecords.value = res.length
  } catch (error) {
    console.error('加载数据失败:', error)
    gridOptions.data = []
  } finally {
    gridOptions.loading = false
  }
}

const handleApproval = async (appSta)=> {
  const ids = await getSelectIds();
  if(ids.length == 0){
    return;
  }
  batchSaveApproval({
    ids:ids,
    appSta:appSta
  },setDataList)
}

const saveApproval = async (id,sta)=> {
  batchSaveApproval({
    ids:[id],
    appSta:sta
  },function(){
    
  })

}

async function getSelectIds() {
  let ids = [];
  const $table = tableRef.value;
  if ($table) {
    const selRecords = $table.getCheckboxRecords();
    selRecords.forEach(function (ele) {
      ids.push(ele.reportId);
    });
  }
  return ids;
}

// 处理搜索
const handleSearch = async () => {
  await setDataList(formData)
}

// 重置搜索
const resetSearch = () => {
  searchForm.stFillTime = null
  searchForm.endFillTime = null
  setDataList({})
}

onMounted(async () => {
  await setDataList({});
})

// 显示图表弹窗
const showChartModal = (row) => {
  currentRow.value = row
  chartModalTitle.value = `指标详情 - ${row.mtrcName}`
  chartModalVisible.value = true
}

// 处理弹窗关闭
const handleModalClose = () => {
  chartModalVisible.value = false
}

defineExpose({
  setDataList,
})
</script>

<style scoped>
.custom-bottom {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-top: 1px solid #e1e4e8;
}

.record-count {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  font-size: 14px;
  color: #606266;
}

.record-count i {
  margin-right: 8px;
  color: #409eff;
}

.count-number {
  font-weight: bold;
  color: #409eff;
  font-size: 16px;
  margin: 0 4px;
}

:deep(.ant-modal) {
  top: 20px;
}

:deep(.ant-modal-content) {
  height: 90vh;
  display: flex;
  flex-direction: column;
}

:deep(.ant-modal-body) {
  flex: 1;
  overflow: auto;
  padding: 24px;
}

:deep(.ant-tabs-tabpane) {
  transition: none !important;
  height: 100%;
}

:deep(.ant-table-wrapper) {
  height: 100%;
}

:deep(.ant-table-body) {
  overflow-y: auto !important;
}
</style>