package com.zcloud.service.depository.impl;

import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.mapper.dsno1.depository.LibraryLabelsMapper;
import com.zcloud.mapper.dsno1.depository.LibraryLogMapper;
import com.zcloud.mapper.dsno1.depository.TextInfoMapper;
import com.zcloud.mapper.dsno1.depository.TextLibraryMapper;
import com.zcloud.service.depository.TextLibraryService;
import com.zcloud.util.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 说明：文本信息
 * 作者：luoxiaobao
 * 时间：2022-12-27
 * 官网：www.zcloudchina.com
 */
@Service
@Transactional //开启事物
public class TextLibraryServiceImpl implements TextLibraryService {

    @Resource
    private TextLibraryMapper textlibraryMapper;

    @Resource
    private LibraryLabelsMapper libraryLabelsMapper;

    @Resource
    private LibraryLogMapper libraryLogMapper;

    @Resource
    private TextInfoMapper textInfoMapper;

    @Resource
    private Smb smb;

    /**
     * 新增
     *
     * @param pd
     * @throws Exception
     */
    public void save(PageData pd) throws Exception {
        textlibraryMapper.save(pd);
    }

    /**
     * 删除
     *
     * @param pd
     * @throws Exception
     */
    public void delete(PageData pd) throws Exception {
        PageData entity = textlibraryMapper.findById(pd);
        if (StringUtils.isNotBlank(entity.getString("LOCKTOOL"))) {
            throw new RuntimeException("数据已被锁定，请先解锁数据");
        }
        textlibraryMapper.delete(pd);
    }

    /**
     * 修改
     *
     * @param pd
     * @throws Exception
     */
    public void edit(PageData pd) throws Exception {
        textlibraryMapper.edit(pd);
    }

    /**
     * 列表
     *
     * @param page
     * @throws Exception
     */
    public List<PageData> list(Page page) throws Exception {
        List<PageData> list = textlibraryMapper.datalistPage(page);
        for (PageData entity : list) {
            List<PageData> _labels = libraryLabelsMapper.findBylibraryId(entity);
            // 安全操作规程
            // 标签
            entity.put("labels", _labels.stream().filter(n -> Tools.notEmpty(n.getString("BUS_LABEL_FACTORY_ID"))).collect(Collectors.toList()));
            // 类型
            entity.put("TYPES", _labels.stream().filter(n -> Tools.notEmpty(n.getString("CATEGORY"))).filter(n -> "TYPES".equals(n.getString("CATEGORY"))).map(Warden::addDic).collect(Collectors.toList()));
            // 国民经济行业类型
            entity.put("SPECIFICATION_TYPES", _labels.stream().filter(n -> Tools.notEmpty(n.getString("CATEGORY"))).filter(n -> n.getString("CATEGORY").equals("SPECIFICATION_TYPES")).map(Warden::addDic).collect(Collectors.toList()));
            // 规程属性
            entity.put("CATEGORY_LIST", _labels.stream().filter(n -> Tools.notEmpty(n.getString("CATEGORY"))).filter(n -> n.getString("CATEGORY").equals("CATEGORY_LIST")).map(Warden::addDic).collect(Collectors.toList()));
        }
        return list;
    }

    /**
     * 列表(全部)
     *
     * @param pd
     * @throws Exception
     */
    public List<PageData> listAll(PageData pd) throws Exception {
        return textlibraryMapper.listAll(pd);
    }

