package com.unis.crk.quality.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.crk.basic.entity.BasicEnum;
import com.unis.crk.basic.entity.OrgInfo;
import com.unis.crk.basic.service.IBasicEnumService;
import com.unis.crk.basic.service.IOrgInfoService;
import com.unis.crk.enums.EditStatus;
import com.unis.crk.quality.entity.QualityBase;
import com.unis.crk.quality.entity.QualityCheckitem;
import com.unis.crk.quality.entity.QualityCutitem;
import com.unis.crk.quality.entity.vo.QualityBaseVo;
import com.unis.crk.quality.mapper.QualityBaseMapper;
import com.unis.crk.quality.service.IQualityBaseService;
import com.unis.crk.quality.service.IQualityCheckitemService;
import com.unis.crk.quality.service.IQualityCutitemService;
import com.unis.crk.utils.QualityCheckUtil;
import com.unis.crk.utils.ResultUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 质量标准-根表 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-02-09
 */
@Service
public class QualityBaseServiceImpl extends ServiceImpl<QualityBaseMapper, QualityBase> implements IQualityBaseService {

    @Resource
    private QualityBaseMapper qualityBaseMapper;
    @Autowired
    private IQualityCheckitemService qualityCheckitemService;
    @Autowired
    private IQualityCutitemService qualityCutitemService;
    @Autowired
    private IBasicEnumService basicEnumService;
    @Autowired
    private IOrgInfoService orgInfoService;
    /**
     *保存质量标准-根表
     * @param qualityBase 质量标准-根表业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveBase(QualityBase qualityBase)throws Exception{
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        if (StringUtils.isBlank(qualityBase.getCreater())){
            qualityBase.setCreater(qualityBase.getUnitid());
        }
        qualityBase.setCreateTime(new Date()); //当前时间
        if (qualityBase.getIfStarted() == null){
            qualityBase.setIfStarted(0); //默认不启用
        }
        boolean b = super.saveOrUpdate(qualityBase);
        if (!b) {
            jsonObject.set("msg","保存质量标准失败");
            return  jsonObject;
        }
        if (!qualityCheckitemService.saveOrUpdateBatch(setCheckIitems(qualityBase.getCheckitems()))) { //保存等级信息
            throw new  Exception("保存等级信息失败");
        }
        if (!qualityCutitemService.saveOrUpdateBatch(qualityBase.getCutitems())) { //保存扣量信息
            throw new  Exception("保存扣量信息失败");
        }
        jsonObject.set("success",true);
        jsonObject.set("msg","保存成功");
        return jsonObject;
    }
    private List<QualityCheckitem> setCheckIitems(List<QualityCheckitem> checkitems){
        if (checkitems.size() >0){
            for (int i = 0; i < checkitems.size(); i++) {
                QualityCheckitem checkitem = checkitems.get(i);
                if (StringUtils.isBlank(checkitem.getCheckValue())){
                    checkitem.setCheckValue(null); //设置为空
                    checkitems.set(i,checkitem);
                }
            }
        }
        return checkitems;
    }
    /**
     *修改质量标准-根表
     * @param qualityBase 质量标准-根表业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(QualityBase qualityBase)throws Exception{
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("success",false);
            if (StringUtils.isBlank(qualityBase.getCreater())){
                qualityBase.setCreater(qualityBase.getUnitid());
            }
            boolean b = super.updateById(qualityBase);
            if (!b) {
                jsonObject.set("msg","修改质量标准失败");
                return  jsonObject;
            }
            if (qualityBase.getCheckitems().size() > 0) {
                if (!qualityCheckitemService.saveOrUpdateBatch(setCheckIitems(qualityBase.getCheckitems()))) { //保存等级信息
                    throw new Exception("修改等级信息失败");
                }
            }
            if (qualityBase.getCutitems().size() > 0) {
                if (!qualityCutitemService.saveOrUpdateBatch(qualityBase.getCutitems())) { //保存扣量信息
                    throw new Exception("修改扣量信息失败");
                }
            }
        jsonObject.set("success",true);
        jsonObject.set("msg","修改成功");
        return jsonObject;
    }
    /**
     *删除质量标准-根表数据
     * @param id 质量标准-根表主键尖
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject delete(String id)throws Exception{
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        if (!super.removeById(id)) {
            jsonObject.set("msg","删除质量标准失败");
            return  jsonObject;
        }
        jsonObject.set("success",true);
        jsonObject.set("msg","删除成功");
        return jsonObject;
    }

    /**
     * 按照条件查询质量标准-根表信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(QualityBaseVo pageQuery){
        {
        //条形查询器
        QueryWrapper<QualityBase> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(pageQuery.getUnitId())){
            queryWrapper.and( warpper -> warpper.eq("qb.unitId",pageQuery.getUnitId())
                    .or().eq("qb.unitId","10")); //添加顶级单位数据
        }

        if (StringUtils.isNotBlank(pageQuery.getFileName())){
            queryWrapper.like("qb.FileName", ResultUtil.getQueryWrapperformat(pageQuery.getFileName()));
        }

        if (StringUtils.isNotBlank(pageQuery.getIsCpl())){
            queryWrapper.like("qb.is_cpl", pageQuery.getIsCpl());
        }
            //分页相关
        Page<QualityBase> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

        IPage<Map<String,Object>> page = qualityBaseMapper.selectMyMapsPage(p,queryWrapper);
        return page;
        }
    }

    @Override
    public QualityBase getOne(String id, String lspzCode) {
        //如果id为空，则表示是新增，根据不同品种生成回显值，目前有四个品种
        if (StringUtils.isBlank(id)){
            QualityBase base = new QualityBase();
            String uuid = IdUtil.simpleUUID();
            base.setStandardID(uuid);
            base.setFoodType(lspzCode);
            //小麦
            if (StringUtils.equals("111",lspzCode)){
                base.setFoodName("小麦及混合小麦");
            }
            if (StringUtils.equals("112",lspzCode)){
                    base.setFoodName("玉米");
            }
            if (StringUtils.equals("113",lspzCode)){
                    base.setFoodName("稻谷");
            }
            if (StringUtils.equals("141",lspzCode)){
                    base.setFoodName("大豆");
            }
            //设置等级信息，五个等级
            List<QualityCheckitem> checkitems = new ArrayList<>();

            checkitems.addAll(getQualityCheckitems(uuid,lspzCode,"01")); //一级
            checkitems.addAll(getQualityCheckitems(uuid,lspzCode,"02")); //二级
            checkitems.addAll(getQualityCheckitems(uuid,lspzCode,"03")); //三级
            checkitems.addAll(getQualityCheckitems(uuid,lspzCode,"04")); //四级
            checkitems.addAll(getQualityCheckitems(uuid,lspzCode,"05")); //五级
            //设置扣量信息
            List<QualityCutitem> cutitems = getQualityCutItems(uuid,lspzCode);

            base.setCheckitems(checkitems);
            base.setCutitems(cutitems);
            return base;
        }else {
            QualityBase qualityBase = super.getById(id);
            if (qualityBase != null){
                QueryWrapper<QualityCheckitem> checkitemQueryWrapper = new QueryWrapper<>();
                checkitemQueryWrapper.eq("StandardID",id);
                checkitemQueryWrapper.orderByAsc("FoodGrade").orderByAsc("CheckCode");
                List<QualityCheckitem> checkitems = qualityCheckitemService.list(checkitemQueryWrapper);

                QueryWrapper<QualityCutitem> cutitemQueryWrapper = new QueryWrapper<>();
                cutitemQueryWrapper.eq("StandardID",id);
                cutitemQueryWrapper.orderByAsc("CheckCode");
                List<QualityCutitem> cutitems = qualityCutitemService.list(cutitemQueryWrapper);

                qualityBase.setCheckitems(checkitems);
                qualityBase.setCutitems(cutitems);
            }
            return qualityBase;
        }
    }
    @Override
    public QualityBase getCplOne(String id, String lspzCode) {
        //如果id为空，则表示是新增，根据不同品种生成回显值，目前有四个品种
        if (StringUtils.isBlank(id)){
            QualityBase base = new QualityBase();
            String uuid = IdUtil.simpleUUID();
            base.setStandardID(uuid);
            base.setFoodType(lspzCode);
            if (StringUtils.equals("111",lspzCode)){
                base.setFoodName("大米");
            }
            if (StringUtils.equals("112",lspzCode)){
                    base.setFoodName("面粉");
            }
            if (StringUtils.equals("113",lspzCode)){
                    base.setFoodName("食用油");
            }
            if (StringUtils.equals("114",lspzCode)){
                    base.setFoodName("副食");
            }
            //设置等级信息，五个等级
            List<QualityCheckitem> checkitems = new ArrayList<>();

            checkitems.addAll(getCplQualityCheckitems(uuid,lspzCode,"01")); //一级
            checkitems.addAll(getCplQualityCheckitems(uuid,lspzCode,"02")); //二级
            checkitems.addAll(getCplQualityCheckitems(uuid,lspzCode,"03")); //三级
            checkitems.addAll(getCplQualityCheckitems(uuid,lspzCode,"04")); //四级
            checkitems.addAll(getCplQualityCheckitems(uuid,lspzCode,"05")); //五级
            //设置扣量信息
            List<QualityCutitem> cutitems = getCplQualityCutItems(uuid,lspzCode);

            base.setCheckitems(checkitems);
            base.setCutitems(cutitems);
            return base;
        }else {
            QualityBase qualityBase = super.getById(id);
            if (qualityBase != null){
                QueryWrapper<QualityCutitem> cutitemQueryWrapper = new QueryWrapper<>();
                cutitemQueryWrapper.eq("StandardID",id);
                cutitemQueryWrapper.orderByAsc("CheckCode");
                List<QualityCutitem> cutitems = qualityCutitemService.list(cutitemQueryWrapper);


                QueryWrapper<QualityCheckitem> checkitemQueryWrapper = new QueryWrapper<>();
                checkitemQueryWrapper.eq("StandardID",id);
                checkitemQueryWrapper.orderByAsc("FoodGrade").orderByAsc("CheckCode");
                List<QualityCheckitem> checkitems = qualityCheckitemService.list(checkitemQueryWrapper);



                qualityBase.setCheckitems(checkitems);
                qualityBase.setCutitems(cutitems);
            }
            return qualityBase;
        }
    }

    /**
     * 根据lspzCode查询成品粮標準值
     *
     *
     * @param lspzId
     * @param lsdjId
     * @return
     */
    @Override
    public JSONObject getCplBzz(String unitId,String lspzId, String lsdjId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        String lspzCode = basicEnumService.getById(lspzId).getEnumCode();
        String lsdjCode = basicEnumService.getById(lsdjId).getEnumCode();
        QueryWrapper<QualityBase> qualityBaseQueryWrapper = new QueryWrapper<>();
        qualityBaseQueryWrapper.eq("is_cpl","1");
        qualityBaseQueryWrapper.eq("unitId",unitId);
        qualityBaseQueryWrapper.eq("IfStarted","1");
        qualityBaseQueryWrapper.eq("FoodType",lspzCode);
        qualityBaseQueryWrapper.orderByDesc("CreateTime");
        List<QualityBase> qualityBases = super.list(qualityBaseQueryWrapper);
        if (qualityBases.size() <= 0){
            jsonObject.set("msg","未找到相应成品粮质量标准");
            return jsonObject;
        }
        QualityBase qualityBase = qualityBases.get(0);
        List<Map<String,Object>> checkItems = qualityCheckitemService.getCplBzz(qualityBase.getStandardID(),lspzCode,lsdjCode );
        //得到标准值
        if (checkItems.size() <=0){
            jsonObject.set("msg","未找到相应成品粮质量标准值");
            return jsonObject;
        }
        jsonObject.set("success",true);
        jsonObject.set("msg",checkItems);
        return jsonObject;
    }

