package com.mortals.xhx.module.matter.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.StrSplitter;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.MultipleRowTableRenderPolicy;
import com.deepoove.poi.template.MetaTemplate;
import com.deepoove.poi.util.RegexUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mortals.framework.common.Rest;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.common.code.ComponentEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.formdesign.*;
import com.mortals.xhx.common.key.ParamKey;
import com.mortals.xhx.common.pdu.gen.component.ComponentCons;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.common.utils.ExportDocUtil;
import com.mortals.xhx.common.utils.WordUtil;
import com.mortals.xhx.module.matter.dao.MatterDao;
import com.mortals.xhx.module.matter.model.MatterDatumQuery;
import com.mortals.xhx.module.matter.model.MatterEntity;
import com.mortals.xhx.module.matter.model.MatterQuery;
import com.mortals.xhx.module.matter.service.MatterService;
import com.mortals.xhx.module.pubdatum.model.PubdatumEntity;
import com.mortals.xhx.module.pubdatum.service.PubdatumService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.matter.dao.MatterDatumDao;
import com.mortals.xhx.module.matter.model.MatterDatumEntity;
import com.mortals.xhx.module.matter.service.MatterDatumService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * MatterDatumService
 * 事项申请材料 service实现
 *
 * @author zxfei
 * @date 2022-09-27
 */
@Service("matterDatumService")
public class MatterDatumServiceImpl extends AbstractCRUDServiceImpl<MatterDatumDao, MatterDatumEntity, Long> implements MatterDatumService {

    private static int RECOMMEND_COUNT = 5;

    @Value("${upload.path}")
    private String filePath;
    @Autowired
    private MatterService matterService;
    @Autowired
    private PubdatumService pubdatumService;

    @Override
    protected MatterDatumEntity findBefore(MatterDatumEntity params, PageInfo pageInfo, Context context) throws AppException {
        if (!ObjectUtils.isEmpty(params.getMaterialName())) {
            params.setMaterialName("%".concat(params.getMaterialName()).concat("%"));
        }
        return params;
    }

    @Override
    protected void saveAfter(MatterDatumEntity entity, Context context) throws AppException {
        int count = this.count(new MatterDatumQuery().matterId(entity.getMatterId()), context);
        MatterEntity matterEntity = matterService.get(entity.getMatterId(), context);
        if (!ObjectUtils.isEmpty(matterEntity)) {
            matterEntity.setDatumCount(count);
            matterService.update(matterEntity, context);
        }
        addPubdatum(entity, context);
        super.saveAfter(entity, context);
    }

    private void addPubdatum(MatterDatumEntity entity, Context context) {
        if (!ObjectUtils.isEmpty(entity.getPub()) && entity.getPub() == YesNoEnum.YES.getValue()) {
            //添加到公共库
            PubdatumEntity pubdatumEntity = new PubdatumEntity();
            pubdatumEntity.initAttrValue();
            BeanUtils.copyProperties(entity, pubdatumEntity, new String[]{"id"});
            pubdatumEntity.setCreateTime(new Date());
            pubdatumEntity.setCreateUserId(getContextUserId(context));
            pubdatumService.save(pubdatumEntity, context);
        }
    }


    @Override
    protected void updateAfter(MatterDatumEntity entity, Context context) throws AppException {
        addPubdatum(entity, context);
        super.updateAfter(entity, context);
    }

    @Override
    public int remove(Long id, Context context) throws AppException {
        this.removeBefore(id, context);
        MatterDatumEntity matterDatumEntity = this.get(id, context);
        int iRet = this.dao.delete(id);
        this.removeAfter(id, context, iRet);
        int count = this.count(new MatterDatumQuery().matterId(matterDatumEntity.getMatterId()), context);
        MatterEntity matterEntity = matterService.get(matterDatumEntity.getMatterId(), context);
        if (!ObjectUtils.isEmpty(matterEntity)) {
            matterEntity.setDatumCount(count);
            matterService.update(matterEntity, context);
        }
        return iRet;
    }

    @Override
    protected void saveBefore(MatterDatumEntity entity, Context context) throws AppException {

        if (StringUtils.isEmpty(entity.getSamplePath())) {
            throw new AppException("样表地址不能为空");
        }
        //生成样表预览图片
        String rootPath = this.filePath.endsWith("/") ? this.filePath : this.filePath + "/";
        String samplePath = rootPath + entity.getSamplePath();
        String prePath = "/file/preview/";
        String filePath = rootPath + prePath;
        File pathDir = new File(filePath);
        if (!pathDir.exists()) {
            pathDir.mkdirs();
        }

        String newName = RandomUtil.randomNumbers(12) + ".jpg";
        String filePathAll = filePath + newName;
        WordUtil.convertWordToJPEG(samplePath, filePathAll);
        entity.setPreViewPath(prePath + newName);

        super.saveBefore(entity, context);
    }


    @Override
    public Rest<String> recommend(Long id, Long siteId, Context context) {
        MatterDatumEntity matterDatumEntity = this.get(id, context);
        if (matterDatumEntity == null) {
            throw new AppException("数据已更改,请重试");
        }
        String msg = "推荐成功！";
        List<MatterEntity> matterEntities = matterService.find(new MatterQuery().siteId(siteId), context);
        int recommendCount = 0;
        for (MatterEntity matterEntity : matterEntities) {
            recommendCount += this.count(new MatterDatumQuery().matterId(matterEntity.getId()).isRecommend(YesNoEnum.YES.getValue()), context);
        }
        if (matterDatumEntity.getIsRecommend() == YesNoEnum.NO.getValue()) {
            if (recommendCount >= RECOMMEND_COUNT) {
                throw new AppException("超过推荐个数!");
            }
            matterDatumEntity.setIsRecommend(YesNoEnum.YES.getValue());
        } else {
            matterDatumEntity.setIsRecommend(YesNoEnum.NO.getValue());
            msg = "取消推荐成功！";
        }
        this.update(matterDatumEntity, context);
        return Rest.ok(msg);
    }

}