$(document).ready(async function() {
	const apiBaseUrl = window.location.origin;
	let currentFilePage = 1;
	let totalFilePages = 1;
	let searchKeyword;
	const filePageSize = 10;

	const dataList = await pageQueryTemplates();
	renderTemplates(dataList);


	function renderTemplates(list) {
		const container = $('#file-list');
		container.empty();
		list.forEach(file => {
			const fileItem = $(`
        <div class="file-item">
          <input type="radio" value=${file.signTemplateId} title=${file.signTemplateName}> ${file.signTemplateName}
        </div>
      `);
			container.append(fileItem);
		});
		filePagination()
	}

	async function pageQueryTemplates() {
		const pageIndex = currentFilePage;
		const response = await fetch(
			`${apiBaseUrl}/seeyon/rest/cap4/etemplate/querypage?pageNum=${pageIndex}`, {}
		);
		const res = await response.json();
		// 校验返回值

		console.log(res)
		let respData = res.data;
		totalFilePages = Math.ceil(respData.total / filePageSize);
		return res.data.templateList;
	}

    async function getContractCompareUrl(templateId,templateFileId) {
        const response = await fetch(
        			`${apiBaseUrl}/seeyon/rest/cap4/etemplate/compareurl?templateId=${templateId}&templateFileId=${templateFileId}`, {}
        		);
        		const res = await response.json();
        		// 校验返回值
    }

	function filePagination() {
		    // 分页逻辑
            const pagination = $('#file-pagination');
            pagination.empty();

            const firstBtn = $('<button>首页</button>');
            const prevBtn = $('<button>上一页</button>');
            const nextBtn = $('<button>下一页</button>');
            const pageInfo = $(`<span>第 ${currentFilePage} 页</span>`);

            // 判断是否禁用按钮
            prevBtn.prop('disabled', currentFilePage === 1);

            // 首页按钮点击事件
            firstBtn.click(async () => {
                currentFilePage = 1;  // 跳转到第一页
                await loadTemplates();  // 加载文件
            });

            // 上一页按钮点击事件
            prevBtn.click(async () => {
                if (currentFilePage <= 1) return;  // 防止重复请求
                currentFilePage--;  // 页码减一
                await loadTemplates();  // 加载文件
            });

            // 下一页按钮点击事件
            nextBtn.click(async () => {
                currentFilePage++;  // 页码加一
                await loadTemplates();  // 加载文件
            });

            // 加载文件的逻辑
            async function loadTemplates() {
                let tempTemplateList;

                tempTemplateList = await pageQueryTemplates();

                renderTemplates(tempFileList);  // 渲染文件列表
                pageInfo.text(`第 ${currentFilePage} 页`);  // 更新页数信息
            }

            // 添加按钮到分页容器
            pagination.append(firstBtn, prevBtn, pageInfo, nextBtn);
	}

	function getCookie(name) {
		const value = `; ${document.cookie}`;
		const parts = value.split(`; ${name}=`);
		if (parts.length === 2) return parts.pop().split(';').shift();
	}
})