    @Override
    public JSONObject getYlBzz(String unitId, String lspzId, String lsdjId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        String lspzCode = basicEnumService.getById(lspzId).getEnumCode();
        String lsdjCode = basicEnumService.getById(lsdjId).getEnumCode();
        QueryWrapper<QualityBase> qualityBaseQueryWrapper = new QueryWrapper<>();
        qualityBaseQueryWrapper.eq("is_cpl","0");
        qualityBaseQueryWrapper.eq("unitId",unitId);
        qualityBaseQueryWrapper.eq("IfStarted","1");
        qualityBaseQueryWrapper.eq("FoodType",lspzCode);
        qualityBaseQueryWrapper.orderByDesc("CreateTime");
        List<QualityBase> qualityBases = super.list(qualityBaseQueryWrapper);
        if (qualityBases.size() <= 0){
            jsonObject.set("msg","未找到相应原粮粮质量标准");
            return jsonObject;
        }
        QualityBase qualityBase = qualityBases.get(0);
        List<Map<String,Object>> checkItems = qualityCheckitemService.getYlBzz(qualityBase.getStandardID(),lspzCode,lsdjCode );
        //得到标准值
        if (checkItems.size() <=0){
            jsonObject.set("msg","未找到相应原粮粮质量标准值");
            return jsonObject;
        }
        jsonObject.set("success",true);
        jsonObject.set("msg",checkItems);
        return jsonObject;
    }

