package com.zd.laboratory.service.impl;

import cn.hutool.core.date.DateUtil;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.policy.PictureRenderPolicy;
import com.deepoove.poi.util.BufferedImageUtils;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.FileConfigUtils;
import com.zd.laboratory.domain.LabCheckOption;
import com.zd.laboratory.domain.LabCheckRecord;
import com.zd.laboratory.domain.LabCheckRecordDetails;
import com.zd.laboratory.mapper.LabCheckOptionMapper;
import com.zd.laboratory.mapper.LabCheckRecordDetailsMapper;
import com.zd.laboratory.mapper.LabCheckRecordMapper;
import com.zd.laboratory.service.ILabCheckOptionService;
import com.zd.laboratory.utils.word.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class WordService {

    @Autowired
    private LabCheckOptionMapper labCheckOptionMapper;
    @Autowired
    private ILabCheckOptionService labCheckOptionService;
    @Autowired
    private LabCheckRecordMapper labCheckRecordMapper;
    @Autowired
    private LabCheckRecordDetailsMapper labCheckRecordDetailsMapper;
    @Autowired
    private FileConfigUtils fileConfigUtils;


    /**
     * PC多选 生成整改告知书
     */
    public void genNotify(Long[] ids, HttpServletResponse response) {
        try {

            Word1 word1 = new Word1();

            // 待杨森确认多选数据时 学院信息展示冲突问题，再赋值 -- 确定结果未生成文件限制只能以学院为单位生成
            Date now = new Date();

            word1.setCheck_year((DateUtil.year(now) + ""));
            word1.setCheck_month((DateUtil.month(now) + 1) + "");
            word1.setCheck_day(DateUtil.dayOfMonth(now) + "");

            LabCheckRecord checkRecord;
            List<LabCheckRecordDetails> checkRecordDetails;
            LabCheckRecordDetails labCheckRecordDetails = new LabCheckRecordDetails();

            List<Word1.Detail> list = new ArrayList<>();
            String dept_name = null, check_dept_name = null;
            for (int i = 0; i < ids.length; i++) {

                checkRecord = labCheckRecordMapper.selectLabCheckRecordById(ids[i]);
                if(checkRecord == null){
                    continue;
                }
                // 展示的学院和检查学院只取第一个
                if(dept_name == null){
                    dept_name = checkRecord.getBuildingName();
                }
                if(check_dept_name == null){
                    check_dept_name = checkRecord.getJcDwName();
                }


                labCheckRecordDetails.setCheckId(checkRecord.getId());
                checkRecordDetails = labCheckRecordDetailsMapper.selectLabCheckRecordDetailsList(labCheckRecordDetails);

                for (LabCheckRecordDetails checkRecordDetail : checkRecordDetails) {
                    Word1.Detail detail = word1.new Detail();
                    detail.setIndex((1+i)+"");
                    // 实验室名称
                    detail.setSub_name(checkRecord.getLaboratoryName());
                    // 隐患描述
                    detail.setCheck_desc(checkRecordDetail.getYhMs());
                    // 隐患照片，TODO 需要注意多个的情况
                    detail.setCheck_img(checkRecordDetail.getYhImg());
                    // 检查项名称，需要注意多级展示
                    detail.setCheck_option_name(checkRecordDetail.getJcxName());
                    list.add(detail);
                }

            }

            word1.setCheck_dept_name(check_dept_name);
            word1.setDept_name(dept_name);

            WordUtils.getWord1(word1, list,response);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 小程序单个 生成整改通知书
     */
    public void genNotice(Long id, HttpServletResponse response, HttpServletRequest request) {
        try {
            LabCheckRecord checkRecord = labCheckRecordMapper.selectLabCheckRecordById(id);
            if(checkRecord == null){
                throw new ServiceException("生成失败，ID无效！");
            }

            String baseUrl = request.getServerName();
            boolean isIntranet = false;
            if(baseUrl.contains("192.168")){
                isIntranet = true;
            }

            LabCheckRecordDetails labCheckRecordDetails = new LabCheckRecordDetails();
            labCheckRecordDetails.setCheckId(checkRecord.getId());
            List<LabCheckRecordDetails> checkRecordDetails = labCheckRecordDetailsMapper.selectLabCheckRecordDetailsList(labCheckRecordDetails);

            Word2 word2 = new Word2();
            // 学院名称
            word2.setDept_name(checkRecord.getBuildingName());
            // 实验室名称
            word2.setSub_name(checkRecord.getLaboratoryName());

            word2.setCheck_year(DateUtil.year(checkRecord.getCreateTime()) + "");
            word2.setCheck_month((DateUtil.month(checkRecord.getCreateTime()) + 1) + "");
            word2.setCheck_day(DateUtil.dayOfMonth(checkRecord.getCreateTime()) + "");
            // 需杨森确认 编码到底是什么
            word2.setCode(checkRecord.getCheckNum());
            word2.setCount(checkRecordDetails.size()+"");

            // 晓飞处理检查单位后修改
            String deptSign = labCheckRecordMapper.queryDeptSignByDeptId(Long.parseLong(checkRecord.getJcDw()));
            if(deptSign == null){
                deptSign = "";
            }else {
                deptSign = (isIntranet ? fileConfigUtils.getLocalUrl() :  fileConfigUtils.getRemoteUrl())  + deptSign;
            }

//            word2.setCheck_dept_sign(new PictureRenderData(100, 100, PictureType.PNG, BufferedImageUtils.getUrlBufferedImage(deptSign)));
            word2.setCheck_dept_sign(new SignPictureRenderData(100, 100, deptSign, "图片加载失败", 310 ,-35));
            word2.setCheck_dept_name(checkRecord.getJcDwName());
            word2.setCheck_result(checkRecord.getZgJg());

            Date now = new Date();

            word2.setNow_year(DateUtil.year(now) + "");
            word2.setNow_month((DateUtil.month(now) + 1) + "");
            word2.setNow_day(DateUtil.dayOfMonth(now) + "");
            word2.setCheck_room(checkRecord.getFjNumber());
            word2.setCheck_date(DateUtil.format(checkRecord.getCreateTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
            // 检查人名称 - 2.6 更换为用户签名
            //word2.setCheck_nick_name(checkRecord.getJcRyxm());

            String signature = labCheckRecordMapper.selectSignatureByUserId(checkRecord.getCreateUserId());
            word2.setCheck_nick_name(new PictureRenderData(100, 30, PictureType.PNG, BufferedImageUtils.getUrlBufferedImage(
                            (isIntranet ? fileConfigUtils.getLocalUrl() :  fileConfigUtils.getRemoteUrl())  + signature
                    )));

            List<Word2.Detail> list = new ArrayList<>();

            LabCheckOption option;
            String optionId = null;
            for (int i = 0; i < checkRecordDetails.size(); i++) {
                Word2.Detail detail = word2.new Detail();
                detail.setIndex((i+1)+"");
                // 添加检查项 编码之后补充
                // 数据形式存在 1,2,3, 1,, 1,  31,,, 等形式，故需要特殊处理
                if(checkRecordDetails.get(i).getJcxId() != null){
//                    optionId = checkRecordDetails.get(i).getJcxId().substring(0, checkRecordDetails.get(i).getJcxId().lastIndexOf(","));
//                    if(optionId.lastIndexOf(",") != -1){
//                        optionId = optionId.substring(optionId.lastIndexOf(","));
//                    }

                    String[] ids = checkRecordDetails.get(i).getJcxId().split(",");
                    List<String> list1 = Arrays.asList(ids);
                    for (int i1 = 0; i1 < list1.size(); i1++) {
                        if(StringUtils.isBlank(list1.get(i1))){
                            list1.remove(i1);
                            i--;
                        }
                    }

                    if(list1.size() == 0){
                        continue;
                    }else {
                        optionId = list1.get(list1.size() - 1);
                    }

                    option = labCheckOptionMapper.selectLabCheckOptionById(Long.parseLong(optionId));
                    if(option != null){
                        detail.setOption_code(option.getCode());
                    }else {
                        detail.setOption_code("");
                    }
                }else {
                    detail.setOption_code("");
                }
                detail.setCheck_desc(checkRecordDetails.get(i).getYhMs());
                //  需注意多个图片的展示情况
                String yhImgs = checkRecordDetails.get(i).getYhImg();
                String[] imgs = yhImgs.split(",");
                if(imgs.length > 0){
                    detail.setCheck_img1((isIntranet ? fileConfigUtils.getLocalUrl() :  fileConfigUtils.getRemoteUrl())  + imgs[0]);
                }
                if(imgs.length > 1){
                    detail.setCheck_img2((isIntranet ? fileConfigUtils.getLocalUrl() :  fileConfigUtils.getRemoteUrl())  + imgs[1]);
                }
                if(imgs.length > 2){
                    detail.setCheck_img3((isIntranet ? fileConfigUtils.getLocalUrl() :  fileConfigUtils.getRemoteUrl())  + imgs[2]);
                }
                if(imgs.length > 3){
                    detail.setCheck_img4((isIntranet ? fileConfigUtils.getLocalUrl() :  fileConfigUtils.getRemoteUrl())  + imgs[3]);
                }
                if(imgs.length > 4){
                    detail.setCheck_img5((isIntranet ? fileConfigUtils.getLocalUrl() :  fileConfigUtils.getRemoteUrl())  + imgs[4]);
                }

                list.add(detail);
            }

            WordUtils.getWord2(word2, list,response);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 小程序单个 生成整改报告
     */
    public void genReport(Long id, HttpServletResponse response, HttpServletRequest request) {
        try {

            LabCheckRecord checkRecord = labCheckRecordMapper.selectLabCheckRecordById(id);
            if(checkRecord == null){
                throw new ServiceException("生成失败，ID无效！");
            }

            String baseUrl = request.getServerName();
            boolean isIntranet = false;
            if(baseUrl.contains("192.168")){
                isIntranet = true;
            }

            LabCheckRecordDetails labCheckRecordDetails = new LabCheckRecordDetails();
            labCheckRecordDetails.setCheckId(checkRecord.getId());
            List<LabCheckRecordDetails> checkRecordDetails = labCheckRecordDetailsMapper.selectLabCheckRecordDetailsList(labCheckRecordDetails);

            Word3 word3 = new Word3();
            // 编号需产品确认
            word3.setCode(checkRecord.getCheckNum());

            word3.setDept_name(checkRecord.getBuildingName());
            word3.setCheck_nick_name(checkRecord.getJcRyxm());
            word3.setSub_name(checkRecord.getLaboratoryName());
            word3.setCheck_room(checkRecord.getFjNumber());
            Date now = new Date();
            word3.setNow_year(DateUtil.year(now) + "");
            word3.setNow_month((DateUtil.month(now) + 1) + "");
            word3.setNow_day(DateUtil.dayOfMonth(now) + "");
            word3.setCheck_year(DateUtil.year(checkRecord.getCreateTime()) + "");
            word3.setCheck_month((DateUtil.month(checkRecord.getCreateTime()) + 1) + "");
            word3.setCheck_day(DateUtil.dayOfMonth(checkRecord.getCreateTime()) + "");
            word3.setCount(checkRecordDetails.size()+"");

            String deptSign = labCheckRecordMapper.queryDeptSignByDeptId(Long.parseLong(checkRecord.getJcDw()));
            if(deptSign == null){
                deptSign = "";
            }else {
                deptSign = (isIntranet ? fileConfigUtils.getLocalUrl() :  fileConfigUtils.getRemoteUrl())  + deptSign;
            }
            word3.setCheck_dept_sign(new SignPictureRenderData(100, 100, deptSign, "图片加载失败", 300 ,-55));

            List<Word3.Detail> list = new ArrayList<>();
            List<Word3.Descs> descs = new ArrayList<>();

            int finishCount = 0;
            int unCount = 0;
            LabCheckOption option;
            String optionId = null;
            for (int i = 0; i < checkRecordDetails.size(); i++) {
                Word3.Detail detail = word3.new Detail();
                detail.setIndex((i+1)+"");
                // 添加检查项 编码之后补充
                // 数据形式存在 1,2,3, 1,, 1,  31,,, 等形式，故需要特殊处理
                if(checkRecordDetails.get(i).getJcxId() != null){
//                    optionId = checkRecordDetails.get(i).getJcxId().substring(0, checkRecordDetails.get(i).getJcxId().lastIndexOf(","));
//                    if(optionId.lastIndexOf(",") != -1){
//                        optionId = optionId.substring(optionId.lastIndexOf(","));
//                    }

                    String[] ids = checkRecordDetails.get(i).getJcxId().split(",");
                    List<String> list1 = Arrays.asList(ids);
                    for (int i1 = 0; i1 < list1.size(); i1++) {
                        if(StringUtils.isBlank(list1.get(i1))){
                            list1.remove(i1);
                            i--;
                        }
                    }

                    if(list1.size() == 0){
                        continue;
                    }else {
                        optionId = list1.get(list1.size() - 1);
                    }

                    option = labCheckOptionMapper.selectLabCheckOptionById(Long.parseLong(optionId));
                    if(option != null){
                        detail.setOption_code(option.getCode());
                    }else {
                        detail.setOption_code("");
                    }
                }else {
                    detail.setOption_code("");
                }


                detail.setCheck_desc(checkRecordDetails.get(i).getYhMs());
                // 需注意多个图片的展示情况 - 此处不展示图片
                //detail.setCheck_img(checkRecordDetails.get(i).getYhImg());
                list.add(detail);
                if(checkRecordDetails.get(i).getIsZg() == null || checkRecordDetails.get(i).getIsZg() == 1){
                    unCount ++;
                }else {
                    finishCount ++;
                }

                Word3.Descs desc = word3.new Descs();
                desc.setIndex(WordUtils.CN_NUM[i]);
                desc.setCheck_option_name(checkRecordDetails.get(i).getJcxName());
                desc.setCheck_desc(checkRecordDetails.get(i).getYhMs());
                desc.setCheck_cause(checkRecordDetails.get(i).getZgYyfx());
                desc.setCheck_result(checkRecordDetails.get(i).getZgCs());

                String yhImgs = checkRecordDetails.get(i).getYhImg();
                String[] imgs = yhImgs.split(",");
                if(imgs.length > 0){
                    desc.setCheck_img1((isIntranet ? fileConfigUtils.getLocalUrl() :  fileConfigUtils.getRemoteUrl())  + imgs[0]);
                }
                if(imgs.length > 1){
                    desc.setCheck_img2((isIntranet ? fileConfigUtils.getLocalUrl() :  fileConfigUtils.getRemoteUrl())  + imgs[1]);
                }
                if(imgs.length > 2){
                    desc.setCheck_img3((isIntranet ? fileConfigUtils.getLocalUrl() :  fileConfigUtils.getRemoteUrl())  + imgs[2]);
                }
                if(imgs.length > 3){
                    desc.setCheck_img4((isIntranet ? fileConfigUtils.getLocalUrl() :  fileConfigUtils.getRemoteUrl())  + imgs[3]);
                }
                if(imgs.length > 4){
                    desc.setCheck_img5((isIntranet ? fileConfigUtils.getLocalUrl() :  fileConfigUtils.getRemoteUrl())  + imgs[4]);
                }
                descs.add(desc);
            }
            word3.setFinish_count(finishCount + "");
            word3.setUn_count(unCount + "");

            WordUtils.getWord3(word3, list, descs, response);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }
}