    /**
     * 通过id获取数据
     *
     * @param condition 查询条件
     * @throws Exception all
     */
    public PageData findById(PageData condition) throws Exception {
        PageData info = textlibraryMapper.findById(condition);
        if (info != null && !info.isEmpty()) {
            List<PageData> _labels = libraryLabelsMapper.findBylibraryId(info);
            if ("0".equals(info.getString("ASSOCIATION")) || "1".equals(info.getString("ASSOCIATION")) || "2".equals(info.getString("ASSOCIATION"))) {
                // 标签
                info.put("labels", _labels.stream().filter(n -> Tools.notEmpty(n.getString("BUS_LABEL_FACTORY_ID"))).collect(Collectors.toList()));
                // 类型
                info.put("TYPES", _labels.stream().filter(n -> Tools.notEmpty(n.getString("CATEGORY"))).filter(n -> "TYPES".equals(n.getString("CATEGORY"))).map(Warden::addDic).collect(Collectors.toList()));
                // 国民经济行业类型
                info.put("SPECIFICATION_TYPES", _labels.stream().filter(n -> Tools.notEmpty(n.getString("CATEGORY"))).filter(n -> n.getString("CATEGORY").equals("SPECIFICATION_TYPES")).map(Warden::addDic).collect(Collectors.toList()));
                // 规程属性
                info.put("CATEGORY_LIST", _labels.stream().filter(n -> Tools.notEmpty(n.getString("CATEGORY"))).filter(n -> n.getString("CATEGORY").equals("CATEGORY_LIST")).map(Warden::addDic).collect(Collectors.toList()));
            }
            // 应急预案管理
            if ("3".equals(info.getString("ASSOCIATION"))) {
                info.put("TYPES", _labels.stream().filter(n -> n.get("CATEGORY") != null).filter(n -> n.getString("CATEGORY").equals("TYPES")).map(Warden::addDic).collect(Collectors.toList()));
                info.put("labels", _labels.stream().filter(n -> n.get("BUS_LABEL_FACTORY_ID") != null).collect(Collectors.toList()));
                info.put("SPECIFICATION_TYPES", _labels.stream().filter(n -> n.get("CATEGORY") != null).filter(n -> n.getString("CATEGORY").equals("SPECIFICATION_TYPES")).map(Warden::addDic).collect(Collectors.toList()));
                info.put("ATTRIBUTE_LIST", _labels.stream().filter(n -> n.get("CATEGORY") != null).filter(n -> n.getString("CATEGORY").equals("ATTRIBUTE_LIST")).map(Warden::addDic).collect(Collectors.toList()));
                info.put("CATEGORY_LIST", _labels.stream().filter(n -> n.get("CATEGORY") != null).filter(n -> n.getString("CATEGORY").equals("CATEGORY_LIST")).map(Warden::addDic).collect(Collectors.toList()));
            }
        }
        return info;
    }

    /**
     * 批量删除
     *
     * @param ArrayDATA_IDS
     * @throws Exception
     */
    public void deleteAll(String[] ArrayDATA_IDS) throws Exception {
        textlibraryMapper.deleteAll(ArrayDATA_IDS);
    }

