package com.docus.server.service.impl;

import com.docus.core.util.Func;
import com.docus.infrastructure.redis.service.IdService;
import com.docus.infrastructure.web.request.SearchDTO;
import com.docus.infrastructure.web.response.PageResult;
import com.docus.server.convert.OcrSpecialRuleConvert;
import com.docus.server.dto.segmentation.ocrspecialrule.AddOcrSpecialRuleDTO;
import com.docus.server.dto.segmentation.ocrspecialrule.DeleteOcrSpecialRuleDTO;
import com.docus.server.dto.segmentation.ocrspecialrule.EditOcrSpecialRuleDTO;
import com.docus.server.entity.segmentation.OcrSpecialResult;
import com.docus.server.entity.segmentation.OcrSpecialRule;
import com.docus.server.entity.segmentation.OcrSpecialRuleJson;
import com.docus.server.infrastructure.dao.IOcrSpecialRuleDao;
import com.docus.server.service.IOcrSpecialRuleService;
import com.docus.server.vo.segmentation.ocrspecialrule.OcrSpecialRuleVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 特殊策略表 服务实现类
 *
 * @author AutoGenerator
 * @since 2023-08-29
 */
@Service
public class OcrSpecialRuleServiceImpl implements IOcrSpecialRuleService {
    @Resource
    private IOcrSpecialRuleDao iOcrSpecialRuleDao;
    @Resource
    private IdService idService;

    /**
     * 按主键查询
     *
     * @param id 主键Id
     * @return 实体
     */
    @Override
    public OcrSpecialRuleVO findById(Long id) {
        return OcrSpecialRuleConvert.INSTANCE.convertVO(iOcrSpecialRuleDao.findById(id));
    }

    /**
     * 查询所有
     *
     * @return 实体
     */
    @Override
    public List<OcrSpecialRuleVO> findAll() {
        return OcrSpecialRuleConvert.INSTANCE.convertVO(iOcrSpecialRuleDao.findAll());
    }

    /**
     * 关键字搜索
     *
     * @param searchDTO 搜索参数
     * @return 分页列表
     */
    @Override
    public PageResult<OcrSpecialRuleVO> search(SearchDTO searchDTO) {
        return OcrSpecialRuleConvert.INSTANCE.convertVO(iOcrSpecialRuleDao.search(searchDTO));

        //PageResult<OcrSpecialRuleVO> result = OcrSpecialRuleConvert.INSTANCE.convertVO(iOcrSpecialRuleDao.search(searchDTO));

        //if (CollectionUtils.isEmpty(result.getList())) {
        //return new PageResult<>();
        //}

        //Map<String, SchSystemParams> map = iSchSystemParamsService.find(ListUtils.distinctSelect(result.getList(), SchCollectorVO::getCollectorId));

        //result.getList().forEach(p -> {
        // String collectorId = String.valueOf(p.getCollectorId());
        // if (map.containsKey(collectorId)) {
        //     p.setCollectorName(map.get(collectorId).getParamName());
        // }
        //});

        //return result;
    }

    @Override
    public boolean handleSpecialRuleEnd(OcrSpecialResult lastSpecialResul, List<String> ocrTextList) {
        //获取结束条件列表
        List<OcrSpecialRuleJson> ocrSpecialRuleJsons = Func.parseJsonArray(lastSpecialResul.getEndJson(), OcrSpecialRuleJson.class);
        //判断得分占比
        for (OcrSpecialRuleJson ocrSpecialRuleJson : ocrSpecialRuleJsons) {
            double score = ocrSpecialRuleJson.getScore();
            String[] keyWordList = ocrSpecialRuleJson.getKeyWord().split("#");
            for (String ocrText : ocrTextList) {
                for (int i = 0; i < keyWordList.length; i++) {
                    String keyWord = keyWordList[i];
                    if (ocrText.contains(keyWord)){
                        double rate = keyWord.length() / (double)ocrText.length() * 100;
                        //判断是否命中
                        if (rate>=score) {
                            //返回结束
                            return true;
                        }
                    }
                }
            }
        }
        //默认返回没结束
        return false;
    }