    private List<QualityCutitem> getQualityCutItems(String standardId, String lspzCode) {
        List<QualityCutitem> cutItems = new ArrayList<>();
        String[] arr = new String[]{};
        if (StringUtils.equals("111",lspzCode)){ //小麦扣量值
            arr = xiaomai_klz;
        }
        if (StringUtils.equals("112",lspzCode)){ //玉米扣量值
            arr = yumi_klz;
        }
        if (StringUtils.equals("113",lspzCode)){ //稻谷扣量值
            arr = daogu_klz;
        }
        if (StringUtils.equals("141",lspzCode)){ //大豆扣量值
            arr = dadou_klz;
        }
        for (int i = 0; i < arr.length; i++) {
            QualityCutitem cutItem = new QualityCutitem();
            cutItem.setCutItemID(IdUtil.simpleUUID());
            cutItem.setStandardID(standardId);
            cutItem.setCheckCode(arr[i]);
            cutItem.setKLRange(new BigDecimal("0.0")); //扣量幅度
            cutItem.setKLUpperLimit(new BigDecimal("0.0")); //扣量上限值
            cutItem.setKLIgnored(new BigDecimal("0.0")); //不计扣量值
            cutItem.setJSUpperLimit(new BigDecimal("0.0")); //拒收上限值
            cutItem.setJSLowerLimit(new BigDecimal("0.0")); //拒收下限值
            cutItem.setBzz(new BigDecimal("0.0")); //标准值
            cutItem.setKsfbl(new BigDecimal("0.0")); //整晒费比例
            cutItem.setZLIgnored(new BigDecimal("0.0")); //不计增量
            cutItems.add(cutItem);
        }
        return cutItems;
    }

    private List<QualityCheckitem> getQualityCheckitems(String standardId,String lspzCode,String foodGrade) {
        List<QualityCheckitem> checkItems = new ArrayList<>();
        String[] arr = new String[]{};
        if (StringUtils.equals("111",lspzCode)){
            if (StringUtils.equals("01",foodGrade)){ // 小麦一级
                arr = xiaomai_one_level;
            }else{ //小麦其它等级
                arr = xiaomai_other_level;
            }
        }
        if (StringUtils.equals("112",lspzCode)){
            if (StringUtils.equals("01",foodGrade)){ // 玉米一级
                arr = yumi_one_level;
            }else{ //小麦其它等级
                arr = yumi_other_level;
            }
        }
        if (StringUtils.equals("113",lspzCode)){
            if (StringUtils.equals("01",foodGrade)){ // 稻谷一级
                arr = daogu_one_level;
            }else{ //稻谷其它等级
                arr = daogu_other_level;
            }
        }
        if (StringUtils.equals("141",lspzCode)){
            if (StringUtils.equals("01",foodGrade)){ // 大豆一级
                arr = dadou_one_level;
            }else{ //大豆其它等级
                arr = dadou_other_level;
            }
        }
        for (int i = 0; i < arr.length; i++) {
            QualityCheckitem checkItem = new QualityCheckitem();
            checkItem.setCheckItemID(IdUtil.simpleUUID());
            checkItem.setStandardID(standardId);
            checkItem.setFoodGrade(foodGrade);
            checkItem.setCheckCode(arr[i]);
            checkItem.setCheckValue("0");
            checkItems.add(checkItem);
        }
        return checkItems;
    }

