import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import { getNowDate } from './Date';
import { GetTime } from './Date';
// import HTMLModule from 'docx'
function MakerSpaceWord(data,fund){
    //获取模板文件
    let _url = "./file/2023年二级学院特色创客空间建设项目申报书模板.docx";
    const x = new XMLHttpRequest();
    x.open("GET", _url, true);
    x.responseType = "blob";
    x.onload = function (e) {
        const blob = x.response;
        //转成binary
        const reader = new FileReader();
        reader.readAsArrayBuffer(blob);
        reader.onload=function(a){
            const buffer = reader.result;
            const binary = new Uint8Array(buffer)
            //创建一个PizZip实例
            const zip = new PizZip(binary);
            // 将模板内容加载到 Docxtemplater 中
            const doc = new Docxtemplater().loadZip(zip);
            console.log(data)
            //处理项目数据
            data['chapters'] = JSON.parse(data['chapters']);
            data['course_teacher'] = JSON.parse(data['course_teacher']);
            data['course_student'] = JSON.parse(data['course_student']);
            //处理资金使用情况
            let fundDataArray = [];
            fund.forEach(item=>{
                let fundData = {
                    total:"",
                    device:"",deviceRemarks:"",
                    Material:"",MaterialRemarks:"",
                    processing:"",processingRemarks:"",
                    Collaboration:"",CollaborationRemarks:"",
                    APPRAISAL:"",APPRAISALRemarks:"",
                    entery:"",enteryRemarks:"",
                    activities:"",activitiesRemarks:"",
                    Transaction:"",TransactionRemarks:""
                }
                //直接经费

                let direct = JSON.parse(item['directFund']);
                //间接经费
                let indirect = JSON.parse(item['indirectFund']);
    
                direct.forEach(item2=>{
                    if (item2['directFundData']==1) {
                        fundData['device'] = direct.filter(item=>item['directFundData']==1)[0]['budget'];
                        // console.log(fundData['device']);
                        fundData['deviceRemarks'] = direct.filter(item=>item['directFundData']==1)[0]['reason'];
                    }
    
                    if (item2['directFundData']==2) {
                        fundData['Material'] = direct.filter(item=>item['directFundData']==2)[0]['budget']
                        fundData['MaterialRemarks'] = direct.filter(item=>item['directFundData']==2)[0]['reason'];
                    }
                    
                    if (item2['directFundData']==3) {
                        fundData['processing'] = direct.filter(item=>item['directFundData']==3)[0]['budget']
                        fundData['processingRemarks'] = direct.filter(item=>item['directFundData']==3)[0]['reason'];
                    }
                    
        
                    if (item2['directFundData']==4) {
                        fundData['Collaboration'] = direct.filter(item=>item['directFundData']==4)[0]['budget']
                        fundData['CollaborationRemarks'] = direct.filter(item=>item['directFundData']==4)[0]['reason'];
                    }
    
                })
                
                indirect.forEach(item3=>{
                    if (item3['indirectFundData']==1) {
                        fundData['APPRAISAL'] = indirect.filter(item=>item['indirectFundData']==1)[0]['budget']
                        fundData['APPRAISALRemarks'] = indirect.filter(item=>item['indirectFundData']==1)[0]['reason'];
                    }
    
                    if (item3['indirectFundData']==2) {
                        fundData['entery'] = indirect.filter(item=>item['indirectFundData']==2)[0]['budget']
                        fundData['enteryRemarks'] = indirect.filter(item=>item['indirectFundData']==2)[0]['reason'];
                    }
    
                    if (item3['indirectFundData']==3) {
                        fundData['activities'] = indirect.filter(item=>item['indirectFundData']==3)[0]['budget']
                        fundData['activitiesRemarks'] = indirect.filter(item=>item['indirectFundData']==3)[0]['reason'];
                    }
    
                    if (item3['indirectFundData']==4) {
                        fundData['Transaction'] = indirect.filter(item=>item['indirectFundData']==4)[0]['budget']
                        fundData['TransactionRemarks'] = indirect.filter(item=>item['indirectFundData']==4)[0]['reason'];
        
                    }
                })
    
                fundData['total'] = Number(fundData['device'])+Number(fundData['Material'])+Number(fundData['processing'])+Number(fundData['Collaboration'])+Number(fundData['APPRAISAL'])+Number(fundData['entery'])+Number(fundData['activities'])+Number(fundData['Transaction']);
    
                fundDataArray.push(fundData);
            })
            
            //去除标签
            for(let i in data['chapters']){
                data['chapters'][i]=data['chapters'][i].replace(/<[^>]+>/g,"");
            }

            let nowDate = getNowDate().split(' ')[0]

            //模板数据
            let wordData = {
                year:nowDate.split('-')[0],  //申请日期年
                month:nowDate.split('-')[1],   //申请日期月
                day:nowDate.split('-')[2],     //申请日期日
                ing:data['typeName']=='待建设'?"√":"□", //已建设
                ed:data['typeName']=='已建设'?"√":"□",  //待建设
                projectName:data['title'],//项目名称
                college:data['name'],//
                begin_at:data['begin_at'],//项目开始时间
                plannedEnd_at:data['plannedEnd_at'],//计划完成时间
                pro_leader:data['pro_leader'],//项目负责人
                lead_leader:data['lead_leader'],//学院牵头领导
                people:(data['course_teacher'].length+data['course_student'].length),//项目组人数
                teacherNum:data['course_teacher'].length,//参与教师人数
                studentNum:data['course_student'].length,//参与学生人数
                teacher:data['course_teacher'],   //教师组//name：姓名  speciality：专业  title：职称 education：学历    section：所在教研室    work：项目组角色分工
                student:data['course_student'],   //学生组//name：姓名    class：班级 age：年龄   work：项目组任务分工
                brief:data['brief'],//项目简介
                Construction:data['chapters']['Construction'],//建设内容
                ProjectBasis:data['chapters']['ProjectBasis'],//立项依据
                development:data['chapters']['development'],//创客空间物理环境、制度建设及软件设施建设情况
                studio:data['chapters']['studio'],//学生创客工作室建设情况
                studentTeam:data['chapters']['studentTeam'],//学生创客团队（人才）培养预期成果、数量
                studentActivities:data['chapters']['studentActivities'],//学生创客活动组织实施情况
                Transforming:data['chapters']['Transforming'],//学生创客团队孵化、转化创业项目情况
                condition:data['chapters']['condition'],//立 项基 础及条 件
                fund:fundDataArray,//预算经费
                    //total：总经费     
                    //小型仪器设备费：device        deviceRemarks
                    //材料费：Material             MaterialRemarks
                    //测试化验加工费：processing    processingRemarks
                    //项目协作费：Collaboration     CollaborationRemarks
                    //项目成果鉴定费：APPRAISAL     APPRAISALRemarks
                    //参展参赛费：entery            enteryRemarks
                    //创客交流活动费：activities    activitiesRemarks
                    //知识产权事务费：Transaction   TransactionRemarks
            }
            //渲染模板
            doc.setData(wordData);
            doc.render();
            //获取渲染后的文本
            const output = doc.getZip().generate({
                type: "blob",
                mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                compression: "DEFLATE",
            });
            let link = document.createElement("a");
            link.download = '附件3：2023年二级学院特色创客空间建设项目申报书模板(2).docx';
            link.style.display = "none";
            let blob = new Blob([output]);
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        return
    }
    x.send()
}

// 学生创业项目申请表下载模板
function MakerStudentWord(data,fund){
    console.log(data);
    // console.log(fund);
    //获取模板文件
    // ssti-CollegeManage\public\file\2023年学生创客项目申报书模板 .docx
    let _url = "./file/2023年学生创客项目申报书模板.docx";
    // return console.log(_url);

    const x = new XMLHttpRequest();
    x.open("GET",_url, true);
    x.responseType = "blob";
    x.onload = function (e) {
        const blob = x.response;
        //转成binary
        const reader = new FileReader();
        reader.readAsArrayBuffer(blob);
        reader.onload=function(a){
            const buffer = reader.result;
            const binary = new Uint8Array(buffer)
            //创建一个PizZip实例
            const zip = new PizZip(binary);
            // 将模板内容加载到 Docxtemplater 中
            const doc = new Docxtemplater().loadZip(zip);
            //处理项目数据
            // console.log(111);
            // data['chapters'] = data['chapters'];
            // data['course_teacher'] = JSON.parse(data['course_teacher']);
            // data['course_student'] = JSON.parse(data['course_student']);
            // return console.log(data['chapters'],data['course_teacher'],data['course_student']);
            //处理资金使用情况
            let fundDataArray = [];
            fund.forEach(item=>{
                let fundData = {
                    total:"",
                    device:"",deviceRemarks:"",
                    Material:"",MaterialRemarks:"",
                    processing:"",processingRemarks:"",
                    Collaboration:"",CollaborationRemarks:"",
                    APPRAISAL:"",APPRAISALRemarks:"",
                    entery:"",enteryRemarks:"",
                    activities:"",activitiesRemarks:"",
                    Transaction:"",TransactionRemarks:""
                }
                //直接经费
                let direct = JSON.parse(item['directFund']);
                //间接经费
                let indirect = JSON.parse(item['indirectFund']);
    
                direct.forEach(item2=>{
                    if (item2['directFundData']==1) {
                        fundData['device'] = direct.filter(item=>item['directFundData']==1)[0]['budget'];
                        // console.log(fundData['device']);
                        fundData['deviceRemarks'] = direct.filter(item=>item['directFundData']==1)[0]['reason'];
                    }
    
                    if (item2['directFundData']==2) {
                        fundData['Material'] = direct.filter(item=>item['directFundData']==2)[0]['budget']
                        fundData['MaterialRemarks'] = direct.filter(item=>item['directFundData']==2)[0]['reason'];
                    }
                    
                    if (item2['directFundData']==3) {
                        fundData['processing'] = direct.filter(item=>item['directFundData']==3)[0]['budget']
                        fundData['processingRemarks'] = direct.filter(item=>item['directFundData']==3)[0]['reason'];
                    }
                    
        
                    if (item2['directFundData']==4) {
                        fundData['Collaboration'] = direct.filter(item=>item['directFundData']==4)[0]['budget']
                        fundData['CollaborationRemarks'] = direct.filter(item=>item['directFundData']==4)[0]['reason'];
                    }
    
                })
                
                indirect.forEach(item3=>{
                    if (item3['indirectFundData']==1) {
                        fundData['APPRAISAL'] = indirect.filter(item=>item['indirectFundData']==1)[0]['budget']
                        fundData['APPRAISALRemarks'] = indirect.filter(item=>item['indirectFundData']==1)[0]['reason'];
                    }
    
                    if (item3['indirectFundData']==2) {
                        fundData['entery'] = indirect.filter(item=>item['indirectFundData']==2)[0]['budget']
                        fundData['enteryRemarks'] = indirect.filter(item=>item['indirectFundData']==2)[0]['reason'];
                    }
    
                    if (item3['indirectFundData']==3) {
                        fundData['activities'] = indirect.filter(item=>item['indirectFundData']==3)[0]['budget']
                        fundData['activitiesRemarks'] = indirect.filter(item=>item['indirectFundData']==3)[0]['reason'];
                    }
    
                    if (item3['indirectFundData']==4) {
                        fundData['Transaction'] = indirect.filter(item=>item['indirectFundData']==4)[0]['budget']
                        fundData['TransactionRemarks'] = indirect.filter(item=>item['indirectFundData']==4)[0]['reason'];
        
                    }
                })


                
                
    
                
    
                
               
                fundData['total'] = Number(fundData['device'])+Number(fundData['Material'])+Number(fundData['processing'])+Number(fundData['Collaboration'])+Number(fundData['APPRAISAL'])+Number(fundData['entery'])+Number(fundData['activities'])+Number(fundData['Transaction']);
    
                fundDataArray.push(fundData);
            })
            //去除标签
            for(let i in data['chapters']){
                data['chapters'][i]=data['chapters'][i].replace(/<[^>]+>/g,"");
            }

            let nowDate = getNowDate().split(' ')[0]

            //模板数据
            let wordData = {
                // begin_date:data['begin_at'],//项目开始时间
                year:nowDate.split('-')[0],  //申请日期年
                month:nowDate.split('-')[1],   //申请日期月
                day:nowDate.split('-')[2],     //申请日期日
                projectName:data['title'],//项目名称
                ing:data['typeName']==0?"√":"□", //创意组
                ed:data['typeName']==0?"□":"√",  //初创组
                // college:data['name'],//
                mone:data['multiSelectProject'].indexOf(1)!=-1?"√":"□",    //优先支持项目
                mtwo:data['multiSelectProject'].indexOf(2)!=-1?"√":"□",
                mthree:data['multiSelectProject'].indexOf(3)!=-1?"√":"□",
                mfour:data['multiSelectProject'].indexOf(4)!=-1?"√":"□",

                sone:data['schoolRemould']==1?"√":"□", //美丽校园改造项目
                stwo:data['schoolRemould']==2?"√":"□",
                sthree:data['schoolRemould']==3?"√":"□",
                sfour:data['schoolRemould']==4?"√":"□",

                stu:data['projectApplyperson']==1?"√":"□", //项目申请人
                leg:data['projectApplyperson']==1?"□":"√",  

                appPeason:data['pro_leader'], //申请人姓名
                school:data['name'],    //所在学院
                tel:data['phone'],   //联系电话

                begin_at:data['begin_at'],
                plannedEnd_at:data['plannedEnd_at'],

                allnum:(data['course_teacher'].length+data['course_student'].length),//项目组人数
                snum:data['course_teacher'].length,//参与教师人数
                tnum:data['course_student'].length,//参与学生人数

                brief:data['brief'],//项目简介

                back:data['chapters']['back'],
                innovate:data['chapters']['innovate'],
                path:data['chapters']['path'],
                scene:data['chapters']['scene'],
                worth:data['chapters']['worth'],
                team:data['chapters']['team'],
                cost:data['chapters']['cost'],
                expectResults:data['chapters']['expectResults'],
                expectResultsTeacher:data['chapters']['expectResultsTeacher'],
                expectConversion:data['chapters']['expectConversion'],
                plan:data['chapters']['plan'],
            
                teacher:data['course_teacher'],   //教师组//name：姓名  speciality：专业  title：职称 education：学历    section：所在教研室    work：项目组角色分工
                student:data['course_student'],   //学生组//name：姓名    class：班级 age：年龄   work：项目组任务分工
               
                fund:fundDataArray,//预算经费
                    //total：总经费     
                    //小型仪器设备费：device        deviceRemarks
                    //材料费：Material             MaterialRemarks
                    //测试化验加工费：processing    processingRemarks
                    //项目协作费：Collaboration     CollaborationRemarks
                    //项目成果鉴定费：APPRAISAL     APPRAISALRemarks
                    //参展参赛费：entery            enteryRemarks
                    //创客交流活动费：activities    activitiesRemarks
                    //知识产权事务费：Transaction   TransactionRemarks
            }
            //渲染模板
            doc.setData(wordData);
            doc.render();
            //获取渲染后的文本
            const output = doc.getZip().generate({
                type: "blob",
                mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                compression: "DEFLATE",
            });
            let link = document.createElement("a");
            link.download = '2023年学生创客项目申报书.docx';
            link.style.display = "none";
            let blob = new Blob([output]);
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        return
    }
    x.send()
}

//活动管理的申请表
function ActivityWord(data){
    let _url = "./file/附件 2：创客专项资金项目申请表创客活动模板.docx";
    const x = new XMLHttpRequest();
    x.open("GET", _url, true);
    x.responseType = "blob";
    x.onload = function (e) {
        const blob = x.response;
        //转成binary
        const reader = new FileReader();
        reader.readAsArrayBuffer(blob);
        reader.onload=function(a){
            const buffer = reader.result;
            const binary = new Uint8Array(buffer)
            //创建一个PizZip实例
            const zip = new PizZip(binary);
            // 将模板内容加载到 Docxtemplater 中
            const doc = new Docxtemplater().loadZip(zip);
          
            //处理数据
            data['chapters'] = JSON.parse(data['chapters']);
            data['begin_at'] = GetTime(data['begin_at'])
            data['course_teacher'] = JSON.parse(data['course_teacher'])
            //模板数据
            let wordData = {
                activityName:data['title'],//活动名称
                money:data['money'],//预算经费
                pro_leader:data['pro_leader'],//负责人
                class:data['className'],//所在部门
                phone:data['phone'],//联系电话
                activityTime:data['begin_at'],//活动时间
                studentNum:data['students'],//参加学生人数
                teacher:data['course_teacher'],//活动指导教师
                plan:data['chapters'][0].replace(/<[^>]+>/g,""),//活动计划
                Expectations:data['chapters'][1].replace(/<[^>]+>/g,""),//预期目标
                EventAudience:data['chapters'][2].replace(/<[^>]+>/g,""),//活动受众面
                fund:data['chapters'][3].replace(/<[^>]+>/g,""),//经费支出计划
            }
            //渲染模板
            doc.setData(wordData);
            doc.render();
            //获取渲染后的文本
            const output = doc.getZip().generate({
                type: "blob",
                mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                compression: "DEFLATE",
            });
            let link = document.createElement("a");
            link.download = '附件 2：创客专项资金项目申请表（创客活动）.docx';
            link.style.display = "none";
            let blob = new Blob([output]);
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        return
    }
    x.send()
}


export{
    MakerSpaceWord,
    MakerStudentWord,
    ActivityWord
}