package com.qmth.teachcloud.eds.service.impl;

import com.qmth.teachcloud.eds.dao.GdpuMapper;
import com.qmth.teachcloud.eds.entity.*;
import com.qmth.teachcloud.eds.service.GdpuService;
import com.qmth.teachcloud.eds.utils.gdpu.JdbcUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * quartz 服务实现类
 */
@Service
public class GdpuServiceImpl implements GdpuService {
    private final static Logger log = LoggerFactory.getLogger(GdpuServiceImpl.class);

    // test为数据库名,?后面这句很重要,设置useSSl=false
    static final String DB_URL = "jdbc:mysql://dexchange.gdpu.edu.cn:3306/ZNKSPT?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8";
    // 数据库的用户名与密码，需要根据自己的设置
    static final String USER = "ZNKSPT";
    static final String PASS = "GdxWs@169139958$";

    @Resource
    private GdpuMapper gdpuMapper;

    @Transactional
    @Override
    public void syncZtXsxx() {
        String sql = "select * from zt_xsxx";

        List<ZtXsxx> ztXsxxList = new JdbcUtil(DB_URL, USER, PASS).query(sql, ZtXsxx.class);
        if (!CollectionUtils.isEmpty(ztXsxxList)) {
            gdpuMapper.deleteZtXsxx();


            List<ZtXsxx> data = new ArrayList<>();
            //5000条提交一次
            for (ZtXsxx ztXsxx : ztXsxxList) {
                if (data.size() == 2000) {
                    gdpuMapper.insertZtXsxx(data);
                    data.clear();
                }
                data.add(ztXsxx);
            }
            //将剩下的数据也导入
            if (!data.isEmpty()) {
                gdpuMapper.insertZtXsxx(data);
            }
        }
    }

    @Override
    public void syncJwxtJgdmb() {
        String sql = "select * from jwxt_jgdmb";
        List<JwxtJgdmb> jwxtJgdmbList = new JdbcUtil(DB_URL, USER, PASS).query(sql, JwxtJgdmb.class);
        if (!CollectionUtils.isEmpty(jwxtJgdmbList)) {
            gdpuMapper.deleteJwxtJgdmb();
            gdpuMapper.insertJwxtJgdmb(jwxtJgdmbList);
        }
    }

    @Override
    public void syncJwxtJyzr() {
        String sql = "select * from jwxt_jyzr";
        List<JwxtJyzr> jwxtJyzrList = new JdbcUtil(DB_URL, USER, PASS).query(sql, JwxtJyzr.class);
        if (!CollectionUtils.isEmpty(jwxtJyzrList)) {
            gdpuMapper.deleteJwxtJyzr();
            gdpuMapper.insertJwxtJyzr(jwxtJyzrList);
        }
    }

    @Override
    public void syncJwxtJzgxxb() {
        String sql = "select * from jwxt_jzgxxb";
        List<JwxtJzgxxb> jwxtJzgxxbList = new JdbcUtil(DB_URL, USER, PASS).query(sql, JwxtJzgxxb.class);
        if (!CollectionUtils.isEmpty(jwxtJzgxxbList)) {
            gdpuMapper.deleteJwxtJzgxxb();
            gdpuMapper.insertJwxtJzgxxb(jwxtJzgxxbList);
        }
    }

    @Override
    public void syncJwxtKcdmb() {
        String sql = "select * from jwxt_kcdmb";
        List<JwxtKcdmb> jwxtKcdmbList = new JdbcUtil(DB_URL, USER, PASS).query(sql, JwxtKcdmb.class);
        if (!CollectionUtils.isEmpty(jwxtKcdmbList)) {
            gdpuMapper.deleteJwxtKcdmb();
            gdpuMapper.insertJwxtKcdmb(jwxtKcdmbList);
        }
    }

    @Override
    public void downloadFile(HttpServletResponse response, String type) {
        File file = new File("/Users/xiaofei/1.xlsx");
        System.out.println(file.getPath());
        try {
            outputFile(response, new FileInputStream(file), "123.xlsx");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
       /* ExcelWriter writer = ExcelUtil.getWriter("/Users/xiaofei/1.xlsx");

        Map<String, String> map = new HashMap<>();
        map.put("jgId", "机构ID");
        map.put("jgmc", "机构名称");
        writer.setHeaderAlias(map);
        JgVo bean1 = new JgVo();
        bean1.setJgId("1");
        bean1.setJgmc("2313");

        JgVo bean2 = new JgVo();
        bean2.setJgId("2");
        bean2.setJgmc("34324");

        List<JgVo> rows = CollUtil.newArrayList(bean1, bean2);
        writer.write(rows, true);

//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=" + SystemConstant.CHARSET_NAME);
//        response.setHeader("Content-Disposition", "attachment;filename=" + type + ".xlsx");
//
//        try {
//            ServletOutputStream out = response.getOutputStream();
//            writer.flush(out, true);
        writer.close();
//            IoUtil.close(out);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }*/

    }

    public static void outputFile(HttpServletResponse response, InputStream inputStream, String fileName) {
        try {
//            byte[] buf = new byte[1024];
//            int len = 0;

            String fName = new String(fileName.getBytes(), "utf8");

            response.reset();
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + fName);

//            OutputStream outStream = response.getOutputStream();

//            while ((len = inputStream.read(buf)) > 0) {
//                outStream.write(buf, 0, len);
//            }

            IOUtils.copy(inputStream, response.getOutputStream());
            inputStream.close();
//            outStream.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }
}