    /**
     * 成品扣量标准
     * @param standardId
     * @param lspzCode
     * @return
     */
    private List<QualityCutitem> getCplQualityCutItems(String standardId, String lspzCode) {{
        List<QualityCutitem> cutItems = new ArrayList<>();
        String[] arr = new String[]{};
        if (StringUtils.equals("111",lspzCode)){ //大米扣量值
            arr = dami_klz;
        }
        if (StringUtils.equals("112",lspzCode)){ //面粉扣量值
            arr = mianfen_klz;
        }
        if (StringUtils.equals("113",lspzCode)){ //食用油扣量值
            arr = you_klz;
        }
        if (StringUtils.equals("114",lspzCode)){ //副食扣量值
            arr = fushi_klz;
        }
        for (int i = 0; i < arr.length; i++) {
            QualityCutitem cutItem = new QualityCutitem();
            cutItem.setCutItemID(IdUtil.simpleUUID());
            cutItem.setCheckCode(arr[i]);
            cutItem.setStandardID(standardId);
            cutItem.setKLUpperLimit(new BigDecimal("0.0")); //扣量上限值
            cutItem.setKLRange(new BigDecimal("0.0")); //扣量幅度
            cutItem.setKLIgnored(new BigDecimal("0.0")); //不计扣量值
            cutItem.setJSUpperLimit(new BigDecimal("0.0")); //拒收上限值
            cutItem.setJSLowerLimit(new BigDecimal("0.0")); //拒收下限值
            cutItem.setBzz(new BigDecimal("0.0")); //标准值
            cutItem.setKsfbl(new BigDecimal("0.0")); //整晒费比例
            cutItem.setZLIgnored(new BigDecimal("0.0")); //不计增量
            cutItems.add(cutItem);
        }
        return cutItems;
    }
    }

    /**
     * 成品粮等级信息
     * @param standardId
     * @param lspzCode
     * @param foodGrade
     * @return
     */
    private List<QualityCheckitem> getCplQualityCheckitems(String standardId,String lspzCode,String foodGrade) {
        List<QualityCheckitem> checkItems = new ArrayList<>();
        String[] arr = new String[]{};
        if (StringUtils.equals("111",lspzCode)){
            if (StringUtils.equals("01",foodGrade)){ // 大米一级
                arr = dami_level;
            }else{ //小麦其它等级
                arr = dami_level;
            }
        }
        if (StringUtils.equals("112",lspzCode)){
            if (StringUtils.equals("01",foodGrade)){ // 面粉一级
                arr = mianfen_level;
            }else{ //面粉其它等级
                arr = mianfen_level;
            }
        }
        if (StringUtils.equals("113",lspzCode)){
            if (StringUtils.equals("01",foodGrade)){ // 食用油一级
                arr = you_level;
            }else{ //食用油其它等级
                arr = you_level;
            }
        }
        if (StringUtils.equals("114",lspzCode)){
            if (StringUtils.equals("01",foodGrade)){ // 大豆一级
                arr = dadou_one_level;
            }else{ //大豆其它等级
                arr = dadou_other_level;
            }
        }
        for (int i = 0; i < arr.length; i++) {
            QualityCheckitem checkItem = new QualityCheckitem();
            checkItem.setCheckItemID(IdUtil.simpleUUID());
            checkItem.setStandardID(standardId);
            checkItem.setFoodGrade(foodGrade);
            checkItem.setCheckValue("0");
            checkItem.setCheckCode(arr[i]);
            checkItems.add(checkItem);
        }
        return checkItems;
    }
    private String[] xiaomai_one_level = new String[]{"0000","11101","11102","11103","11104","11105","11108"}; //小麦一级
    private String[] xiaomai_other_level = new String[]{"0000","11103","11104"}; //小麦其它等级
    private String[] xiaomai_klz = new String[]{"11101","11102","11104","11105"}; //小麦扣量

    private String[] yumi_one_level = new String[]{"0000","11201","11202","11203","11204","11205","11208"}; //玉米一级
    private String[] yumi_other_level = new String[]{"0000","11203","11204"}; //玉米其它等级
    private String[] yumi_klz = new String[]{"11201","11202","11204","11205"}; //玉米扣量

    private String[] daogu_one_level = new String[]{"0000","11301","11302","11303","11304","11305","11306","11307","11308"}; //稻谷一级
    private String[] daogu_other_level = new String[]{"0000","11303","11304"}; //稻谷其它等级
    private String[] daogu_klz = new String[]{"11301","11302","11304","11305"}; //稻谷扣量

    private String[] dadou_one_level = new String[]{"0000","14101","14102","14103","14104","14107","14108"}; //大豆一级
    private String[] dadou_other_level = new String[]{"0000","14103","14104","14107"}; //大豆其它等级
    private String[] dadou_klz = new String[]{"14101","14102"}; //大豆扣量


