package com.engine.htsc.meeting.service.impl;

import cn.hutool.core.lang.Assert;
import com.api.doc.detail.service.DocSaveService;
import com.api.doc.search.service.DocShareService;
import com.engine.core.impl.Service;
import com.engine.htsc.meeting.cmd.GetMeetingFormCmd;
import com.engine.htsc.meeting.cmd.SaveMeetingFormCmd;
import com.engine.htsc.meeting.service.MeetingService;
import com.engine.htsc.meeting.util.Common;
import com.engine.htsc.payment.util.CommonAPI;
import com.weaver.general.GCONST;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.docs.docs.DocManager;
import weaver.docs.docs.DocViewer;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.hthy.Hthy_Util;
import weaver.system.SystemComInfo;


import java.util.*;
import java.util.stream.Collectors;

public class MeetingServiceImpl extends Service implements MeetingService {

    private final Log log = LogFactory.getLog(MeetingServiceImpl.class);

    @Override
    public List<Map<String, String>> getParticipants() {
        return CommonAPI.query("select id,ryxm from uf_hyxx uh where uh.sfxs = 0 order by ryxm ");
    }

    @Override
    public Map<String, Object> getFormDemo(Map<String, Object> params) {
        return commandExecutor.execute(new GetMeetingFormCmd(user, params));
    }

    @Override
    public Map<String, Object> saveFormDemo(Map<String, Object> params) {
        return commandExecutor.execute(new SaveMeetingFormCmd(user, params));
    }

    @Override
    public Map<String, Object> archiving(Map<String, Object> params) {
        Map<String, Object> apidatas = new HashMap<>();

        if (null == user) {
            apidatas.put("hasRight", false);
            return apidatas;
        }
        apidatas.put("hasRight", true);

        try {
            String docid = Util.null2String(params.get("docid"));
            String yabq = Util.null2String(params.get("yabq"));
            String billid = Util.null2String(params.get("billid"));
            Assert.notBlank(docid, "归档文件未指定,请重试");
            PropBean pp = new PropBean();
            RecordSet rs = new RecordSet();
            int hydg_seccategory = Util.getIntValue(pp.getPropName("hydg_seccategory"));

            String userids = "";
            rs.executeQuery("SELECT HYCBRY FROM UF_HYWH WHERE ID = ?", billid);
            if (rs.next()) {
                userids = Util.null2String(rs.getString("HYCBRY"));
            }

            if (!assertWord(docid)) {
                String sql = "SELECT t1.IMAGEFILENAME,t2.DOCCREATERID FROM DocImageFile t1\n" +
                        "LEFT JOIN DOCDETAIL t2\n" +
                        "ON t1.DOCID = t2.ID \n" +
                        "WHERE t1.DOCID = ? ORDER BY IMAGEFILEID DESC";
                rs.executeQuery(sql, docid);
                DocManager docManager = new DocManager();
                docManager.setId(Integer.parseInt(docid));
                docManager.setSeccategory(hydg_seccategory);
                docManager.setDocsubject(Util.null2String(rs.getString("IMAGEFILENAME")));
                docManager.setUserid(rs.getInt("DOCCREATERID"));
                docManager.setUsertype("1");
                docManager.setDoccreaterid(rs.getInt("DOCCREATERID"));
                int newdocid = docManager.copyDoc();
//                copyDocToNewDoc
                apidatas.put("model", getYtmcObj(newdocid, newdocid));
                //更新权限
                //先移除所有权限,再添加特殊权限
                DocShareService docShareService = new DocShareService();
                docShareService.deleteAll(String.valueOf(newdocid), true, true);
//                docShareService.addShareForUser(new User(), newdocid, userids, 1, true);
//                docShareService.addShareForUser(new User(), newdocid, "26342,11635,21785,16653,42033", 1, true);
                docShareService.addShareForAll(new User(), newdocid, 1, 0, 100, true);
                DocViewer docViewer = new DocViewer();
                docViewer.setDocShareByDoc(String.valueOf(newdocid));
                return apidatas;
            }

            Hthy_Util hthy_util = new Hthy_Util();
            int newDocid = hthy_util.hyDoc2Pdf(docid, hydg_seccategory, userids);
            apidatas.put("model", getYtmcObj(newDocid, Integer.parseInt(docid)));

        } catch (Exception e) {
            log.error(e);
            apidatas.put("message", e.getMessage());
        }

        return apidatas;
    }

    @Override
    public Map<String, Object> getImageFileInfoByFieldIds(String imagefileid) throws Exception {
        Map<String, Object> datas = new HashMap<>();
        List<String> removeBlank = Arrays.stream(imagefileid.split(","))
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());
        //转成imagefileid
        List<String> convertFileId = convertFileId(removeBlank);
        datas.put("fileIds", String.join(",", imagefileid));
        List<Map<String, Object>> data = new ArrayList<>();
        convertFileId.forEach(item -> {
            data.add(Common.getImageFileInfo(item));
        });
        datas.put("fileList", data);

        return datas;
    }

    private Map<String, Object> getYtmcObj(int newDocId, int docid) {
        RecordSet rs = new RecordSet();
        String sql = "SELECT IMAGEFILENAME FROM DocImageFile WHERE DOCID =?";
        rs.executeQuery(sql, docid);
        Map<String, Object> ytmc = new HashMap<>();
        if (rs.next()) {
            ytmc.put("id", newDocId);
            ytmc.put("name", removeSuffix(Util.null2String(rs.getString("IMAGEFILENAME"))));
        } else {
            ytmc.put("id", "");
            ytmc.put("name", "");
        }
        return ytmc;
    }

    private String removeSuffix(String title) {
        int i = title.lastIndexOf(".");
        try {
            return title.substring(0, i);
        } catch (Exception e) {
            return "unknow";
        }
    }

    public boolean assertWord(String docid) {
        RecordSet rs = new RecordSet();
        String sql = "SELECT IMAGEFILENAME FROM DocImageFile WHERE DOCID =?";
        rs.executeQuery(sql, docid);
        String imageFilename = "";
        if (rs.next()) {
            imageFilename = Util.null2String(rs.getString("IMAGEFILENAME"));
        }
        if (StringUtils.isBlank(imageFilename)) {
            return false;
        }
        int i = imageFilename.lastIndexOf(".");
        String suffix = imageFilename.substring(i);
        return ".doc".equalsIgnoreCase(suffix) || ".docx".equalsIgnoreCase(suffix);
    }

    public List<String> convertFileId(List<String> fileId) {
        String collect = String.join("','", fileId);
        String sql = "SELECT IMAGEFILENAME,DOCID,IMAGEFILEID FROM DocImageFile\n" +
                "WHERE DOCID in ('"+collect+"')";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql);
        List<String> list = new ArrayList<>();
        while (rs.next()) {
            list.add(Util.null2String(rs.getString("IMAGEFILEID")));
        }
        return list.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());

    }

}