    @Override
    public void init(PageData condition, MultipartFile[] file) throws Exception {
        if (file != null && file.length > 0) {
            String path = smb.saveFile(file[0]);
            condition.put("PATH", path);
        }
        if (StringUtils.isNotBlank(condition.getString("BUS_TEXT_LIBRARY_ID"))) {
            // 保存历史文件
            PageData entity = textlibraryMapper.findById(condition);
            condition.put("REMOTE_FILE_NAME", Warden.getFileName(condition.getString("PATH")));
            condition.put("CREATED_TIME", entity.get("CREATED_TIME"));
            condition.put("CORPINFO_ID", "0");
            textlibraryMapper.edit(condition);
            libraryLabelsMapper.deleteByLibraryId(condition);
            List<PageData> types = Warden.getList(condition.getString("TYPES"));
            List<PageData> list = new ArrayList<>(types);
            List<PageData> categoryList = Warden.getList(condition.getString("CATEGORY_LIST"));
            list.addAll(categoryList);
            List<PageData> specificationTypes = Warden.getList(condition.getString("SPECIFICATION_TYPES"));
            list.addAll(specificationTypes);
            List<PageData> labels = Warden.getList(condition.getString("labels"));
            list.addAll(labels);
            if ("3".equals(condition.getString("ASSOCIATION"))) {
                List<PageData> attributeList = Warden.getList(condition.getString("ATTRIBUTE_LIST"));
                list.addAll(attributeList);
            }

            for (PageData _label : list) {
                PageData label = new PageData();
                label.put("BUS_TEXT_LIBRARY_ID", condition.getString("BUS_TEXT_LIBRARY_ID"));
                label.put("BUS_LIBRARY_LABELS_ID", Warden.get32UUID());
                label.put("BUS_LABEL_FACTORY_ID", _label.getString("BUS_LABEL_FACTORY_ID"));
                label.put("NAME", _label.getString("NAME"));
                label.put("ISDELETE", "0");
                if (StringUtils.isNotEmpty(_label.getString("CATEGORY_ID")))
                    label.put("CATEGORY_ID", _label.getString("CATEGORY_ID"));
                if (StringUtils.isNotEmpty(_label.getString("CATEGORY")))
                    label.put("CATEGORY", _label.getString("CATEGORY"));
                if (StringUtils.isNotEmpty(_label.getString("CATEGORY_NAME")))
                    label.put("CATEGORY_NAME", _label.getString("CATEGORY_NAME"));
                libraryLabelsMapper.save(label);
            }
            PageData text_info = new PageData();
            text_info.put("BUS_TEXT_LIBRARY_ID", condition.getString("BUS_TEXT_LIBRARY_ID"));
            text_info = textInfoMapper.findByMainId(text_info);
            if (text_info == null || text_info.size() == 0) {
                text_info = new PageData();
                text_info.put("CREATED_TIME", new Date());
                text_info.put("TEXT_INFO_ID", Warden.get32UUID());
                text_info.put("BUS_TEXT_LIBRARY_ID", condition.getString("BUS_TEXT_LIBRARY_ID"));
                text_info.put("ISDELETE", "0");
                text_info.put("OPERATE_TIME", new Date());
                text_info.put("TEXT_INFO", condition.getString("TEXT_INFO"));
                textInfoMapper.save(text_info);
            } else {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(condition.getString("TEXT_INFO"))){
                    text_info.put("OPERATE_TIME", new Date());
                    text_info.put("TEXT_INFO", condition.getString("TEXT_INFO"));
                    text_info.put("ISDELETE", "0");
                    textInfoMapper.edit(text_info);
                }
            }
        } else {
            condition.put("BUS_TEXT_LIBRARY_ID", Warden.get32UUID());
            condition.put("REMOTE_FILE_NAME", Warden.getFileName(condition.getString("PATH")));
            condition.put("UPLOAD_TIME", DateUtil.date2Str(new Date()));
            condition.put("UPLOAD_USER", Jurisdiction.getUSER_ID());
            condition.put("UPLOAD_USER_NAME", Jurisdiction.getUsername());
            condition.put("CREATED_TIME", new Date());
            condition.put("ISDELETE", "0");
            condition.put("CORPINFO_ID", "0");
            textlibraryMapper.save(condition);

            List<PageData> list = new ArrayList<>();

            List<PageData> labels = Warden.getList(condition.getString("labels"));
            List<PageData> types = Warden.getList(condition.getString("TYPES"));
            List<PageData> categoryList = Warden.getList(condition.getString("CATEGORY_LIST"));
            List<PageData> specificationTypes = Warden.getList(condition.getString("SPECIFICATION_TYPES"));

            if ("3".equals(condition.getString("ASSOCIATION"))) {
                List<PageData> attributeList = Warden.getList(condition.getString("ATTRIBUTE_LIST"));
                list.addAll(attributeList);
            }
            list.addAll(labels);
            list.addAll(types);
            list.addAll(specificationTypes);
            list.addAll(categoryList);
            for (PageData _label : list) {
                PageData label = new PageData();
                label.put("BUS_LIBRARY_LABELS_ID", Warden.get32UUID());
                label.put("BUS_TEXT_LIBRARY_ID", condition.getString("BUS_TEXT_LIBRARY_ID"));
                label.put("BUS_LABEL_FACTORY_ID", _label.getString("BUS_LABEL_FACTORY_ID"));
                label.put("NAME", _label.getString("NAME"));
                label.put("ISDELETE", "0");
                label.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                if (StringUtils.isNotEmpty(_label.getString("CATEGORY")))
                    label.put("CATEGORY", _label.getString("CATEGORY"));
                if (StringUtils.isNotEmpty(_label.getString("CATEGORY_ID")))
                    label.put("CATEGORY_ID", _label.getString("CATEGORY_ID"));
                if (StringUtils.isNotEmpty(_label.getString("CATEGORY_NAME")))
                    label.put("CATEGORY_NAME", _label.getString("CATEGORY_NAME"));
                libraryLabelsMapper.save(label);
            }

            PageData text_info = new PageData();
            text_info.put("CREATED_TIME", new Date());
            text_info.put("OPERATE_TIME", new Date());
            text_info.put("TEXT_INFO_ID", Warden.get32UUID());
            text_info.put("BUS_TEXT_LIBRARY_ID", condition.getString("BUS_TEXT_LIBRARY_ID"));
            text_info.put("TEXT_INFO", condition.getString("TEXT_INFO"));
            text_info.put("ISDELETE", "0");
            textInfoMapper.save(text_info);
        }
    }

    @Override
    public void lock(PageData request) throws Exception {
        PageData entity = textlibraryMapper.findById(request);
        Optional.ofNullable(entity).orElseThrow(() -> new RuntimeException("数据不正确"));
        if ("1".equals(request.getString("isLock"))) {
            entity.put("LOCKTOOL", Jurisdiction.getUSER_ID());
            textlibraryMapper.edit(entity);
        } else {
            if (Jurisdiction.getUSER_ID().equals(entity.getString("LOCKTOOL"))) {
                entity.put("LOCKTOOL", null);
                textlibraryMapper.edit(entity);
            } else {
                throw new RuntimeException("此条数据不能解锁，因为您不是锁定数据人");
            }
        }
    }

    @Override
    public void top(PageData request) throws Exception {
        PageData entity = textlibraryMapper.findById(request);
        Optional.ofNullable(entity).orElseThrow(() -> new RuntimeException("数据不正确"));
        if ("1".equals(request.getString("isTop"))) {
            entity.put("ISTOPTIME", new Date().getTime());
            textlibraryMapper.edit(entity);
        } else {
            entity.put("ISTOPTIME", null);
            textlibraryMapper.edit(entity);
        }
    }

    @Override
    public void updateFile(MultipartFile[] file, PageData pageData) throws Exception {
        if (file == null || file.length <= 0) throw new RuntimeException("系统异常，没用要更新的文件");
        String path = smb.saveFile(file[0]);

        PageData condition = new PageData();
        condition.put("BUS_TEXT_LIBRARY_ID", pageData.getString("BUS_TEXT_LIBRARY_ID"));
        PageData entity = textlibraryMapper.findById(condition);

        PageData log = new PageData();
        log.put("LIBRARY_LOG_ID", Warden.get32UUID());
        log.put("PATH", entity.getString("PATH"));
        log.put("BUS_TEXT_LIBRARY_ID", condition.getString("BUS_TEXT_LIBRARY_ID"));
        Warden.initDate(log);
        libraryLogMapper.save(log);
        entity.put("PATH", path);
        textlibraryMapper.edit(entity);
    }

    @Override
    public List<PageData> getUpdateLog(PageData pageData) throws Exception {
        PageData condition = new PageData();
        condition.put("BUS_TEXT_LIBRARY_ID", pageData.getString("BUS_TEXT_LIBRARY_ID"));
        return libraryLogMapper.findByLogId(condition);
    }

    @Override
    public void setStatus(PageData pageData) throws Exception {
        PageData condtion = new PageData();
        condtion.put("BUS_TEXT_LIBRARY_ID", pageData.getString("BUS_TEXT_LIBRARY_ID"));
        PageData entity = textlibraryMapper.findById(condtion);
        entity.put("STATUS", pageData.getString("STATUS"));
        textlibraryMapper.edit(entity);
    }

    @Override
    public void copyToOperate(PageData pageData) throws Exception {
        PageData condition = new PageData();
        condition.put("BUS_TEXT_LIBRARY_ID", pageData.getString("BUS_TEXT_LIBRARY_ID"));
        PageData info = textlibraryMapper.findById(condition);
        List<PageData> label_list = libraryLabelsMapper.findBylibraryId(condition);
        //复制数据
        info.put("CORPINFO_ID", "0");
        info.put("BUS_TEXT_LIBRARY_ID", Warden.get32UUID());
        // 2023-08-17 张志军要求，从其他企业加入库的数据自动置顶
        info.put("ISTOPTIME", new Date().getTime());

        for (PageData entity : label_list) {
            entity.put("BUS_TEXT_LIBRARY_ID", info.getString("BUS_TEXT_LIBRARY_ID"));
            entity.put("BUS_LIBRARY_LABELS_ID", Warden.get32UUID());
        }

        textlibraryMapper.save(info);
        for (PageData entity : label_list) {
            libraryLabelsMapper.save(entity);
        }

        PageData text_info = textInfoMapper.findByMainId(condition);
        if (text_info != null && text_info.size() > 0) {
            text_info.put("TEXT_INFO_ID", Warden.get32UUID());
            text_info.put("BUS_TEXT_LIBRARY_ID", info.getString("BUS_TEXT_LIBRARY_ID"));
            textInfoMapper.save(text_info);
        }
    }

    @Override
    public PageData getTextInfo(PageData pageData) {
        return textInfoMapper.findByMainId(pageData);
    }

    @Override
    public void exportWord(PageData pageData, HttpServletResponse response) throws Exception {
        PageData condition = new PageData();
        condition.put("BUS_TEXT_LIBRARY_ID", pageData.getString("BUS_TEXT_LIBRARY_ID"));
        PageData info = textInfoMapper.findByMainId(condition);
        PageData entity = textlibraryMapper.findById(condition);
        info.put("REMARKS",entity.getString("REMARKS"));
        //2023-08-21 created by liu jun 解决文本样式问题
        WordUtil.exportHtmlToWord(null, response, info.getString("TEXT_INFO"), info.getString("REMARKS"));
    }

}