    private String[] dami_level = new String[]{"0000","11101","11102","11103","11104","11105","11106","11107","1110201","1110402","11109","11110","11111"}; //大米等级
    private String[] dami_klz = new String[]{"11101","11102","11103","11104","11105","11106","11107","11108","1110201","1110402","11109","11110","11111"}; //大米扣量

    private String[] mianfen_level = new String[]{"0000","11201","11202","11203","11204","11205","11206","11207","11208","11209","11210","11211"}; //面粉等级
    private String[] mianfen_klz = new String[]{"11201","11202","11204","11205"}; //面粉扣量

    private String[] you_level = new String[]{"0000","11301","11302","11303","11304","11305","11306","11307","11308","11309","11310","11311","11312","113013","11314"}; //食用油等级
    private String[] you_klz = new String[]{"11301","11302","11303","11304","11305","11306","11307","11308","11309","11310","11311","11312","113013","11314"}; //食用油扣量

    private String[] fushi_level = new String[]{"0000","14101","14102","14103","14104","14107","14108"}; //副食等级
    private String[] fushi_klz = new String[]{"14101","14102"}; //副食扣量

    /**
     * 根据检验值获取等级 All rights Reserved, Designed By
     *
     * @return BigDecimal
     * @throws
     * @update 修改时间 by 修改人
     * @description TODO(这里用一句话描述这个方法的作用)
     */
    public String getLevelByTestValue(JSONObject params) throws Exception {

        BigDecimal testValue = new BigDecimal("0");

        try {
            testValue = new BigDecimal(params.get("testValue") + "");
        } catch (Exception e) {
            throw new Exception("检验结果输入格式错误");
        }

        String cateId = params.get("cateId") + "";
        String cateName = params.get("cateName") + "";
        String indexName = params.get("indexName") + "";
        String indexId = params.get("indexId") + "";
        String unitId = params.get("unitId") + "";

        // 查询大类的code
 /*       List<Map<String, Object>> categoryInfo = this.getByWhere("enumitem", "enumitem.EnumItemId = '"
                + cateId + "'");

        if (StringUtil.isNullOrEmpty(categoryInfo)) {
            throw new Exception("大类不存在");
        }
        String categoryCode = categoryInfo.get(0).get("EnumItemCode") + "";
*/
        BasicEnum categoryInfo = basicEnumService.getById(cateId);

        if (categoryInfo == null) {
            throw new Exception("大类不存在");
        }
        // 大类编码
        String categoryCode = categoryInfo.getEnumCode();

        BasicEnum enumIndexInfo = basicEnumService.getById(indexId);
        if (enumIndexInfo == null) {
            throw new Exception("没有查到枚举");
        }
        String indexCode = enumIndexInfo.getEnumCode();

        // 通过轮询获取，该机构指定品种的质量标准，该机构没有，就获取其父机构的，直至最顶层.
        QualityBase qualityBaseMap = getAmountMapLunXun(categoryCode, unitId);

        String qualityBaseId = qualityBaseMap.getStandardID();

        // 查询增扣量
      /*  List<Map<String, Object>> qualityAmountInfo = this.getByWhere("quality_checkitem",
                " quality_checkitem.StandardID = '" + qualityBaseId + "' ");*/
        QueryWrapper<QualityCheckitem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("StandardID",qualityBaseId);
        queryWrapper.likeLeft("CheckCode",indexCode);
        queryWrapper.orderByDesc("FoodGrade"); //等级倒序
        List<QualityCheckitem> newList = qualityCheckitemService.list(queryWrapper);

        if (newList.size()<=0) {
            throw new Exception("没有查到增扣量信息");
        }

        boolean isCompareMin = StringUtils.equals(params.get("isCompareMin").toString(), "1"); //是比较大值还是比较小值
        String level = "";
        if (newList.size() >0) {
            for (int i = 0; i <= newList.size()-1; i++) {
                // 获取n级值
//            Map<String, Object> nLevel = getMapByLevel(i, newList);
                QualityCheckitem nLevel = newList.get(i);
                // 获取n级标准
                BigDecimal nValue = new BigDecimal( StringUtils.isBlank(nLevel.getCheckValue()) ? "0" : nLevel.getCheckValue());
                String foodGrade = nLevel.getFoodGrade(); //等级
                // 大于等于标准值 /小于等于标准值
                if (testValue.compareTo(nValue) == 0 || testValue.compareTo(nValue) == (isCompareMin?-1:1)) {
                    level = getWordByNum(Integer.parseInt(foodGrade) + "") + "等";
//        			break;
                }
            }
        }

        if (StringUtils.isBlank(level)) {
            level = EditStatus.LevelUtil.OUT.getLevel();
        }
        // 根据等级名称获取对应枚举项里的枚举项id
        QueryWrapper<BasicEnum> levelEnum = new QueryWrapper<>();
        levelEnum.eq("parentId","1002");
        levelEnum.eq("enumName",level);
        List<BasicEnum> basicEnums = basicEnumService.list(levelEnum);

        if (basicEnums.size() < 1) {
            throw new Exception("没有找到匹配的枚举项");
        }
        return basicEnums.get(0).getEnumId();

/*        // 根据等级名称获取对应枚举项里的枚举项id
        List<Map<String, Object>> enumMap = this.getByWhere("metaenum", " EnumName = '等级' ");

        if (StringUtil.isNullOrEmpty(enumMap)) {
            throw new Exception("没有查到等级枚举");
        }

        String enumIdStr = enumMap.get(0).get("EnumId") + "";

        // 根据枚举id查询枚举项
        // 根据等级名称获取对应枚举项里的枚举项id
        List<Map<String, Object>> enumItemsMap = this
                .getByWhere("enumitem", " EnumId = '" + enumIdStr + "' ");

        if (StringUtil.isNullOrEmpty(enumItemsMap)) {
            throw new Exception("没有查到等级枚举项");
        }

        String enum_item_level_id = "";

        for (Map<String, Object> item : enumItemsMap) {
            if (level.equals(item.get("EnumItemName"))) {
                enum_item_level_id = item.get("EnumItemId") + "";
                break;
            }
        }

        if (enum_item_level_id.length() < 1) {
            throw new Exception("没有找到匹配的枚举项");
        }*/


    }
    /**
     * 获取中文 All rights Reserved, Designed By
     *
     * @return getWordByNum
     * @throws
     * @update 修改时间 by 修改人
     * @description TODO(这里用一句话描述这个方法的作用)
     */
    public String getWordByNum(String input) {

        String units[] = {"", "十", "百", "千", "万", "十", "百", "千", "亿"};

        String nums[] = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"};

        String result[];

        String out = "";
        result = new String[input.length()];

        for (int i = 0; i < result.length; i++) {
            result[i] = String.valueOf(input.charAt(i));
        }
        int back = 0;
        for (int i = 0; i < result.length; i++) {
            if (!result[i].equals("0")) {
                back = result.length - i - 1;
                out += nums[Integer.parseInt(result[i])];
                out += units[back];
            } else {
                if (i == result.length - 1) {

                } else {
                    if (!result[i + 1].equals("0")) {
                        out += nums[0];
                    }
                }
            }
        }
        return out;
    }
    /**
     * 检质定制化获取扣量、扣价
     *
     * @return BigDecimal
     * @throws
     * @update 修改时间 by 修改人
     * @description
     */
    public Map<String, Object> getScaleByFomula(JSONObject params) throws Exception {

        // 返回结果
        Map<String, Object> resultMap = null;

        final BigDecimal ZERO = new BigDecimal("0");

        // 大类id
        String categoryId = (params.get("categoryId") + "").trim();
        // 大类名称
        String categoryName = (params.get("categoryName") + "").trim();
        if (StringUtils.isBlank(categoryName)){
            categoryName =  basicEnumService.getById(categoryId).getEnumName();
        }
        // 指标id
        String indexId = (params.get("indexId") + "").trim();
        // 指标名称
        String indexName = (params.get("indexName") + "").trim();
        // 业务单据号
        String billNo = (params.get("billNo") + "").trim();
        // 等级（可空）
        String level = (params.get("level") + "").trim();
        if (StringUtils.isBlank(level)){
            level ="一等";
        }
        // 机构id.
        String unitId = (params.get("unitId") + "").trim();

        // 质检结果
        BigDecimal checkValue = new BigDecimal("0");

        // 判断所输入的检验结果（检验值）
        // 注：如果质检结果输入的是非数字 直接返回 0
        try {
            checkValue = new BigDecimal(params.get("testValue") + "");
        } catch (Exception e) {
            resultMap = new LinkedHashMap<String, Object>();
            resultMap.put("amount", ZERO);
            resultMap.put("price", ZERO);
            return resultMap;
        }

        // 标准值
        BigDecimal standardValue = new BigDecimal("0");

        // 增扣量信息 （根据指标code查询到的增扣量信息）
        Map<String, Object> amountMap = this.getAmountMap(categoryId, indexId, unitId);

        if (categoryName.indexOf("玉米") >= 0 || categoryName.indexOf("高粱") >= 0) {
            // if("水分".equals(indexName)){
            if (indexName.indexOf("水分") >= 0) {
                resultMap = QualityCheckUtil.getCornMoistureMap(amountMap, checkValue);
            } else if (indexName.indexOf("杂质") >= 0) {
                resultMap = QualityCheckUtil.getCornImpurityMap(amountMap, checkValue);
            } else if (indexName.indexOf("霉变粒") >= 0) {
                resultMap = QualityCheckUtil.getCornMildewMap(amountMap, checkValue);
            } else if (indexName.indexOf("不完善粒") >= 0) {
                // 获取玉米不完善粒
                standardValue = new BigDecimal(this.getByLevel(level, this.getStandardId(categoryId, unitId),
                        indexId));
                resultMap = QualityCheckUtil.getCornUnsoundGrainMap(amountMap, standardValue, checkValue);
            } else {
                resultMap = QualityCheckUtil.getMapInstance();
                resultMap.put("amount", ZERO);
                resultMap.put("price", ZERO);
            }
        } else if (categoryName.indexOf("稻谷") >= 0 || categoryName.indexOf("糙米") >= 0) {
            if (indexName.indexOf("水分") >= 0) {
                resultMap = QualityCheckUtil.getPaddyMoistureMap(amountMap, checkValue);
            } else if (indexName.indexOf("杂质") >= 0) {
                resultMap = QualityCheckUtil.getPaddyImpurityMap(amountMap, checkValue);
            } else if (indexName.indexOf("整精米率") >= 0) {
                // 获取稻谷整精米率标准
                standardValue = new BigDecimal(this.getByLevel(level, this.getStandardId(categoryId, unitId),
                        indexId));
                resultMap = QualityCheckUtil.getPaddyHeadRiceRateMap(amountMap, standardValue, checkValue);
            } else if (indexName.indexOf("互混率") >= 0) {
                resultMap = QualityCheckUtil.getPaddyMutualMixingRatioMap(amountMap, checkValue);
            } else if (indexName.indexOf("黄粒米") >= 0) {
                resultMap = QualityCheckUtil.getPaddyYellowColoredRiceMap(amountMap, checkValue);
            } else {
                resultMap = QualityCheckUtil.getMapInstance();
                resultMap.put("amount", ZERO);
                resultMap.put("price", ZERO);
            }
        } else if (categoryName.indexOf("小麦") >= 0 || categoryName.indexOf("粟") >= 0 || categoryName.indexOf("大麦") >= 0 ||  categoryName.indexOf("大豆") >= 0) {
            if (indexName.indexOf("水分") >= 0) {
                resultMap = QualityCheckUtil.getWheatMoistureMap(amountMap, checkValue);
            } else if (indexName.indexOf("杂质") >= 0) {
                resultMap = QualityCheckUtil.getWheatImpurityMap(amountMap, checkValue);
            } else if (indexName.indexOf("无机杂质") >= 0) {
                resultMap = QualityCheckUtil.getWheatMineralMap(amountMap, checkValue);
            } else if (indexName.indexOf("不完善粒") >= 0) {
                // 获取小麦不完善粒标准
                standardValue = new BigDecimal(this.getByLevel(level, this.getStandardId(categoryId, unitId),
                        indexId));
                resultMap = QualityCheckUtil.getWheatUnsoundGrainMap(amountMap, standardValue, checkValue);
            } else {
                resultMap = QualityCheckUtil.getMapInstance();
                resultMap.put("amount", ZERO);
                resultMap.put("price", ZERO);
            }
        } else if(categoryName.indexOf("不另分类的去壳谷物") >= 0 || categoryName.indexOf("小麦粉") >= 0) {
            if(indexName.indexOf("水分") >= 0) {
                resultMap = QualityCheckUtil.getRiceMoistureMap(amountMap, checkValue);
            } else if (indexName.indexOf("杂质") >= 0) {
                resultMap = QualityCheckUtil.getRiceImpurityMap(amountMap, checkValue);
            } else if (indexName.indexOf("不完善粒") >= 0) {
                // 获取小麦不完善粒标准
                standardValue = new BigDecimal(this.getByLevel(level, this.getStandardId(categoryId, unitId),
                        indexId));
                resultMap = QualityCheckUtil.getRiceUnsoundGrainMap(amountMap, standardValue, checkValue);
            } else if (indexName.indexOf("互混率") >= 0) {
                resultMap = QualityCheckUtil.getRiceMutualMixingRatioMap(amountMap, checkValue);
            } else if (indexName.indexOf("黄粒米") >= 0) {
                resultMap = QualityCheckUtil.getRiceYellowColoredRiceMap(amountMap, checkValue);
            }
        }else {
            resultMap = QualityCheckUtil.getMapInstance();
            resultMap.put("amount", ZERO);
            resultMap.put("price", ZERO);
        }
        return resultMap;

    }

