package org.jeecg.modules.ai.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;

import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.ai.entity.PreExaminationMatters;
import org.jeecg.modules.ai.entity.PreReviewRecords;
import org.jeecg.modules.ai.entity.PreReviewRecordsDetail;
import org.jeecg.modules.ai.entity.PreReviewRecordsDetailTemplate;
import org.jeecg.modules.ai.entity.YsDirectory;
import org.jeecg.modules.ai.entity.YsDirectoryMaterial;
import org.jeecg.modules.ai.mapper.PreExaminationMattersMapper;
import org.jeecg.modules.ai.mapper.PreReviewMaterialMapper;
import org.jeecg.modules.ai.mapper.PreReviewRecordsDetailMapper;
import org.jeecg.modules.ai.mapper.PreReviewRecordsDetailTemplateMapper;
import org.jeecg.modules.ai.mapper.PreReviewRecordsMapper;
import org.jeecg.modules.ai.mapper.YsDirectoryMapper;
import org.jeecg.modules.ai.qo.PreExaminationMattersQuery;
import org.jeecg.modules.ai.qo.PreReviewMaterialQuery;
import org.jeecg.modules.ai.qo.PreReviewRecordsApiQuery;
import org.jeecg.modules.ai.qo.PreReviewRecordsDetailQuery;
import org.jeecg.modules.ai.qo.PreReviewRecordsQuery;
import org.jeecg.modules.ai.service.IPreReviewRecordsService;
import org.jeecg.modules.ai.vo.PreReviewMaterialVo;
import org.jeecg.modules.ai.vo.PreReviewRecordsDetailVo;
import org.jeecg.modules.ai.vo.PreReviewRecordsVo;
import org.jeecg.modules.system.util.SendSmsUtil;
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 com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.hutool.core.io.FileUtil;


/**
 * @Description: 办事预审记录
 * @Author: jeecg-boot
 * @Date:   2023-11-25
 * @Version: V1.0
 */
@Service
public class PreReviewRecordsServiceImpl extends ServiceImpl<PreReviewRecordsMapper, PreReviewRecords> implements IPreReviewRecordsService {

	@Resource
	private PreReviewRecordsMapper preReviewRecordsMapper;
	@Resource
	private PreReviewRecordsDetailMapper preReviewRecordsDetailMapper;
	@Resource
	private YsDirectoryMapper ysDirectoryMapper;
	@Resource
	private PreReviewMaterialMapper preReviewMaterialMapper;
	@Resource
	private PreExaminationMattersMapper preExaminationMattersMapper;
	@Resource
	private PreReviewRecordsDetailTemplateMapper preReviewRecordsDetailTemplateMapper;
	@Value(value = "${jeecg.path.upload}")
    private String uploadpath;
	
