package com.yihu.jw.base.service.word;

import com.yihu.jw.base.dao.word.BaseImportSensitiveDao;
import com.yihu.jw.base.dao.word.BaseSensitiveWordDao;
import com.yihu.jw.base.service.word.excelImport.BaseSensitiveExcelDO;
import com.yihu.jw.utils.SensitivewordFilter;
import com.yihu.jw.entity.base.words.BaseImportSensitiveDO;
import com.yihu.jw.entity.base.words.BaseSensitiveDO;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.iot.IotRequestMapping;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.mysql.query.BaseJpaService;
import jxl.write.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import java.io.*;
import java.util.*;

/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2020/7/6
 */
@Service
public class BaseSensitiveService extends BaseJpaService<BaseSensitiveDO, BaseSensitiveWordDao> {

    @Autowired
    private BaseSensitiveWordDao baseSensitiveWordDao;


    @Autowired
    private BaseImportSensitiveDao baseImportSensitiveDao;


    @Autowired
    FileUploadService fileUploadService;


    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(BaseSensitiveService.class);
    /**
     * 创建敏感词汇
     * @param words
     * @param explanation
     */
    public void createSensitiveWords(String words, String explanation,String status,String operatorCode,String name) {
        BaseSensitiveDO baseSensitiveDO = new BaseSensitiveDO();
        baseSensitiveDO.setSensitiveWord(words);
        baseSensitiveDO.setExplanation(explanation);
        baseSensitiveDO.setStatus(status);
        baseSensitiveDO.setAddTime(DateUtil.getNowDate());
        baseSensitiveDO.setOperatorCode(operatorCode);
        baseSensitiveDO.setOperator(name);
        baseSensitiveWordDao.save(baseSensitiveDO);
    }

    /**
     * 更新敏感词汇
     * @param id
     * @param words
     * @param explanation
     */
    public void updateSensitiveWords(String id, String words, String explanation,String status,String operatorCode,String name) {
        BaseSensitiveDO baseSensitiveDO = baseSensitiveWordDao.findOne(id);
        baseSensitiveDO.setSensitiveWord(words);
        baseSensitiveDO.setExplanation(explanation);
        baseSensitiveDO.setUpdateTime(DateUtil.getNowDate());
        baseSensitiveDO.setOperatorCode(operatorCode);
        baseSensitiveDO.setOperator(name);
        baseSensitiveDO.setStatus(status);
        baseSensitiveWordDao.save(baseSensitiveDO);
    }

    /**
     * 删除敏感词
     * @param ids
     */
    public void delSensitiveWords(String ids) {
        String[] list = ids.split(",");
        for (String id : list) {
            if (StringUtils.isNotEmpty(id)){
                baseSensitiveWordDao.delete(id);
            }
        }
    }

    /**
     * 修改敏感词状态
     * @param ids
     * @param status
     */
    public void updateSensitiveWordsStatus(String ids, String status,String operatorCode,String name) {
        String[] list = ids.split(",");
        for (String id : list) {
            if (StringUtils.isNotEmpty(id)){
                BaseSensitiveDO baseSensitiveDO = baseSensitiveWordDao.findOne(id);
                baseSensitiveDO.setStatus(status);
                baseSensitiveDO.setUpdateTime(DateUtil.getNowDate());
                baseSensitiveDO.setOperatorCode(operatorCode);
                baseSensitiveDO.setOperator(name);
                baseSensitiveWordDao.save(baseSensitiveDO);
            }
        }

    }

    /**
     * 查询所有敏感词
     * @param status
     * @param words
     * @param page
     * @param pageSize
     * @return
     */
    public MixEnvelop findSensitiveWords(String status, String words, Integer page, Integer pageSize) {
        StringBuffer sql = new StringBuffer("select * from base_sensitive s where 1=1 ");
        StringBuffer countSql = new StringBuffer("select count(*) count from base_sensitive s where 1=1 ");
        if (!status.equalsIgnoreCase("null")){
            sql.append(" AND s.status='").append(status).append("'");
            countSql.append(" AND s.status='").append(status).append("'");
        }
        if (StringUtils.isNotEmpty(words)){
            sql.append(" AND (s.sensitive_word like'%").append(words).append("%'").append(" or ").append("s.explanation like'%").append(words).append("%')");
            countSql.append(" AND (s.sensitive_word like'%").append(words).append("%'").append(" or ").append("s.explanation like'%").append(words).append("%')");
        }
        sql.append(" ORDER BY s.update_time desc LIMIT ").append((page-1)*pageSize).append(",").append(pageSize);
        logger.info("sql="+sql.toString());
        List<BaseSensitiveDO> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(BaseSensitiveDO.class));
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(countSql.toString());
        long count = (long)mapList.get(0).get("count");
        return MixEnvelop.getSuccessListWithPage(IotRequestMapping.Common.message_success_find,list,page,pageSize,count);
    }


    /**
     * 导出敏感词日志
     * @param
     * @return
     */
    public String exportSensitiveWordsLog(OutputStream os,String operatorCode,String path) throws Exception {
        String sql="SELECT * FROM base_import_sensitive b WHERE b.create_time=(SELECT MAX(b.create_time) FROM base_import_sensitive b WHERE b.operator_code='"+operatorCode+"') ";
        List<BaseImportSensitiveDO> list =jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(BaseImportSensitiveDO.class));

