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.OcrRuleTestConvert;
import com.docus.server.dto.segmentation.ocrruletest.AddOcrRuleTestDTO;
import com.docus.server.dto.segmentation.ocrruletest.DeleteOcrRuleTestDTO;
import com.docus.server.dto.segmentation.ocrruletest.EditOcrRuleTestDTO;
import com.docus.server.entity.segmentation.OcrRuleJson;
import com.docus.server.entity.segmentation.OcrRuleResult;
import com.docus.server.entity.segmentation.OcrRuleSecondJson;
import com.docus.server.entity.segmentation.OcrRuleTest;
import com.docus.server.infrastructure.dao.IOcrRuleTestDao;
import com.docus.server.service.IOcrRuleTestService;
import com.docus.server.vo.segmentation.ocrruletest.OcrRuleTestVO;
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 OcrRuleTestServiceImpl implements IOcrRuleTestService {
    @Resource
    private IOcrRuleTestDao iOcrRuleTestDao;
    @Resource
    private IdService idService;

    @Override
    public OcrRuleResult handleRule(List<String> ocrTextList) {
        //查询所有规则列表
        List<OcrRuleTest> ocrRuleTestList = iOcrRuleTestDao.findAll();
        //判断是否符合某个条件的开始条件
        for (OcrRuleTest ocrRuleTest : ocrRuleTestList) {
            String assortName = ocrRuleTest.getAssortName();
            String assortId = ocrRuleTest.getAssortId();
            double score = ocrRuleTest.getMatchRatio();
            if (Func.isEmpty(ocrRuleTest.getKeyWord())){
                continue;
            }
            String[] keyWordList = ocrRuleTest.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 (ocrRuleTest.getIsUseSecond() && Func.isNotEmpty(ocrRuleTest.getJson())) {
                                List<OcrRuleJson> ocrRuleList = Func.parseJsonArray(ocrRuleTest.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[j];
                                            if (ocrText.contains(keyWord)) {
                                                rate = keyWord.length() / (double) ocrText.length() * 100;
                                                //判断是否命中
                                                if (rate >= score) {
                                                    OcrRuleResult ocrRuleResult = new OcrRuleResult();
                                                    ocrRuleResult.setRuleId(ocrRuleTest.getId());
                                                    ocrRuleResult.setAssortId(assortId);
                                                    ocrRuleResult.setAssortName(assortName);
                                                    ocrRuleResult.setHitKey(keyWord);
                                                    ocrRuleResult.setRate(rate);
                                                    return ocrRuleResult;
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                OcrRuleResult ocrRuleResult = new OcrRuleResult();
                                ocrRuleResult.setRuleId(ocrRuleTest.getId());
                                ocrRuleResult.setAssortName(assortName);
                                ocrRuleResult.setAssortId(assortId);
                                ocrRuleResult.setHitKey(keyWord);
                                ocrRuleResult.setRate(rate);
                                return ocrRuleResult;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

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

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

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

        //PageResult<OcrRuleTestVO> result = OcrRuleTestConvert.INSTANCE.convertVO(iOcrRuleTestDao.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 void deleteAndAdd(List<EditOcrRuleTestDTO> editOcrRuleTestDTOList) {
        List<OcrRuleTest> ruleTestList = editOcrRuleTestDTOList.stream().map(m -> {
            OcrRuleTest ocrRuleTest = OcrRuleTestConvert.INSTANCE.convertDO(m);
            ocrRuleTest.setId(ocrRuleTest.getId() == null ? idService.getDateSeq() : ocrRuleTest.getId());
            return ocrRuleTest;
        }).collect(Collectors.toList());
        String assortId = ruleTestList.get(0).getAssortId();

        iOcrRuleTestDao.deleteBy("assortId", assortId);
        iOcrRuleTestDao.saveBatch(ruleTestList, 1000);
    }

    /**
     * 新增
     *
     * @param addOcrRuleTestDTO 编辑参数
     * @return 成功或失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(AddOcrRuleTestDTO addOcrRuleTestDTO) {
        OcrRuleTest ocrRuleTest = OcrRuleTestConvert.INSTANCE.convertDO(addOcrRuleTestDTO);
        ocrRuleTest.setId(idService.getDateSeq());
        return iOcrRuleTestDao.add(ocrRuleTest);

        // String name = addOcrRuleTestDTO.getName();

        //OcrRuleTest ocrRuleTest = iOcrRuleTestDao.findOneBy("name", name);

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

        // OcrRuleTest ocrRuleTest =OcrRuleTestConvert.INSTANCE.convertDO(addOcrRuleTestDTO);
        // ocrRuleTest.setId(idService.getDateSeq());

        // return iOcrRuleTestDao.add(schCollector);

    }

    /**
     * 编辑
     *
     * @param editOcrRuleTestDTO 编辑参数
     * @return 成功或失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(EditOcrRuleTestDTO editOcrRuleTestDTO) {
        OcrRuleTest ocrRuleTest = OcrRuleTestConvert.INSTANCE.convertDO(editOcrRuleTestDTO);
        return iOcrRuleTestDao.edit(ocrRuleTest);

        // Long id = editOcrRuleTestDTO.getId();

        //  OcrRuleTest ocrRuleTest = iOcrRuleTestDao.findById(id);

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

        // ocrRuleTest.setUpdateTime(LocalDateTime.now());
        // return iOcrRuleTestDao.edit(ocrRuleTest);
    }

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

