package com.mosty.sjzx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.model.dto.qwzx.TbQwBmjlbbCountDto;
import com.mosty.base.model.entity.jcgl.TbJcglBxd;
import com.mosty.base.model.entity.sjzx.TbCaseType;
import com.mosty.sjzx.mapper.TbCaseTypeMapper;
import com.mosty.sjzx.service.TbCaseTypeService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
@AllArgsConstructor
public class TbCaseTypeServiceImpl extends ServiceImpl<TbCaseTypeMapper, TbCaseType> implements TbCaseTypeService {

    private TbCaseTypeMapper tbCaseTypeMapper;

    @Override
    public String queryCaseByCode(String code) {
        List<TbCaseType> list = getCaseList(code);
        if(CollectionUtils.isEmpty(list)) {
            return "";
        }
        String oneCode = code.substring(0, 2) + "000000";
        String twoCode = code.substring(0, 4) + "0000";
        String threeCode = code.substring(0, 6) + "00";
        String oneCase = getCase(list, oneCode);
        String twoCase = getCase(list, twoCode);
        String threeCase = getCase(list, threeCode);
        String caseStr = "";
        if(StringUtils.isNotBlank(oneCase)) {
            caseStr = caseStr + oneCase + "-";
        }
        if(StringUtils.isNotBlank(twoCase)) {
            caseStr = caseStr + twoCase + "-";
        }
        if(StringUtils.isNotBlank(threeCase)) {
            caseStr = caseStr + threeCase + "-";
        }
        if(StringUtils.isNotBlank(caseStr) && !twoCase.equals(threeCase)) {
            caseStr = caseStr.substring(0, caseStr.length() - 1);
        }
        return caseStr;
    }

    @Override
    public TbCaseType queryCase(String code) {
        QueryWrapper<TbCaseType> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbCaseType::getCode, code);
        return tbCaseTypeMapper.selectOne(queryWrapper);
    }

    /**
     * 获取案由
     * @param code
     * @return
     */
    public List<TbCaseType> getCaseList(String code) {
        if(StringUtils.isNotBlank(code)) {
            String firstCode = code.substring(0, 2);
            QueryWrapper<TbCaseType> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().likeRight(TbCaseType::getCode, firstCode);
            return tbCaseTypeMapper.selectList(queryWrapper);
        }
        return null;
    }

    /**
     * 获取案由
     * @param list
     * @param code
     * @return
     */
    public String getCase(List<TbCaseType> list, String code) {
        TbCaseType caseType = list.stream().filter(item -> item.getCode().equals(code)).findFirst().orElse(null);
        if(caseType != null) {
            return caseType.getName();
        }
        return "";
    }


}