//        WritableWorkbook wwb = jxl.Workbook.createWorkbook(os);
//
//        try {
//            WritableSheet ws;
//            ws = wwb.createSheet("sheet", 1);
//
//            String[] header = {"序号", "原因"};
//            int k = 0;
//            for (String h : header) {
//                addCell(ws, 0, k, h);//表名，行，列，header
//                k++;
//            }
//            int i = 1;
//
//            for (BaseImportSensitiveDO one : list) {
//                addCell(ws, i, 0,one.getRow() , "");
//                addCell(ws, i, 1,  one.getProblem(), "");
//                i++;
//            }
//            wwb.write();
//            wwb.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//            if (wwb != null){
//                wwb.close();
//            }
//            throw e;
//        }
//        byte[] bytes = wwb.toString().getBytes();
//        InputStream in = new ByteArrayInputStream(bytes) {
//        };
//        UploadVO uploadVO = fileUploadService.uploadStream(in, "sentitiveLog.xls", path);
        //拼接字符串
        StringBuffer text = new StringBuffer();
            text.append("序号").append("   ").append("原因").append("\r\n");
        for(BaseImportSensitiveDO one:list){
            text.append("第");
            text.append(one.getRow());
            text.append("行");
            text.append("   ");
            text.append(one.getProblem());
            text.append("\r\n");//换行字符
        }
        byte[] bytes = text.toString().getBytes();
        InputStream in = new ByteArrayInputStream(bytes);
        UploadVO uploadVO = fileUploadService.uploadStream(in, "sentitiveLog.txt", path);
        return uploadVO.getFullUri();
    }


    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column, String data) throws WriteException {
        Label label = new Label(column, row, data);
        ws.addCell(label);
    }


    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column, String data, String memo) throws WriteException {
        Label label = new Label(column, row, data);
        if (!org.springframework.util.StringUtils.isEmpty(memo)) {
            WritableCellFeatures cellFeatures = new WritableCellFeatures();
            cellFeatures.setComment(memo);
            label.setCellFeatures(cellFeatures);
        }
        ws.addCell(label);
    }

    /**
     * 导入敏感词
     * @param correctLs
     * @return
     */
    public Map<String, Object> importSensitive(List<BaseSensitiveExcelDO> correctLs,String operatorCode,String name,OutputStream os,String fastdfs_file_url){
        Map<String, Object> rs = new HashMap<>();
        int total = correctLs.size();
        rs.put("total",total);
        Date nowDate = DateUtil.getNowDate();
        for (BaseSensitiveExcelDO one : correctLs) {
            BaseSensitiveDO sensitive = baseSensitiveWordDao.findBySensitiveWord(one.getSensitiveWord());
            if (sensitive!=null){
                BaseImportSensitiveDO importSensitiveDO = new BaseImportSensitiveDO();
                importSensitiveDO.setRow(one.getId());
                importSensitiveDO.setProblem("敏感词已存在");
                importSensitiveDO.setCreateTime(nowDate);
                importSensitiveDO.setOperatorCode(operatorCode);
                importSensitiveDO.setOperator(name);
                baseImportSensitiveDao.save(importSensitiveDO);
                total-=1;
                continue;
            }
            if (StringUtils.isEmpty(one.getSensitiveWord())){
                BaseImportSensitiveDO importSensitiveDO = new BaseImportSensitiveDO();
                importSensitiveDO.setRow(one.getId());
                importSensitiveDO.setProblem("敏感词为空");
                importSensitiveDO.setCreateTime(nowDate);
                importSensitiveDO.setOperatorCode(operatorCode);
                importSensitiveDO.setOperator(name);
                baseImportSensitiveDao.save(importSensitiveDO);
                total-=1;
                continue;
            }
            BaseSensitiveDO baseSensitiveDO = new BaseSensitiveDO();
            baseSensitiveDO.setId(UUID.randomUUID().toString().replaceAll("-",""));
            baseSensitiveDO.setStatus("1");
            baseSensitiveDO.setExplanation(one.getExplanation());
            baseSensitiveDO.setSensitiveWord(one.getSensitiveWord());
            baseSensitiveDO.setOperatorCode(operatorCode);
            baseSensitiveDO.setOperator(name);
            baseSensitiveDO.setAddTime(nowDate);
            baseSensitiveWordDao.save(baseSensitiveDO);
        }

        //
        try {
            String url = exportSensitiveWordsLog(os, operatorCode, fastdfs_file_url);
            rs.put("downloadLogUrl",url);
            logger.info("downloadLogUrl="+url);
        } catch (Exception e) {
            e.printStackTrace();
            rs.put("downloadLogUrl","导出日志失败");
            logger.info("Logerror="+e.getMessage());
        }
        rs.put("success",total);
        return rs;
    }


    /**
     * 敏感词过滤
     * @param txt
     * @return
     */
    public String filterSensitiveWords(String txt){
        List<BaseSensitiveDO> list = (List<BaseSensitiveDO>) baseSensitiveWordDao.findAll();
        HashSet<String> set = new HashSet<>();
        for (BaseSensitiveDO one : list) {
            set.add(one.getSensitiveWord());
        }
        SensitivewordFilter filter = new SensitivewordFilter(set);
        Set<String> words = filter.getSensitiveWord(txt, 1);
        String replaceTxt = filter.replaceSensitiveWord(txt, 1, "***");
        return replaceTxt;
    }
}