    /**
     * 获取增扣量信息
     *
     * @update 修改时间 by 修改人
     * @param //categoryCode 大类code
     * @param indexId        指标id
     * @param unitId         机构id
     * @return Map<String       ,       Object>
     * @throws Exception
     * @update 修改时间 by 修改人
     * @description TODO(这里用一句话描述这个方法的作用)
     */
    public Map<String, Object> getAmountMap(String categoryId, String indexId, String unitId)
            throws Exception {

        // 查询大类的code
        /*List<Map<String, Object>> categoryInfo = this.getByWhere("enumitem", "enumitem.EnumItemId = '"
                + categoryId + "'");*/
        BasicEnum basicEnum = basicEnumService.getById(categoryId);

        if (basicEnum == null) {
            throw new Exception("大类不存在");
        }

        // 大类编码
        String categoryCode = basicEnum.getEnumCode();

        // 轮询获取质量标准
        QualityBase qualityMap = getAmountMapLunXun(categoryCode, unitId);

        if (qualityMap == null) {
            throw new Exception("没有有效的质量计算公式");
        }

        // 获取质量标准主表id
        String qualityBaseId = qualityMap.getStandardID();

        // 通过枚举id查询枚举信息
        /*List<Map<String, Object>> enumIndexInfo = this.getByWhere("enumitem", "enumitem.EnumItemId = '"
                + indexId + "'");*/
        BasicEnum enumIndexInfo = basicEnumService.getById(indexId);
        String indexCode = enumIndexInfo.getEnumCode();

        // 查询增扣量
        /*List<Map<String, Object>> qualityAmountInfo = this.getByWhere("quality_cutitem",
                " quality_cutitem.StandardID = '" + qualityBaseId + "' and quality_cutitem.CheckCode = '"
                        + indexCode + "' ");*/
        QueryWrapper<QualityCutitem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("StandardID",qualityBaseId);
        queryWrapper.eq("CheckCode",indexCode);
        List<Map<String, Object>> qualityAmountInfo = qualityCutitemService.listMaps(queryWrapper);
        if (qualityAmountInfo.size() <= 0) {
            return null;
        }
        Map<String, Object> map = qualityAmountInfo.get(0);
        Map<String, Object> map_1 = new HashMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            //小写转大写
            map_1.put(entry.getKey().toUpperCase(),entry.getValue());

        }