	/**
	 * 保存预审记录
	 * @param preReviewRecordsVo
	 * {
	 *	    "eventCode":"1234",//事项编码
	 *	    "materialBag":"TX7788",//材料袋编码
	 *	    "userId":"372922111111111111",//用户身份信息
     *	    "materialDetail":[//材料详情列表
	 *	        {
	 *	            "materialCode":"456",//材料编码
	 **	            "listMaterialResult":[//上传材料信息
	 *	                {
	 *	                    "materiaUrl":"/dfasfasf/dddd.png",//上传地址
	 *	                    "templateId":"asdfasfaf",//对应的模板id
	 *	                    "reviewResult":"通过",//预审结果
	 *	                    "ocrResult":"{\"result\":[{\"major\":{\"probability\":0.9989657998,\"words\":\"德阳玺合印章有限公司送检样章\"},\"minor\":[],\"probability\":0.9393941164,\"location\":{\"top\":30,\"left\":58,\"width\":578,\"height\":577},\"type\":\"circle\"}],\"log_id\":1731126137911910870,\"result_num\":1}"
	 *	                }
	 *	            ]
	 *	        },
	 *	        {
	 *	            "materialCode":"456",
	 *	            "listMaterialResult":[
	 *	
	 *	            ]
	 *	        }
	 *	    ]
	 *	}
	 * @return
	 */
	@Override
	public String saveInfo(String preReviewRecordsVo) {
		JSONObject json = JSONObject.parseObject(preReviewRecordsVo);
		
		LambdaQueryWrapper<YsDirectory> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(YsDirectory::getEventCode, json.getString("eventCode"));
		YsDirectory ysDirectory =  ysDirectoryMapper.selectOne(queryWrapper);
		
		//获取预审事项下面所需所有材料
		PreReviewMaterialQuery query = new PreReviewMaterialQuery();
    	query.setEventCode(json.getString("eventCode"));
    	query.setValidStatus(1);
    	List<PreReviewMaterialVo> listReviewMaterial = preReviewMaterialMapper.getPreReviewMaterialList(query);
		
		//预审记录
		PreReviewRecords preReviewRecords = new PreReviewRecords();
		preReviewRecords.setEventCode(json.getString("eventCode"));
		preReviewRecords.setMaterialBag(json.getString("materialBag"));
		preReviewRecords.setSysOrgCode(ysDirectory.getSysCode());
		preReviewRecords.setUserId(json.getString("userId"));
		preReviewRecords.setIsMaterial(oConvertUtils.isEmpty(json.getString("materialBag"))?0:1);
		preReviewRecordsMapper.insert(preReviewRecords);
		
		
		//
		boolean validEventStatusFlag = true;//是否全部通过审核
		//保存预审记录详情
		JSONArray materialDetailArray = json.getJSONArray("materialDetail");
		for(int i=0;i<materialDetailArray.size();i++) {
			JSONObject materialJson = materialDetailArray.getJSONObject(i);
			PreReviewRecordsDetail preReviewRecordsDetail = JSONObject.parseObject(materialJson.toString(), PreReviewRecordsDetail.class);
			preReviewRecordsDetail.setEventCode(json.getString("eventCode"));
			preReviewRecordsDetail.setSysOrgCode(ysDirectory.getSysOrgCode());
			preReviewRecordsDetail.setReviewRecordsId(preReviewRecords.getId());
			preReviewRecordsDetailMapper.insert(preReviewRecordsDetail);
			//添加预审材料
			boolean validStatusFlag = true;//是否全部通过审核
			JSONArray materialDetailTemArray = materialJson.getJSONArray("listMaterialResult");
			for(int j=0;j<materialDetailTemArray.size();j++) {
				JSONObject result = materialDetailTemArray.getJSONObject(j);
				PreReviewRecordsDetailTemplate temp = new PreReviewRecordsDetailTemplate();
				temp.setEventCode(json.getString("eventCode"));
				temp.setMaterialCode(materialJson.getString("materialCode"));
				temp.setMateriaUrl(result.getString("materiaUrl"));
				temp.setOcrResult(result.getString("ocrResult"));
				temp.setTemplateId(result.getString("templateId"));
				temp.setReviewResult(result.getString("reviewResult"));
				temp.setRecordDetailId(preReviewRecordsDetail.getId());
				if(!"通过".equals(materialJson.getString("reviewResult"))) {
					validStatusFlag = false;
				}
				preReviewRecordsDetailTemplateMapper.insert(temp);
			}
			if(validStatusFlag) {
				PreReviewRecordsDetail preReviewRecordsDetailUp = new PreReviewRecordsDetail();
				preReviewRecordsDetailUp.setId(preReviewRecordsDetail.getId());
				preReviewRecordsDetailUp.setReviewResult("通过");
				preReviewRecordsDetailMapper.updateById(preReviewRecordsDetailUp);
			}else {
				validEventStatusFlag = false;
			}
		}
		//预审材料全部通过审核且提交预审材料数量与要求数量一致
		if(validEventStatusFlag&&listReviewMaterial.size()==materialDetailArray.size()) {
			
			PreReviewRecords preReviewRecordsUp = new PreReviewRecords();
			if(preReviewRecords.getId()!=null) {
				//发送完成短信
				String result = new SendSmsUtil().sendSms("", "", "", "");
			}
			preReviewRecordsUp.setId(preReviewRecords.getId());
			preReviewRecordsUp.setValidStatus(1);
			preReviewRecordsUp.setSendSmsFlag(1);
			preReviewRecordsUp.setSendSmsTime(new Date());
			preReviewRecordsMapper.updateById(preReviewRecordsUp);
		}
		return preReviewRecords.getId();
	}
	
