package yangtz.cs.liu.campus.controller.studentStatus;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.word.WordExportUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.http.HttpUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import yangtz.cs.liu.campus.domain.student.SchoolStudentParent;
import yangtz.cs.liu.campus.domain.studentTurnover.StudentTurnover;
import yangtz.cs.liu.campus.service.student.ISchoolStudentClassRelationService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentParentService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentService;
import yangtz.cs.liu.campus.service.studentTurnover.IStudentTurnoverService;
import yangtz.cs.liu.campus.util.TemplateExcelUtils;
import yangtz.cs.liu.campus.vo.student.SchoolStudentVO;
import yangtz.cs.liu.wechat.domain.Image;
import yangtz.cs.liu.wechat.vo.userInfo.UserInfoVo;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date: 2023/2/23 10:43
 * @Description:学籍表
 */
@RestController
@RequestMapping("/school/studentStatus")
public class StudentStatusController {
    @Autowired
    private ISchoolStudentService schoolStudentService;

    @Autowired
    private ISchoolStudentClassRelationService relationService;

    @Autowired
    private ISchoolStudentParentService parentService;

    @Autowired
    private IStudentTurnoverService turnoverService;

    @Value("${ruoyi.profile}")
    private String profile;

    /*
     * 导出学籍信息表(针对单个学生)Excel
     * */
    @PostMapping("/exportStatus/{id}")
    public void exportStatus(@PathVariable Long id, HttpServletResponse response){
        //查询学生基本信息
        SchoolStudentVO baseInfo = schoolStudentService.getInfo(id);
        baseInfo.setCurrentGrade("");
        if(StringUtils.isNotNull(baseInfo.getEnrollmentYear()) && !"".equals(baseInfo.getEnrollmentYear())){
            baseInfo.setCurrentGrade("高中"+baseInfo.getEnrollmentYear()+"级");
        }
        //查询监护人信息
        SchoolStudentParent schoolStudentParent=new SchoolStudentParent();
        schoolStudentParent.setStudentId(id);
        List<SchoolStudentParent> parentList = parentService.queryList(schoolStudentParent);
        ///查询异动信息表，添加到备注
        StudentTurnover turnover=new StudentTurnover();
        turnover.setStudentId(id);
        //已办结的
        turnover.setState("2");
        List<StudentTurnover> studentTurnovers = turnoverService.selectStudentTurnoverList(turnover);

        Map<String,Object> map=new HashMap<>();
        map.put("studentName",baseInfo.getStudentName());
        if("0".equals(baseInfo.getSex())){
            map.put("sex","男");
        }else{
            map.put("sex","女");
        }
       // byte[] avatar = HttpUtil.downloadBytes(baseInfo.getAvatar());
        //byte[] avatar = HttpUtil.downloadBytes("https://t7.baidu.com/it/u=4162611394,4275913936&fm=193&f=GIF");
       // byte[] image = ImageUtils.getImage(baseInfo.getAvatar());
        // map.put("avatar",getUrlImage(baseInfo.getAvatar()));
        //map.put("avatar",baseInfo.getAvatar());
        // 图片
        ImageEntity image = new ImageEntity();
        // 这里是设置合并单元格，但是千万不要再模板你提前合并单元格。合并了这里会报错。行合并多少个格子在这里设置。
        image.setRowspan(5);//向下合并三行
        image.setColspan(3);//向右合并三行
        //添加图片存放路径 D:\IMG_0783.JPG
        //路径去掉/profile
        String url = baseInfo.getAvatar();
        if(StringUtils.isNotNull(url) && !"".equals(url)){
            url = url.substring(8);
            image.setUrl(profile+url);
            //表格外添加简单图片
            image.setType(ImageEntity.URL);
            map.put("avatar", image);
        }else{
            map.put("avatar", image);
        }
        map.put("idCard",baseInfo.getIdCard());
        if (StringUtils.isNotNull(baseInfo.getBirthday())){
           map.put("birthday",new SimpleDateFormat("yyyy-MM-dd").format(baseInfo.getBirthday()));
        }
        map.put("nation",baseInfo.getNation());
        map.put("stuTelephone",baseInfo.getStuTelephone());
        map.put("postalCode",baseInfo.getPostalCode());
        map.put("nature",baseInfo.getNature());
        map.put("provincialNumber",baseInfo.getProvincialNumber());
        map.put("nationalNumber",baseInfo.getNationalNumber());
        map.put("schoolNo",baseInfo.getSchoolNo());
        map.put("enrollmentYear",baseInfo.getEnrollmentYear());
        map.put("enrollmentTime",baseInfo.getEnrollmentTime());
        map.put("platform",baseInfo.getPlatform());
        map.put("nativePlace",baseInfo.getNativePlace());
        map.put("homeAddress",baseInfo.getHomeAddress());
        map.put("birthAddress",baseInfo.getBirthAddress());
        map.put("postalAddress",baseInfo.getPostalAddress());
        map.put("studentStatus",baseInfo.getStudentStatus());
        map.put("studentType",baseInfo.getStudentType());
        map.put("schoolYear",baseInfo.getSchoolYear());
        map.put("gradeValue",baseInfo.getCurrentGrade());
        map.put("classValue",baseInfo.getClassValue());
        map.put("registeredAddress",baseInfo.getRegisteredAddress());
        map.put("registeredType",baseInfo.getRegisteredType());
        map.put("juniorSchool",baseInfo.getJuniorSchool());
        map.put("region",baseInfo.getRegion());
        map.put("foreignLanguages",baseInfo.getForeignLanguages());
        if ("2".equals(baseInfo.getAppearance())){
            map.put("appearance","群众");
        }else if("1".equals(baseInfo.getAppearance())){
            map.put("appearance","共青团员");
        }else{
            map.put("appearance","中共党员");
        }
        map.put("bloodType",baseInfo.getBloodType());
        map.put("health",baseInfo.getHealth());
        map.put("otherRegions",baseInfo.getOtherRegions());
        map.put("floatingPopulation",baseInfo.getFloatingPopulation());
        map.put("support",baseInfo.getSupport());
        //独生子女 "0=否,1=是"
        if("0".equals(baseInfo.getOnlyChild())){
            map.put("onlyChild","否");
        }else {
            map.put("onlyChild","是");
        }

        map.put("oneCard",baseInfo.getOneCard());
        if (parentList.size()>0){
        map.put("parentName1",parentList.get(0).getParentName());
       // 0=父亲,1=母亲,2=爷爷,3=奶奶,4=叔叔,5=姑姑

            switch (parentList.get(0).getRelationship()){
                case "0":{map.put("relationship1","父亲");break;}
                case "1":{map.put("relationship1","母亲");break;}
                case "2":{map.put("relationship1","爷爷");break;}
                case "3":{map.put("relationship1","奶奶");break;}
                case "4":{map.put("relationship1","叔叔");break;}
                case "5":{map.put("relationship1","姑姑");break;}
            }

        map.put("workAddress1",parentList.get(0).getWorkAddress());
        map.put("contactAddress1",parentList.get(0).getContactAddress());
        map.put("telephone1",parentList.get(0).getTelephone());
        map.put("postalCode1",parentList.get(0).getPostalCode());
        }
        if(parentList.size()>1){
            map.put("parentName2",parentList.get(1).getParentName());
            switch (parentList.get(1).getRelationship()){
                case "0":{map.put("relationship2","父亲");break;}
                case "1":{map.put("relationship2","母亲");break;}
                case "2":{map.put("relationship2","爷爷");break;}
                case "3":{map.put("relationship2","奶奶");break;}
                case "4":{map.put("relationship2","叔叔");break;}
                case "5":{map.put("relationship2","姑姑");break;}
            }
        map.put("workAddress2",parentList.get(1).getWorkAddress());
        map.put("contactAddress2",parentList.get(1).getContactAddress());
        map.put("telephone2",parentList.get(1).getTelephone());
        map.put("postalCode2",parentList.get(1).getPostalCode());
        }

        //处理异动信息
        if (StringUtils.isNotNull(studentTurnovers) && studentTurnovers.size() > 0){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String turnOverInfo="异动信息为："+"\n";
            for (StudentTurnover info: studentTurnovers) {
                if ("0".equals(info.getChangeType())){
                    turnOverInfo=turnOverInfo+simpleDateFormat.format(info.getEndTime())+",从"+info.getTurnSchool()+"转入"+"\n";
                }
                if ("1".equals(info.getChangeType())){
                    turnOverInfo=turnOverInfo+","+simpleDateFormat.format(info.getEndTime())+",从"+info.getTurnSchool()+"转入借读"+"\n";
                }
                if ("2".equals(info.getChangeType())){
                    turnOverInfo=turnOverInfo+","+simpleDateFormat.format(info.getEndTime())+",从"+info.getTurnSchool()+"转出"+"\n";
                }
                if ("3".equals(info.getChangeType())){
                    turnOverInfo=turnOverInfo+","+simpleDateFormat.format(info.getEndTime())+",从"+info.getTurnSchool()+"转出借读"+"\n";
                }
                if ("4".equals(info.getChangeType())){
                    turnOverInfo=turnOverInfo+","+simpleDateFormat.format(info.getEndTime())+",从"+info.getTurnSchool()+"退学"+"\n";
                }
                if ("5".equals(info.getChangeType())){
                    turnOverInfo=turnOverInfo+","+simpleDateFormat.format(info.getEndTime())+",从"+info.getTurnSchool()+"休学"+"\n";
                }
                if ("6".equals(info.getChangeType())){
                    turnOverInfo=turnOverInfo+","+simpleDateFormat.format(info.getEndTime())+",从"+info.getTurnSchool()+"复学"+"\n";
                }

            }
            map.put("turnoverInfo",turnOverInfo);
        } else {
            map.put("turnoverInfo","暂无异动信息");
        }
        Workbook workbook=null;
        try{
            //Windows
            //Resource classPathResource = new ClassPathResource("template/status.xlsx");
            //获取模板文件相对路径
            //String absolutePath = classPathResource.getFile().getPath();
            //TemplateExportParams params = new TemplateExportParams(absolutePath);
            //Linux
            //获取jar包模板
            TemplateExportParams params = new TemplateExportParams(TemplateExcelUtils.convertTemplatePath("template/status.xlsx"));

            // 设置字符编码
            response.setCharacterEncoding("utf-8");
            // 设置响应头
            response.setHeader("Content-disposition", "attachment;filename=demo.xlsx");

            // 设置文本内省
            response.setContentType("application/vnd.ms-excel");
            response.flushBuffer();
            workbook = ExcelExportUtil.exportExcel(params, map);
            workbook.write(response.getOutputStream());
            response.setHeader("Content-Length", String.valueOf(response.getOutputStream().toString().length()));
        }catch (Exception e){
            throw new ServiceException("下载出错");
        }finally {
            if (workbook!=null){
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
}

    /**
     * 学籍证明(针对单个学生)Word
     */
    @PostMapping("/proofStatus/{id}")
    public void proofStatus(@PathVariable Long id, HttpServletResponse response){
        //查询学生基本信息
        SchoolStudentVO baseInfo = schoolStudentService.getInfo(id);

        Map<String,Object> map=new HashMap<>();
        map.put("studentName",baseInfo.getStudentName());
        if("0".equals(baseInfo.getSex())){


            map.put("sex","男");
        }else{
            map.put("sex","女");
        }
        if (StringUtils.isNotNull(baseInfo.getBirthday())){
            map.put("birthday",new SimpleDateFormat("yyyy-MM-dd").format(baseInfo.getBirthday()));
        }
        map.put("idCard",baseInfo.getIdCard());
        // 图片
        //路径去掉/profile
        String url = baseInfo.getAvatar();
        if(StringUtils.isNotNull(url) && !"".equals(url)){
            url = url.substring(8);
            map.put("avatar", this.imgFormatting(profile+url,200,200));
        }else{
            //map.put("avatar", image);
        }

        map.put("provincialNumber",baseInfo.getProvincialNumber());
        map.put("nationalNumber",baseInfo.getNationalNumber());
        map.put("enrollmentYear",baseInfo.getEnrollmentYear());
        map.put("nativePlace",baseInfo.getNativePlace());
        map.put("gradeValue",baseInfo.getGradeName());
        map.put("classValue",baseInfo.getClassValue());
        map.put("today", DateUtils.getDate());
        XWPFDocument xwpfDocument=null;
        try {
            // 读取模板
            Resource classPathResource = new ClassPathResource("template/proof.docx");

            //获取模板文件绝对路径
            //String absolutePath = classPathResource.getAbsolutePath();
            //获取模板文件相对路径
            //String absolutePath = classPathResource.getFile().getPath();

            //获取jar包中模板路径
            String absolutePath = TemplateExcelUtils.convertTemplatePath("template/proof.docx");
            xwpfDocument = WordExportUtil.exportWord07(absolutePath, map);
            // 设置字符编码
            response.setCharacterEncoding("utf-8");
            // 设置响应头
            response.setHeader("Content-disposition", "attachment;filename=学籍证明.docx");
            // 设置文本内省
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.flushBuffer();
            xwpfDocument.write(response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("下载出错");
        }finally {
            if (xwpfDocument!=null){
                try {
                    xwpfDocument.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 图片格式化，Word导出图片格式
     *
     * @param imgPath 图片路径
     */
    private ImageEntity imgFormatting(String imgPath, int width, int height) {
        //设置图片
        ImageEntity image = new ImageEntity(imgPath, width, height);
        //表格外添加简单图片
        image.setType(ImageEntity.URL);
        return image;
    }

    /**
     * @Description: 从地址获取图片
     * @param:
     * @return:
     */
    public static BufferedImage getUrlImage(String url) {
        byte[] bytes = HttpUtil.downloadBytes(url);
        InputStream buffin = new ByteArrayInputStream(bytes,0,bytes.length);
        BufferedImage img = null;
        try {
            img = ImageIO.read(buffin);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return img;
    }
}