        return map_1;

    }

    /**
     * 轮询获取质量标准.
     *
     * @param categoryCode
     * @param unitId
     * @return
     * @throws Exception
     */
    public QualityBase getAmountMapLunXun(String categoryCode, String unitId) throws Exception {
        // 根据机构，粮食大类，查询质量标准.
        /*List<Map<String, Object>> qualityInfo  = this.getByWhere("quality_base",
                    " quality_base.IfStarted = 1 and quality_base.FoodType = '" + categoryCode
                            + "' and UNITID = '" + unitId + "'");*/
        QueryWrapper<QualityBase> qualityInfoWrapper = new QueryWrapper<>();
        qualityInfoWrapper.eq("IfStarted",1);
        qualityInfoWrapper.eq("FoodType",categoryCode);
        qualityInfoWrapper.eq("UNITID",unitId);
        List<QualityBase> qualityInfo = super.list(qualityInfoWrapper);
        // 如果不存在质量标准数据 说明 品种大类不在指定的机构中.
        if (qualityInfo.size() <= 0) {
            // 获取当前机构的父机构，查询父机构的此品种大类的质量标准.
            OrgInfo orgInfoList = orgInfoService.getById(unitId);
            if (orgInfoList != null ) {
                String unitIdO = orgInfoList.getParentId();
                if (StringUtils.isNotBlank(unitIdO)) {
                    QualityBase map = getAmountMapLunXun(categoryCode, unitIdO);
                    return map;
                } else {
                    throw new Exception("没有有效的质量计算公式");
                }
            } else {
                throw new Exception("没有有效的质量计算公式");
            }
        } else {
            return qualityInfo.get(0);
        }
    }

    /**
     * 根据等级获取不完整粒或整精米率
     *
     * @param levelName  等级名称
     * @param standardId 标准id
     * @param indexId    指标id
     * @return String
     * @throws Exception
     * @update 修改时间 by 修改人
     * @description TODO(这里用一句话描述这个方法的作用)
     */
    public String getByLevel(String levelName, String standardId, String indexId) throws Exception {

        if (levelName.equals(EditStatus.LevelUtil.OUT.getLevel())) {
            throw new Exception("请注意当前品种等级为："+EditStatus.LevelUtil.OUT.getLevel());
        }

        // 粮食等级
        String levelCode = "";

        if (EditStatus.LevelUtil.FIRST.getLevel().equals(levelName)) {
            levelCode = EditStatus.LevelUtil.FIRST.getOrdinal();
        } else if (EditStatus.LevelUtil.SECOND.getLevel().equals(levelName)) {
            levelCode = EditStatus.LevelUtil.SECOND.getOrdinal();
        } else if (EditStatus.LevelUtil.THIRD.getLevel().equals(levelName)) {
            levelCode = EditStatus.LevelUtil.THIRD.getOrdinal();
        } else if (EditStatus.LevelUtil.FOURTH.getLevel().equals(levelName)) {
            levelCode = EditStatus.LevelUtil.FOURTH.getOrdinal();
        } else if (EditStatus.LevelUtil.FIFTH.getLevel().equals(levelName)) {
            levelCode = EditStatus.LevelUtil.FIFTH.getOrdinal();
        }

        // 通过枚举id查询枚举信息
     /*   List<Map<String, Object>> enumIndexInfo = this.getByWhere("enumitem", "enumitem.EnumItemId = '"
                + indexId + "'");

        String indexCode = enumIndexInfo.get(0).get("EnumItemCode") + "";*/

        BasicEnum enumIndexInfo = basicEnumService.getById(indexId);
        String indexCode = enumIndexInfo.getEnumCode();

        // 通过标准id，指标编码,等级查询
/*        List<Map<String, Object>> levelList = this.getByWhere("quality_checkitem",
                " quality_checkitem.StandardID = '" + standardId + "' and quality_checkitem.FoodGrade = '"
                        + levelCode + "' and quality_checkitem.CheckCode = '" + indexCode + "' ");*/
        QueryWrapper<QualityCheckitem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("StandardID",standardId);
        queryWrapper.eq("FoodGrade",levelCode);
        queryWrapper.eq("CheckCode",indexCode);
        List<QualityCheckitem> levelList = qualityCheckitemService.list(queryWrapper);
        if (levelList.size() <= 0) {
            throw new Exception("没有找到等级信息");
        }
        return levelList.get(0).getCheckValue();
    }

    /**
     * 获取质量标准id
     *
     * @param categoryId
     * @return String
     * @throws Exception
     * @throws
     * @update 修改时间 by 修改人
     * @description TODO(这里用一句话描述这个方法的作用)
     */
    public String getStandardId(String categoryId, String unitId) throws Exception {
        // 查询大类的code
       /* List<Map<String, Object>> categoryInfo = this.getByWhere("enumitem", "enumitem.EnumItemId = '"
                + categoryId + "'");*/
        BasicEnum categoryInfo = basicEnumService.getById(categoryId);
        if (categoryInfo == null) {
            throw new Exception("大类不存在");
        }

        // 大类编码
        String categoryCode = categoryInfo.getEnumCode();

        QualityBase qualityInfo = getAmountMapLunXun(categoryCode, unitId);

        // 获取质量标准主表id
        String qualityBaseId = qualityInfo.getStandardID();

        return qualityBaseId;
    }

}