    @Override
    public OcrSpecialResult handleSpecialRule(List<String> ocrTextList,Integer version) {
        // 查询所以的特殊规则列表
        List<OcrSpecialRule> all = iOcrSpecialRuleDao.findBy("version",version);
        //判断是否符合某个条件的开始条件
        for (OcrSpecialRule ocrSpecialRule : all) {

            String assortId = ocrSpecialRule.getAssortId();
            String startJson = ocrSpecialRule.getStartJson();
            String assortName = ocrSpecialRule.getAssortName();

            List<OcrSpecialRuleJson> ocrSpecialRuleJsons = Func.parseJsonArray(startJson, OcrSpecialRuleJson.class);
            for (OcrSpecialRuleJson ocrSpecialRuleJson : ocrSpecialRuleJsons) {
                if (Func.isEmpty(ocrSpecialRuleJson.getKeyWord())){
                    continue;
                }
                double score = ocrSpecialRuleJson.getScore();
                String[] keyWordList = ocrSpecialRuleJson.getKeyWord().split("#");
                for (String ocrText : ocrTextList) {
                    for (int i = 0; i < keyWordList.length; i++) {
                        String keyWord = keyWordList[i];
                        if (ocrText.contains(keyWord)){
                            double rate = keyWord.length() / (double)ocrText.length() * 100;
                            //判断是否命中
                            if (rate>=score) {
                                OcrSpecialResult ocrSpecialResult = new OcrSpecialResult();
                                ocrSpecialResult.setAssortId(assortId);
                                ocrSpecialResult.setAssortName(assortName);
                                ocrSpecialResult.setRate(rate);
                                ocrSpecialResult.setHitKey(keyWord);
                                return ocrSpecialResult;
                            }
                        }
                    }
                }
            }
        }
        //默认返回空对象
        return null;
    }

    /**
     * 新增
     *
     * @param addOcrSpecialRuleDTO 编辑参数
     * @return 成功或失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(AddOcrSpecialRuleDTO addOcrSpecialRuleDTO) {
        OcrSpecialRule ocrSpecialRule = OcrSpecialRuleConvert.INSTANCE.convertDO(addOcrSpecialRuleDTO);
        ocrSpecialRule.setId(idService.getDateSeq());
        return iOcrSpecialRuleDao.add(ocrSpecialRule);

        // String name = addOcrSpecialRuleDTO.getName();

        //OcrSpecialRule ocrSpecialRule = iOcrSpecialRuleDao.findOneBy("name", name);

        //if (Func.notNull(ocrSpecialRule)) {
        // throw new ApiException(ExceptionCode.ParamIllegal.getCode(), "特殊策略表已经存在");
        // }

        // OcrSpecialRule ocrSpecialRule =OcrSpecialRuleConvert.INSTANCE.convertDO(addOcrSpecialRuleDTO);
        // ocrSpecialRule.setId(idService.getDateSeq());

        // return iOcrSpecialRuleDao.add(schCollector);

    }

    /**
     * 编辑
     *
     * @param editOcrSpecialRuleDTO 编辑参数
     * @return 成功或失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(EditOcrSpecialRuleDTO editOcrSpecialRuleDTO) {
        OcrSpecialRule ocrSpecialRule = OcrSpecialRuleConvert.INSTANCE.convertDO(editOcrSpecialRuleDTO);
        return iOcrSpecialRuleDao.edit(ocrSpecialRule);

        // Long id = editOcrSpecialRuleDTO.getId();

        //  OcrSpecialRule ocrSpecialRule = iOcrSpecialRuleDao.findById(id);

        // if (Func.isNull(ocrSpecialRule)) {
        //     throw new ApiException(ExceptionCode.ParamIllegal.getCode(), "特殊策略表，无法更新！");
        // }

        // ocrSpecialRule.setUpdateTime(LocalDateTime.now());
        // return iOcrSpecialRuleDao.edit(ocrSpecialRule);
    }

    /**
     * 批量删除
     *
     * @param deleteOcrSpecialRuleDTO 删除参数
     * @return 成功或失败
     */
    @Override
    public int delete(DeleteOcrSpecialRuleDTO deleteOcrSpecialRuleDTO) {
        return iOcrSpecialRuleDao.delete(deleteOcrSpecialRuleDTO.getIds());
    }
}

