<template>
  <div class="pro-cont">
    <div class="pro-title"> {{ activeDownloadGroupId === 1?'问卷设计':'数据分析' }}</div>
    <a-table
      class="pro-table custom-table"
      :columns="columns"
      :data-source="tableData"
      :pagination="false"
      :scroll="{ y: 'calc(100vh - 305px)' }"
      :rowKey="(record,index)=> record.id"
    >
      <template #file_size="{ record }">
        <div>{{ !record.file_size?'-':record.file_size }}</div>
      </template>
      <template #status_str="{ record }">
        <div v-if="record.status===2" @click="clickDownload(record)" class="blue">{{ record.status_str }}</div>
        <div v-else class="status-text"
          :class="
            record.status === 0 || record.status === 1 ? 'green' : record.status === 3 ? 'red' : record.status === 4 ? 'gray' : ''
          ">{{ record.status_str }}</div>
      </template>
      <template v-slot:footer>
        <a-pagination
          class="pagination"
          show-size-changer
          v-model:current="page"
          v-model:pageSize="pageSize"
          v-model:defaultPageSize="pageSize"
          :total="total"
          @change="onPaginationChange"
          @showSizeChange="onShowSizeChange"
        />
      </template>
    </a-table>
  </div>
</template>
<script>
import { defineComponent, ref, watch, getCurrentInstance, computed, onMounted, onUnmounted, } from "vue";
import { useRouter, useRoute } from "vue-router";
import { getDownloadList } from "@/api/download.js";
import { useStore } from "vuex";
const router = useRouter();
const columns = [
  {
    title: "文件名称",
    key: "file_name",
    dataIndex: "file_name",
    // align: "center",
    slots: {
      customRender: "file_name",
    },
  },
  {
    title: "时间",
    key: "created_at",
    dataIndex: "created_at",
    // align: "center",
    // sorter: true,
    sorter: (a, b) => { return a.time> b.time? 1 : -1 },
  },
  {
    title: "文件大小",
    key: "file_size",
    dataIndex: "file_size",
    // align: "center",
    slots: {
      customRender: "file_size",
    },
  },
  {
    title: "状态",
    dataIndex: "status_str",
    key: "status_str",
    // align: "center",
    slots: {
      customRender: "status_str",
    },
  },
];
export default defineComponent({
  name: "DownloadTableList",
  components: {
  },
  props: {
    groupId: { type: Number, value: 0 },
    questionSn: { type: String, default: '' }
  },
  setup(props) {
    const { proxy } = getCurrentInstance();
    const route = useRoute();
    const sn = route.query.sn || props.questionSn;
    const tableData = ref([]);
    const page = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const activeGroupId = ref(0);
    const timer = ref(null)
    const store = useStore();
    const activeDownloadGroupId = computed(() => store.state.groupName.downloadGroupId) || '';
    const onPaginationChange = (current, perPage) => {
      page.value = current;
      pageSize.value = perPage;
      getList();
    };
    const onShowSizeChange = (current, perPage) => {
      page.value = current;
      pageSize.value = perPage;
      getList();
    };
    watch(
      () => props.groupId,
      (newValue, oldValue) => {
        module = newValue
        getList();
      }
    );
    const skipPath = ref('')
    let module
    // 下载中心列表接口
    const getList = async() => {
        try {
            const { data,meta } = await getDownloadList(sn,module,{
              page: page.value,
              per_page: pageSize.value,
            })
            // console.log('下载中心列表data',data,meta);
            tableData.value = data;
            total.value = meta.total;
            let isSetInterval = tableData.value.some(el=>{
              if(el.status===0||el.status===1) {
                return true
              }else{
                return false
              }
            })
            if(isSetInterval) {
              createSetInterval()
            }else{
              stopSetInterval()
            }
        } catch (error) {
            console.error(error)
        }
    }
    const tableIdsData = ref([])
    const getIdsList = async(ids) => {
        try {
            // console.log('module',module);
            const { data } = await getDownloadList(sn,module,{
              page: page.value,
              per_page: pageSize.value,
              ids
            })
            // console.log('下载中心列表data',data);
            tableIdsData.value = data;
            let isClear = tableData.value.every(el=>{
              return el.status!==0&&el.status!==1
            })
            if(isClear) {
              stopSetInterval()
              return
            }
            tableData.value.map(el=>{
              tableIdsData.value.map(idsEl=>{
                if(el.id===idsEl.id) {
                  el.status = idsEl.status
                  el.status_str = idsEl.status_str
                  el.file_url = idsEl.file_url
                  el.file_name = idsEl.file_name
                  el.file_size = idsEl.file_size
                }
              })
            })
        } catch (error) {
            console.error(error)
            stopSetInterval()
        }
    }

    let idsList = ref([])
    // 开启轮询  如果存在则先销毁定时器后重新开启
    const createSetInterval = () => {
      console.log('开启轮询');
      stopSetInterval()
      timer.value = setInterval(() => {
        idsList.value = []
        tableData.value&&tableData.value.some((el) => {
          // console.log('el',el);
          if(el.status===0||el.status===1) idsList.value.push(el.id)
        })
        if(idsList.value) {
          console.log('idsList.value',idsList.value);
          getIdsList(idsList.value.join(','))
        }
      }, 2000)
    }
    // 关闭轮询
    const stopSetInterval = () => {
      if (timer.value) {
        idsList.value = []
        clearInterval(timer.value)
        timer.value = null
      }
    }
    // 下载
    const clickDownload = (record) => {
      console.log('record',record);
        // let url = record.file_url;
        // let a = document.createElement("a"); // 生成一个a元素
        // let event = new MouseEvent("click"); // 创建一个单击事件
        // a.href = url; // 将生成的URL设置为a.href属性
        // a.dispatchEvent(event); // 触发a的单击事件
      // const subdata = {
      //     fileURL:record.file_url,
      //     fileName:record.file_name
      //   }
      // store.dispatch('common/fileDown',subdata)
      window.open(record.file_url, '_self');
    }
    
    onMounted(() => {
      // console.log('skipPath',skipPath);
      // 下载中心列表
      if(store.state?.downloadCenter?.centerUrl?.includes('planet')||store.state?.downloadCenter?.centerUrl?.includes('preview')||store.state?.downloadCenter?.centerUrl==='/home/project') module = 1
      if(store.state?.downloadCenter?.centerUrl?.includes('analyse')) module = 3
      getList();
    })
    onUnmounted (()=>{
      if(timer.value) {
        clearInterval(timer.value)
        timer.value = null
      }
    })
    return {
      sn,
      onPaginationChange,
      onShowSizeChange,
      columns,
      page,
      pageSize,
      total,
      tableData,
      activeGroupId,
      activeDownloadGroupId,
      clickDownload,
    };
  },
});
</script>
<style lang="scss" scoped>
.pro-table {
  overflow: hidden;
  height: calc(100vh - 200px);
}
.pro-table:deep(.ant-table-footer) {
  background: #ffffff;
}
::v-deep .pro-table .ant-table-thead > tr > th {
  color: #434343;
  background: #f5f7fa;
}
.pro-cont {
  padding: 32px;
  background-color: #fff;
  height: 100%;
  .pro-title {
      font-size: 20px;
      font-weight: normal;
      color: #434343;
      margin-bottom: 25px;
  }
}
.status-text {
  font-size: 14px;
  display: flex;
  // justify-content: center;
  align-items: center;
  &::before {
    content: "";
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 8px;
  }
}
.blue {
  cursor: pointer;
  color: #70b936;
  &::before {
    background-color: #70b936;
  }
}
.red {
  color: #FF374F;
  &::before {
    background-color: #FF374F;
  }
}
.green {
  color: #17be6b;
  &::before {
    background-color: #17be6b;
  }
}
.gray {
  color: #8c8c8c;
  &::before {
    background-color: #8c8c8c;
  }
}
.pagination {
  display: inline-flex;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  margin-top: 0;
}
</style>
