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.OcrRuleConvert;
import com.docus.server.dto.segmentation.ocrrule.AddOcrRuleDTO;
import com.docus.server.dto.segmentation.ocrrule.DeleteOcrRuleDTO;
import com.docus.server.dto.segmentation.ocrrule.EditOcrRuleDTO;
import com.docus.server.entity.segmentation.*;
import com.docus.server.infrastructure.dao.IOcrRuleDao;
import com.docus.server.service.IOcrRuleService;
import com.docus.server.vo.segmentation.ocrrule.OcrRuleVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 匹配策略表 服务实现类
 *
 * @author AutoGenerator
 * @since 2023-08-29
 */
@Service
public class OcrRuleServiceImpl implements IOcrRuleService {
    @Resource
    private IOcrRuleDao iOcrRuleDao;
    @Resource
    private IdService idService;

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

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

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

        //PageResult<OcrRuleVO> result = OcrRuleConvert.INSTANCE.convertVO(iOcrRuleDao.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 OcrRuleResult handleRule(List<String> ocrTextList,Integer version) {
        //查询所有规则列表
        List<OcrRule> ocrRules = iOcrRuleDao.findBy("version",version);
        //判断是否符合某个条件的开始条件
        for (OcrRule ocrRule : ocrRules) {
            if (Func.isEmpty(ocrRule.getKeyWord())){
                continue;
            }
            String assortId = ocrRule.getAssortId();
            String assortName = ocrRule.getAssortName();
            double score = ocrRule.getMatchRatio();
            String[] keyWordList = ocrRule.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) {
                            //判断二级是否启用
                            if (ocrRule.getIsUseSecond() && Func.isNotEmpty(ocrRule.getJson())) {
                                List<OcrRuleJson> ocrRuleList = Func.parseJsonArray(ocrRule.getJson(), OcrRuleJson.class)
                                        .stream().sorted(Comparator.comparing(OcrRuleJson::getSort))
                                        .collect(Collectors.toList());
                                for (OcrRuleJson ruleJson : ocrRuleList) {
                                    //匹配二级的关键词列表
                                    assortId = ruleJson.getAssortId();
                                    assortName = ruleJson.getAssortName();
                                    List<OcrRuleSecondJson> ocrRuleSecondJsonList = ruleJson.getKeyWordList();
                                    for (OcrRuleSecondJson ocrRuleSecondJson:ocrRuleSecondJsonList) {
                                        if (Func.isEmpty(ocrRuleSecondJson.getKeyWord())){
                                            continue;
                                        }
                                        keyWordList = ocrRuleSecondJson.getKeyWord().split("#");
                                        score = ocrRuleSecondJson.getMatchRatio();
                                        for (int j = 0; j < keyWordList.length; j++) {
                                            keyWord = keyWordList[i];
                                            if (ocrText.contains(keyWord)) {
                                                rate = keyWord.length() / (double) ocrText.length() * 100;
                                                //判断是否命中
                                                if (rate >= score) {
                                                    OcrRuleResult ocrRuleResult = new OcrRuleResult();
                                                    ocrRuleResult.setRuleId(ocrRule.getId());
                                                    ocrRuleResult.setAssortId(assortId);
                                                    ocrRuleResult.setAssortName(assortName);
                                                    ocrRuleResult.setHitKey(keyWord);
                                                    ocrRuleResult.setRate(rate);
                                                    return ocrRuleResult;
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                OcrRuleResult ocrRuleResult = new OcrRuleResult();
                                ocrRuleResult.setRuleId(ocrRule.getId());
                                ocrRuleResult.setAssortId(assortId);
                                ocrRuleResult.setAssortName(assortName);
                                ocrRuleResult.setHitKey(keyWord);
                                ocrRuleResult.setRate(rate);
                                return ocrRuleResult;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 新增
     *
     * @param addOcrRuleDTO 编辑参数
     * @return 成功或失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(AddOcrRuleDTO addOcrRuleDTO) {
        OcrRule ocrRule = OcrRuleConvert.INSTANCE.convertDO(addOcrRuleDTO);
        ocrRule.setId(idService.getDateSeq());
        return iOcrRuleDao.add(ocrRule);

        // String name = addOcrRuleDTO.getName();

        //OcrRule ocrRule = iOcrRuleDao.findOneBy("name", name);

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

        // OcrRule ocrRule =OcrRuleConvert.INSTANCE.convertDO(addOcrRuleDTO);
        // ocrRule.setId(idService.getDateSeq());

        // return iOcrRuleDao.add(schCollector);

    }

    /**
     * 编辑
     *
     * @param editOcrRuleDTO 编辑参数
     * @return 成功或失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(EditOcrRuleDTO editOcrRuleDTO) {
        OcrRule ocrRule = OcrRuleConvert.INSTANCE.convertDO(editOcrRuleDTO);
        return iOcrRuleDao.edit(ocrRule);

        // Long id = editOcrRuleDTO.getId();

        //  OcrRule ocrRule = iOcrRuleDao.findById(id);

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

        // ocrRule.setUpdateTime(LocalDateTime.now());
        // return iOcrRuleDao.edit(ocrRule);
    }

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

