package com.jeeplus.business.inscription.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.business.goOut.mapper.GoOutMapper;
import com.jeeplus.business.inscription.domain.Inscription;
import com.jeeplus.business.inscription.mapper.InscriptionMapper;
import com.jeeplus.business.inscription.service.dto.InscriptionDTO;
import com.jeeplus.business.project.domain.JyProject;
import com.jeeplus.business.project.mapper.JyProjectMapper;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.swing.text.Document;
import javax.xml.parsers.DocumentBuilder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class InscriptionService {

    @Resource
    private InscriptionMapper inscriptionMapper;

    @Resource
    private GoOutMapper goOutMapper;

    @Resource
    private JyProjectMapper jyProjectMapper;

    @Autowired
    private IFlowableApi flowTaskService;

    @Value("${config.accessory.aliyun.endpoint}")
    private String endpoint;

    @Value("${config.accessory.aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${config.accessory.aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Value("${config.accessory.aliyun.bucketName}")
    private String bucketName;


    /**
     * 文印申请列表
     * @param inscriptionDTO
     * @param page
     * @return
     */
    public IPage<InscriptionDTO> findPageList(InscriptionDTO inscriptionDTO, Page<InscriptionDTO> page) throws Exception {
        QueryWrapper<InscriptionDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(inscriptionDTO, InscriptionDTO.class);
        queryWrapper.eq("a.del_flag",0);
        //关联项目
        if (StringUtils.isNotBlank(inscriptionDTO.getProjectName())){
            queryWrapper.like("pr.name",inscriptionDTO.getProjectName());
        }
        //申请人
        if (StringUtils.isNotBlank(inscriptionDTO.getCreateById())){
            queryWrapper.eq("a.create_by_id",inscriptionDTO.getCreateById());
        }
        //申请人部门
        if (StringUtils.isNotBlank(inscriptionDTO.getOfficeId())){
            queryWrapper.eq("so.id",inscriptionDTO.getOfficeId());
        }
        //申请时间
        if (inscriptionDTO.getCreateDates() != null && inscriptionDTO.getCreateDates().length > 0) {
            queryWrapper.between("a.create_time", inscriptionDTO.getCreateDates()[0], inscriptionDTO.getCreateDates()[1]);
        }

        IPage<InscriptionDTO> iPage=inscriptionMapper.findPageList(queryWrapper,page);
        return iPage;
    }

    /**
     * 获取附件总页数
     * @param
     * @return
     */
    public Integer getPageTotal( InscriptionDTO inscriptionDTO) throws IOException {
        Integer total=0;
        String path="C:/localpath/";
        File dir = new File(path);
        if (!dir.exists()) {
            boolean result = dir.mkdirs();  // 使用 mkdirs，不仅可以创建最后一层目录，还会创建所有父目录。

            if (result) {
                System.out.println("文件夹创建成功!");
            } else {
                System.out.println("文件夹创建失败!");
            }
        } else {
            System.out.println("文件夹已存在!");
        }

        String aliyunUrl = "http://cdn.gangwaninfo.com";
        String aliDownloadUrl = "http://oss.gangwaninfo.com";

        for (WorkAttachmentInfo info : inscriptionDTO.getFiles()) {
            String deleteFile = null;
            try {
                String file = aliyunUrl + info.getUrl();

                file = file.replace("amp;","");
                String fileName = file.substring(file.lastIndexOf("/") + 1, file.length());
                String cons = "";
                if (file.contains(aliyunUrl)){
                    cons = aliyunUrl;
                }else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
                    cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
                }else {
                    cons = aliDownloadUrl;
                }
                String ossKey = file.split(cons+"/")[1];
                SpringUtil.getBean ( IWorkAttachmentApi.class ).downByStreamSaveLocal(ossKey,fileName,path+fileName);
                //将下载下来的文件转换为file文件
                File srcFile = new File(path+fileName);
                deleteFile = path+fileName;
                //截取文件后缀名
                String substring = srcFile.getName().substring(srcFile.getName().lastIndexOf(".")+1, srcFile.getName().length());
    //            //判断附件类型是doc,pdf,xls格式
    //            //word文件
                if (substring.equals("doc") || substring.equals("docx")){
                    //读取文件信息
                    FileInputStream inputStream = new FileInputStream(srcFile);
                    XWPFDocument xwpfDocument = new XWPFDocument(inputStream);
                    total+=xwpfDocument.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();
                    xwpfDocument.close();
                }
                //excel文件
                if (substring.equals("xls") || substring.equals("xlsx")){
                    Workbook sheets = WorkbookFactory.create(new FileInputStream(srcFile));
                    int numberOfSheets = sheets.getNumberOfSheets();
                    total+=numberOfSheets;
                }
                //pdf文件
                if (substring.equals("pdf")){
                    PDDocument load = PDDocument.load(srcFile);
                    int numberOfPages = load.getNumberOfPages();
                    total+=numberOfPages;
                }
            }catch (Exception e){

            }finally {
                if(StringUtils.isNotBlank(deleteFile)){
                    //根据路径创建文件对象
                    File file = new File(deleteFile);
                    //路径是个文件且不为空时删除文件
                    if(file.isFile()&&file.exists()){
                        file.delete();
                    }
                }
            }

        }
        return total;


    }

    /**
     * 新增或修改
     * @param inscriptionDTO
     * @return
     */
    public String save(InscriptionDTO inscriptionDTO) {
        if (StringUtils.isNotBlank(inscriptionDTO.getId())){
            return update(inscriptionDTO);
        }
        return add(inscriptionDTO);
    }

    private String update(InscriptionDTO inscriptionDTO) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        Inscription inscription = new Inscription();
        BeanUtils.copyProperties(inscriptionDTO,inscription);
        for (JyProject jyProject : inscriptionDTO.getProjectList()) {
            inscription.setProjectId(jyProject.getProjectId());
        }
        inscription.setUpdateById(userDTO.getId());
        inscription.setUpdateTime(new Date());
        inscription.setId(inscriptionDTO.getId());
        inscriptionMapper.updateById(inscription);
        //修改附件
        List<WorkAttachmentInfo> files = inscriptionDTO.getFiles();
        updateFiles(files, userDTO, inscriptionDTO.getId());
        return inscriptionDTO.getId();
    }

    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (WorkAttachmentInfo dto : list) {
            names = names + "," +dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachmentInfo> infoList = goOutMapper.findList(id);
        if (CollectionUtil.isNotEmpty(infoList)) {
            for (WorkAttachmentInfo i : infoList) {
                if (!names.contains(i.getUrl())) {
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(i.getId());
                }
            }
        }
        //保存信息
        for (WorkAttachmentInfo dto : list) {
            //判断是否存在
            Integer isExit = goOutMapper.findIsExit(id, dto.getName());
            if (isExit == 0) {
                WorkAttachmentInfo i = new WorkAttachmentInfo();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
//                i.getCreateBy().setId(userDTO.getId());
                i.setCreateTime(new Date());
//                i.getUpdateBy().setId(userDTO.getId());
                i.setUpdateTime(new Date());
                i.setDelFlag(0);
                i.setUrl(dto.getUrl());
                //文件类型处理
                List<String> strings = Arrays.asList(dto.getName().split("\\."));
                if (CollectionUtil.isNotEmpty(strings)) {
                    i.setType(strings.get(1));
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag("inscription");
                i.setFileSize(dto.getSize());
                i.setSort(j);
                Map<String,String> map = new HashMap<>();
                String workAttachment = JSON.toJSONString((i));
                String userDTOInfo = JSON.toJSONString((userDTO));
                map.put("workAttachment",workAttachment);
                map.put("userDTO",userDTOInfo);
                SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
                j++;
            }
        }
    }

    private String add(InscriptionDTO inscriptionDTO) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        Inscription inscription = new Inscription();
        for (JyProject jyProject : inscriptionDTO.getProjectList()) {
            inscription.setProjectId(jyProject.getProjectId());
        }
        //id
        String id = UUID.randomUUID().toString().replace("-", "");

        inscription.setId(id);
        inscription.setCreateById(userDTO.getId());
        inscription.setCreateTime(new Date());
        inscription.setUpdateById(userDTO.getId());
        inscription.setUpdateTime(new Date());
        inscription.setNormalPage(inscriptionDTO.getNormalPage());//黑白页数量
        inscription.setColorPage(inscriptionDTO.getColorPage()); //彩页数量
        inscription.setBookbindingNum(inscriptionDTO.getBookbindingNum()); //装订数量
        inscription.setOtherNum(inscriptionDTO.getOtherNum()); //其他
        inscription.setContent(inscriptionDTO.getContent()); //文印内容
        inscription.setStatus(inscriptionDTO.getStatus());
        inscriptionMapper.insert(inscription);
        //保存附件
        List<WorkAttachmentInfo> files = inscriptionDTO.getFiles();
        if (CollectionUtil.isNotEmpty(files)) {
            saveFiles(files, userDTO, id);
        }
        return id;

    }

    /**
     * 保存附件信息
     * @param list 待保存的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id) {
        int j = 1;
        for (WorkAttachmentInfo dto : list) {
            WorkAttachmentInfo i = new WorkAttachmentInfo();
            //包含了url、size、name
            i.setId(UUID.randomUUID().toString().replace("-", ""));
//            i.getCreateBy().setId(userDTO.getId());
            i.setCreateTime(new Date());
//            i.getUpdateBy().setId(userDTO.getId());
            i.setUpdateTime(new Date());
            i.setDelFlag(0);
            i.setUrl(dto.getUrl());
            //文件类型处理
            List<String> strings = Arrays.asList(dto.getName().split("\\."));
            if (CollectionUtil.isNotEmpty(strings)) {
                i.setType(strings.get(1));
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("inscription");
            i.setFileSize(dto.getSize());
            i.setSort(j);
            Map<String,String> map = new HashMap<>();
            String workAttachment = JSON.toJSONString((i));
            String userDTOInfo = JSON.toJSONString((userDTO));
            map.put("workAttachment",workAttachment);
            map.put("userDTO",userDTOInfo);
            SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
            j++;
        }
    }

    /**
     * 根据id查找文印信息
     * @param id
     * @return
     */
    public InscriptionDTO findById(String id) {
        InscriptionDTO inscriptionDTO = new InscriptionDTO();
        InscriptionDTO dto=inscriptionMapper.findById(id);
        BeanUtils.copyProperties(dto,inscriptionDTO);
        if (ObjectUtil.isNotEmpty(dto)){
            ArrayList<JyProject> projects = new ArrayList<>();
            //查询项目信息
            if (StringUtils.isNotBlank(dto.getProjectId())){
                JyProject jyProject=jyProjectMapper.getById(dto.getProjectId());
                projects.add(jyProject);
                inscriptionDTO.setProjectList(projects);
                inscriptionDTO.setProjectNo(jyProject.getNo());
            }
            if (ObjectUtils.isNotEmpty(dto.getNormalPage()) && ObjectUtils.isNotEmpty(dto.getColorPage())){
                //用于管理员修改彩页数量时做的计算
                inscriptionDTO.setPageTotal(dto.getNormalPage()+dto.getColorPage());
            }

        }
        // 查询附件信息
        List<WorkAttachmentInfo> files = goOutMapper.findDtos(id);
        if (CollectionUtils.isNotEmpty(files)) {
            for (WorkAttachmentInfo i : files) {
                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
            }
            inscriptionDTO.setFiles(files);
        }



        return inscriptionDTO;
    }

    /**
     * 根据id修改状态
     * @param inscriptionDTO
     */
    public void updateStatusById(InscriptionDTO inscriptionDTO) {
        Inscription inscription = new Inscription();
        inscription.setStatus(inscriptionDTO.getStatus());
        inscription.setId(inscriptionDTO.getId());
        if (StringUtils.isNotBlank(inscriptionDTO.getMinister())){
            inscription.setMinister(inscriptionDTO.getMinister());//部长
        }else if (StringUtils.isNotBlank(inscriptionDTO.getApprover())){
            inscription.setApprover(inscriptionDTO.getApprover());//批准人
        }else if (StringUtils.isNotBlank(inscriptionDTO.getExaminer())){
            inscription.setExaminer(inscriptionDTO.getExaminer());//核准人
        }
        inscriptionMapper.updateById(inscription);
    }

    /**
     * 根据id进行删除
     * @param id
     * @return
     */
    public String deleteById(String id) {
        inscriptionMapper.deleteById(id);
        return "操作成功";
    }

    /**
     * 下载文印申请单
     * @param inscription
     * @return
     */
    public Map getAuditInfoMap(Inscription inscription) throws ParseException {
        Map data = new HashMap();
        InscriptionDTO inscriptionDTO = inscriptionMapper.findCheckerById(inscription.getId());
        //申请部门
        if (StringUtils.isNotBlank(inscriptionDTO.getOfficeName())){
            data.put("officeName",inscriptionDTO.getOfficeName());
        }else {
            data.put("officeName","");
        }
        //申请人
        if (StringUtils.isNotBlank(inscriptionDTO.getCreateName())){
            data.put("createName",inscriptionDTO.getCreateName());
        }else {
            data.put("createName","");
        }
        //申请时间
        if (ObjectUtils.isNotEmpty(inscriptionDTO.getCreateTime())){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(inscriptionDTO.getCreateTime());
            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(format );
            Calendar ca = Calendar.getInstance();
            ca.setTime(date);
            String year = String.valueOf(ca.get(Calendar.YEAR));
            String month = String.valueOf(ca.get(Calendar.MONTH)+1);
            String day = String.valueOf(ca.get(Calendar.DAY_OF_MONTH));
            data.put("year",year);
            data.put("month",month);
            data.put("day",day);
        }else {
            data.put("year","");
            data.put("month","");
            data.put("day","");
        }
        //文印内容
        if (StringUtils.isNotBlank(inscriptionDTO.getContent())){
            data.put("content",inscriptionDTO.getContent());
        }else {
            data.put("content","");
        }
        //黑白页数量
        if (ObjectUtils.isNotEmpty(inscriptionDTO.getNormalPage())){
            data.put("normalPage",inscriptionDTO.getNormalPage());
        }else {
            data.put("normalPage","");
        }
        //彩页数量
        if (ObjectUtils.isNotEmpty(inscriptionDTO.getColorPage())){
            data.put("colorPage",inscriptionDTO.getColorPage());
        }else {
            data.put("colorPage","");
        }
        //装订数量
        if (ObjectUtils.isNotEmpty(inscriptionDTO.getBookbindingNum())){
            data.put("bookbindingNum",inscriptionDTO.getBookbindingNum());
        }else {
            data.put("bookbindingNum","");
        }
        //其他数量
        if (ObjectUtils.isNotEmpty(inscriptionDTO.getOtherNum())){
            data.put("otherNum",inscriptionDTO.getOtherNum());
        }else {
            data.put("otherNum","");
        }
        //部长
        if (StringUtils.isNotBlank(inscriptionDTO.getMinister())){
            data.put("minister",inscriptionDTO.getMinister());
        }else {
            data.put("minister","");
        }
        //核准人
        if (StringUtils.isNotBlank(inscriptionDTO.getExaminer())){
            data.put("examiner",inscriptionDTO.getExaminer());
        }else {
            data.put("examiner","");
        }
        //批准人
        if (StringUtils.isNotBlank(inscriptionDTO.getApprover())){
            data.put("approver",inscriptionDTO.getApprover());
        }else {
            data.put("approver","");
        }
        return data;

    }

    /**
     * 管理员修改
     * @param inscriptionDTO
     */
    public void adminEditForm(InscriptionDTO inscriptionDTO) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        Inscription inscription = new Inscription();
        for (JyProject jyProject : inscriptionDTO.getProjectList()) {
            inscription.setProjectId(jyProject.getProjectId());
        }
        inscription.setUpdateById(userDTO.getId());
        inscription.setUpdateTime(new Date());
        inscription.setNormalPage(inscriptionDTO.getNormalPage());//黑白页数量
        inscription.setColorPage(inscriptionDTO.getColorPage()); //彩页数量
        inscription.setBookbindingNum(inscriptionDTO.getBookbindingNum()); //装订数量
        inscription.setOtherNum(inscriptionDTO.getOtherNum()); //其他
        inscription.setContent(inscriptionDTO.getContent()); //文印内容
        inscription.setId(inscriptionDTO.getId());
        inscriptionMapper.updateInfoById(inscription);
        //修改申请附件
        List<WorkAttachmentInfo> files = inscriptionDTO.getFiles();
        updateFiles(files, userDTO, inscriptionDTO.getId());
    }
}
