<template>
  <a-drawer
    placement="right"
    v-model:open="innerVisible"
    :get-container="true"
    width="100%"
    :title="titile"
    :mask="true"
    @close="handleClose()"
    :style="{ position: 'absolute', paddingTop: '0px', margin: '0px' }"
  >
    <a-card
    style="width: 100%"
    :tab-list="tabList"
    :active-tab-key="activeKey"
    @tabChange="key => onTabChange(key)"
  >
    <template #tabBarExtraContent>
      <div class="date-picker-wrapper">
        <a-space>
          <a-date-picker placeholder="选择年" picker="year">
            <template #renderExtraFooter></template>
          </a-date-picker>
          <a-date-picker v-show="activeKey === 'quarter'" placeholder="选择季度" picker="quarter">
            <template #renderExtraFooter></template>
          </a-date-picker>
          <a-date-picker v-show="activeKey === 'month'" placeholder="选择月" picker="month">
            <template #renderExtraFooter></template>
          </a-date-picker>
        </a-space>
      </div>
    </template>
    <div style="background-color: #ececec; padding: 20px">
        <a-row :gutter="[16,16]">
            <a-col :span="8" v-for="item in dataList" :key="item.id">
                <a-card :bordered="false">
                    <template #title>
                        {{ item.code }} - {{ item.nm }}
                    </template>
                    <template #extra>
                      <a-space>
                        <a href="#" @click.prevent="downLoadXml(item)">直接下载XML</a>
                        <a href="#" @click.prevent="gotoPage(item)">预览</a>
                      </a-space>
                    </template>
                    <span>年度：{{ item.vyear }} &nbsp;</span>
                    <span>版本：{{ item.version }} &nbsp;</span>
                    <span>节点数：{{ item.childNum }}</span><br>
                    <span>{{ item.xmlfilePath }}</span>
                </a-card>
            </a-col>
        </a-row>
    </div>
  </a-card>
  </a-drawer>
</template>

<script lang="ts" setup>  
import { ref, onMounted, computed,nextTick } from 'vue';  
import { allTpls } from '../tpl/BaosongTpl.api';  
import { useRoute,useRouter } from 'vue-router';
import { downLoadTaskXml } from '../review/BaosongTaskReview.api';

const route = useRoute();
const router = useRouter();

// const queryParam = ref({
//   taskId:0,
//   taskName:'',
//   tplId:'',
//   tplName:'',
//   tplCode:''
// })

onMounted(()=>{
  // if (route.query.taskId) {  
  //   queryParam.value.taskId = Number(route.query.taskId); // Convert to number  
  // }  
  // if (route.query.taskName) {  
  //   queryParam.value.taskName = String(route.query.taskName); // Ensure it's a string  
  // } 
  iniData();  
})

const activeKey = ref('year');

// 使用 computed 计算 tabList，根据 dataMap 中的记录数动态设置 disabled
const tabList = computed(() => {
  const tabs = [
    {
      key: 'year',
      tab: '年报',
      type: 1
    },
    {
      key: 'quarter',
      tab: '季报',
      type: 2
    },
    {
      key: 'month',
      tab: '月报',
      type: 3
    },
  ];

  return tabs.map(tab => ({
    ...tab,
    //disabled: !dataMap.value[tab.type] || dataMap.value[tab.type].length === 0
  }));
});

const onTabChange = async (value: string) => {
   activeKey.value = value;
  if(value === 'year') {
    dataList.value = await filteredData(1)
  } else if(value === 'quarter') {
    dataList.value = await filteredData(2)
  } else if(value === 'month') {
    dataList.value = await filteredData(3)
  } else {
    //dataList.value = await filteredData(4)
  }
}

