package com.jfinal.club.my.newsfeed;

import com.jfinal.aop.Inject;
import com.jfinal.club.common.model.Docws;
import com.jfinal.club.common.model.Wsinfo;
import com.jfinal.club.common.model.Wsman;
import com.jfinal.club.util.Cons;
import com.jfinal.club.ws.DocWsService;
import com.jfinal.club.ws.WsInfoService;
import com.jfinal.club.ws.WsmanService;
import com.jfinal.kit.PathKit;
import freemarker.template.Configuration;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.URL;
import java.util.*;


/**
 * @ProjectName: jfinal-club
 * @Package: com.jfinal.template
 * @ClassName: test1
 * @Author: Jzdsh
 * @Description:
 * @Date: 2020/4/10 18:59
 * @Version: 1.0
 */
public class WsDownloadService {
    private Configuration configuration = null;

    @Inject
    DocWsService docWsService;

    @Inject
    WsInfoService wsInfoService;

    @Inject
    WsmanService wsmanService;


    public String createWord(int id) throws IOException {
        try {
            Map< String, Object > dataMap = new HashMap< String, Object >( );
            getData(dataMap, id);
            //模板文件所在路径
            configuration = new Configuration( );
            //防止中文乱码
            configuration.setDefaultEncoding("UTF-8");
            configuration.setClassForTemplateLoading(this.getClass( ), "/");
            URL resource = this.getClass( ).getResource("/");
            System.out.println("**** >> url "+resource );
            //configuration.setDirectoryForTemplateLoading(new File("F:\\idea\\tiezuiwang\\src\\main\\resources\\"));
            freemarker.template.Template t = null;
            try {
                //获取模板文件
                t = configuration.getTemplate("ws.ftl", "UTF-8");
            } catch (IOException e) {
                e.printStackTrace( );
            }
            //导出文件
            File outFile = new File(PathKit.getWebRootPath( ) + Cons.WS_DOC);
            if (!outFile.exists( )) {
                outFile.mkdirs( );
            }
            String fileName = id + System.currentTimeMillis( ) + ".doc";
            File file = new File(outFile.toString( ), fileName);
            Writer out = null;
            try {
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            } catch (FileNotFoundException e1) {
                e1.printStackTrace( );
            }
            try {
                //将填充数据填入模板文件并输出到目标文件
                t.process(dataMap, out);
            } catch (Exception e) {
                e.printStackTrace( );
            } finally {
                out.close( );
            }
            return Cons.WS_DOC + "/" + fileName;
        } catch (IOException e) {
            e.printStackTrace( );
        }
        return null;
    }

    private void getData(Map< String, Object > dataMap, int id) {

        //Docws ws = docWsService.getDocwsById(id);
        Wsinfo wsinfo = wsInfoService.getById(id);

        dataMap.put("wsType", StringUtils.isBlank(wsinfo.getWsType( )) ? "民事起诉状" : wsinfo.getWsType( ));
        dataMap.put("wsRequest", StringUtils.isBlank(wsinfo.getWsRequest( )) ? "xxxxxxxxxx" : wsinfo.getWsRequest( ));
        dataMap.put("wsReason", StringUtils.isBlank(wsinfo.getWsReason( )) ? "xxxxxxxxxx" : wsinfo.getWsReason( ));
        //附件
        List< String > imgList = new ArrayList<>( );
        if (wsinfo != null && StringUtils.isNotBlank(wsinfo.getImg( ))) {
            List< String > im = Arrays.asList(wsinfo.getImg( ).split(","));
            for (int i = 0; i < im.size( ); i++) {
                File file = new File(PathKit.getWebRootPath( ) + im.get(i));
                String imageBase = getImageBase(file);
                imgList.add(imageBase);
            }
        }
        dataMap.put("imgList", imgList != null && imgList.size( ) > 0 ? imgList : null);
        //原告信息
        List< Wsman > ygList = wsmanService.listByWsIdYgbgs(id, Cons.ONE);
        if(ygList != null){
            ygList.forEach(a -> updData(a));
        }
        dataMap.put("ygList", ygList);
        //被告信息
        List< Wsman > bgList = wsmanService.listByWsIdYgbgs(id, Cons.TWO);
        if(bgList != null){
            bgList.forEach(a -> updData(a));
        }
        dataMap.put("bgList", bgList);


    }
    private void updData(Wsman a){
        if (StringUtils.isNotBlank(a.getBirthday( ))) {
            String[] split = a.getBirthday( ).split("-");
            a.setBirthday(split[0] + "年" + split[1] + "月" + split[2] + "日");
        } else {
            a.setBirthday("xxxx年xx月xx日");
        }
        a.setName(StringUtils.isBlank(a.getName( )) ? "xx" : a.getName( ));
        a.setGender(StringUtils.isBlank(a.getGender( )) ? "男" : a.getGender( ));
        a.setNation(StringUtils.isBlank(a.getNation( )) ? "汉族" : a.getNation( ));
        a.setHujiAddress(StringUtils.isBlank(a.getHujiAddress( )) ? "xxxxxxxxxx" : a.getHujiAddress( ));
        a.setNowAddress(StringUtils.isBlank(a.getNowAddress())?"xxxxxxxxxx":a.getNowAddress());
        a.setPhone(StringUtils.isBlank(a.getPhone())?"xxxxxxxxxxx":a.getPhone());
        a.setIdType(StringUtils.isBlank(a.getIdType())?"身份证":a.getIdType());
        a.setIdNumber(StringUtils.isBlank(a.getIdNumber())?"xxxxxxxxxxxxxxxxx":a.getIdNumber());

        a.setCompany(StringUtils.isBlank(a.getCompany( )) ? "xxxxxx" : a.getCompany( ));
        a.setLegalPerson(StringUtils.isBlank(a.getLegalPerson( )) ? "xx" : a.getLegalPerson( ));
        a.setCompanyAddress(StringUtils.isBlank(a.getCompanyAddress( )) ? "xxxxxx" : a.getCompanyAddress( ));
        a.setCreditCode(StringUtils.isBlank(a.getCreditCode( )) ? "xxxxxxxxx" : a.getCreditCode( ));
        a.setLegalPhone(StringUtils.isBlank(a.getLegalPhone( )) ? "xxxxxxxxxxx" : a.getLegalPhone( ));
    }


    //获得图片的base64码
    @SuppressWarnings("deprecation")
    public String getImageBase(File f) {
/*        if(src==null||src==""){
            return "";
        }*/
        File file = f;
        if (!file.exists( )) {
            return "";
        }
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace( );
        }
        try {
            data = new byte[in.available( )];
            in.read(data);
            in.close( );
        } catch (IOException e) {
            e.printStackTrace( );
            return "";
        }
        BASE64Encoder encoder = new BASE64Encoder( );
        return encoder.encode(data);
    }

}