	/**
	 * 根据参数关联查询事项信息
	 * @param page
	 * @param queryWrapper
	 * @return
	 */
	@Override
	public IPage<PreReviewRecordsVo> getPreReviewRecordsList(Page page, PreReviewRecordsQuery query){
		return preReviewRecordsMapper.getPreReviewRecordsList(page, query);
	}
	
	/**
	 * 根据预审记录id修改评价状态
	 * @param reviewRecordId
	 * @return
	 */
	@Override
	public int updateEvaluateStatue(PreReviewRecordsApiQuery query) {
		PreReviewRecords preReviewRecords = new PreReviewRecords();
		preReviewRecords.setId(query.getReviewRecordId());
		preReviewRecords.setStar(query.getStar());
		preReviewRecords.setEvaluateStatus(1);
		return preReviewRecordsMapper.updateById(preReviewRecords);
	}
	
	/**
	 * 通过id下载用户上传文件
	 * @param reviewRecordId
	 * @return
	 */
	@SuppressWarnings("resource")
	@Override
	public String downLoad(PreReviewRecords preReviewRecords){
		PreReviewRecordsDetailQuery query = new PreReviewRecordsDetailQuery();
		query.setReviewRecordsId(preReviewRecords.getId());
		List<PreReviewRecordsDetailVo> list = preReviewRecordsDetailMapper.getPreReviewRecordsDetailList(query);
		//压缩文件
		LambdaQueryWrapper<PreExaminationMatters> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(PreExaminationMatters::getEventCode, preReviewRecords.getEventCode());
		queryWrapper.eq(PreExaminationMatters::getSysOrgCode, preReviewRecords.getSysOrgCode());
		PreExaminationMatters preExaminationMatters =  preExaminationMattersMapper.selectOne(queryWrapper);
		
		
		String ctxPath = uploadpath;
        String fileName = preExaminationMatters.getDisplayName() + "_" + System.currentTimeMillis() + ".zip";
        File file = new File(ctxPath + File.separator + "download" + File.separator );
        if (!file.exists()) {
            file.mkdirs();// 创建文件根目录
        }
        //压缩包地址
        String savePath = file.getPath() + File.separator + fileName;
        
        OutputStream outputStream = null;
		try {
			outputStream = new FileOutputStream(savePath);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
    	list.stream().forEach(preReviewRecordsDetailVo -> {
    		try{
        		//获取上传文件名称
        		String detailFileName = preReviewRecordsDetailVo.getMaterialName();
        		String detailFileUrl = preReviewRecordsDetailVo.getMateriaUrl();
        		detailFileName = detailFileName + detailFileUrl.substring(detailFileUrl.lastIndexOf("."), detailFileUrl.length());
				zipOutputStream.putNextEntry(new ZipEntry(detailFileName));
        		byte[] zipFile = FileUtil.readBytes(ctxPath + detailFileUrl);
        		zipOutputStream.write(zipFile);
        		zipOutputStream.flush();
        		zipOutputStream.closeEntry();
    		}catch (Exception e) {
    			// TODO: handle exception
    		}
    	});
		return savePath;
	}
	
	/**
	 * 按事项分类统计当日发送短信数量
	 * @return
	 */
	@Override
	public List<PreReviewRecords> getSendMsgRecordsCount() {
		return preReviewRecordsMapper.getSendMsgRecordsCount();
	}
}