const gotoPage = async (item) => {
  // 确保所有参数都设置完成后再跳转
  // queryParam.value.tplName = item.nm || ''
  // queryParam.value.tplCode = item.code || ''
  // queryParam.value.tplId = item.id || ''
  
  let targetPath = ''
  const code = item.code || ''
  
  if(code === 'T-B-1') {
    targetPath = '/baosong/report/components/Tb1'
  } else if(code === 'T-B-2') {
    targetPath = '/baosong/report/components/Tb2'
  } else if(code === 'T-B-3') {
    targetPath = '/baosong/report/components/Tb3'
  } else if(code === 'T-B-4') {
    targetPath = '/baosong/report/components/Tb4'
  } else if(code === 'T-B-5') {
    targetPath = '/baosong/report/components/Tb5'
  } else if(code === 'T-B-6') {
    targetPath = '/baosong/report/components/Tb6'
  } else if(code === 'T-B-7') {
    targetPath = '/baosong/report/components/Tb7'
  } else if(code === 'T-B-8') {
    targetPath = '/baosong/report/components/Tb8'
  } else if(code === 'T-B-9') {
    targetPath = '/baosong/report/components/Tb9'
  } else if(code === 'T-B-10') {
    targetPath = '/baosong/report/components/Tb10'
  } else if(code === 'T-B-11') {
    targetPath = '/baosong/report/components/Tb11'
  } else if(code === 'R-R-1') {
    targetPath = '/baosong/report/components/Rr1'
  } else if(code === 'R-R-2') {
    targetPath = '/baosong/report/components/Rr2'
  } else if(code === 'T-M-1') {
    targetPath = '/baosong/report/components/Tm1'
  } else if(code === 'T-M-2') {
    targetPath = '/baosong/report/components/Tm2'
  } else if(code === 'T-M-3') {
    targetPath = '/baosong/report/components/Tm3'
  } else if(code === 'T-Q-1') {
    targetPath = '/baosong/report/components/Tq1'
  } else if(code === 'T-Q-2') {
    targetPath = '/baosong/report/components/Tq2'
  } else if(code === 'T-Q-3') {
    targetPath = '/baosong/report/components/Tq3'
  } else if(code === 'T-Q-4') {
    targetPath = '/baosong/report/components/Tq4'
  } else if(code === 'T-Q-5') {
    targetPath = '/baosong/report/components/Tq5'
  }
  
  if (targetPath) {
    await nextTick();
    router.push({
      path: targetPath,
      query: {
        taskId: taskObj.value.id,
        taskName: taskObj.value.name || '',
        tplId: item.id,
        tplName: item.nm || '',
        tplCode: item.code || '',
        comfrom: 'archive'
      }
    });
  }
}

const dataList = ref([])
const dataMap = ref({})  
const dataAllList = ref([])  
const taskObj = ref({})
const innerVisible = ref(false)
const titile = ref('')
async function iniData() {  
    dataAllList.value  = await allTpls({}); 
    dataMap.value = dataAllList.value.reduce((result, item) => {
      const key = item.tp; 
      if (!result[key]) {
        result[key] = [];
      }
      result[key].push(item);
      return result;
    }, {});
    dataList.value = dataMap.value[1]
}  

const filteredData =  (async (tp) => {  
    return dataMap.value[tp]
});

async function downLoadXml(record) {
  let retData = await downLoadTaskXml({
    taskid: taskObj.value.id,
    tplid: record.id,
    tplname: record.nm || '',
    taskname: taskObj.value.name || ''
  });
  handleDownloadFile(retData);
}

const handleDownloadFile = (filePath) => {
  const globOnlineViewUrl: string = import.meta.env.VITE_GLOB_ONLINE_VIEW_URL;
  const url = globOnlineViewUrl + filePath;
  if (url) {
    window.open(url);
  }
};

const handleClose = () => {
  innerVisible.value = false;
}

const openDrawer = (task) => {
  taskObj.value = task
  titile.value = task.name || ''
  innerVisible.value = true;
  iniData();
}
defineExpose({ 
  openDrawer
});
</script>

<style scoped>
.date-picker-wrapper {
  display: flex;
  justify-content: left;
  align-items: left;
  width: 100%;
  padding: 0 20px auto;
  margin-right:500px;
}
</style>