package com.project.zcustom.service.service.smart.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.project.zcustom.controller.core.PageParamVo;
import com.project.zcustom.controller.core.StringUtils;
import com.project.zcustom.domain.smart.PlatGreenSmartSafety;

import com.project.zcustom.mapper.smart.PlatGreenSmartSafetyMapper;
import com.project.zcustom.service.service.smart.IPlatGreenSmartSafetyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 食堂安全管理Service业务层处理
 *
 * @author change
 * @date 2024-10-31
 */
@Service
public class PlatGreenSmartSafetyServiceImpl extends ServiceImpl<PlatGreenSmartSafetyMapper, PlatGreenSmartSafety> implements IPlatGreenSmartSafetyService {

    /**
     * 组装查询条件
     */
    private LambdaQueryWrapper<PlatGreenSmartSafety> getLambdaQueryWrapper(PlatGreenSmartSafety platGreenSmartSafety) {
        LambdaQueryWrapper<PlatGreenSmartSafety> lqw = new LambdaQueryWrapper<PlatGreenSmartSafety>();
        if (StringUtils.isNotBlank(platGreenSmartSafety.getAppOrg())) {
            lqw.eq(PlatGreenSmartSafety::getAppOrg, platGreenSmartSafety.getAppOrg());
        }
        if (StringUtils.isNotBlank(platGreenSmartSafety.getCanteenName())) {
            lqw.like(PlatGreenSmartSafety::getCanteenName, platGreenSmartSafety.getCanteenName());
        }

        return lqw;
    }

    /**
     * 分页查询食堂安全管理列表
     *
     * @param platGreenSmartSafety 食堂安全管理
     * @return 食堂安全管理集合
     */
    @Override
    public IPage<PlatGreenSmartSafety> pagingPlatGreenSmartSafetyList(PlatGreenSmartSafety platGreenSmartSafety) {
        IPage<PlatGreenSmartSafety> page = new Page<>(platGreenSmartSafety.getPageNum(), platGreenSmartSafety.getPageSize());
        LambdaQueryWrapper<PlatGreenSmartSafety> lqw = getLambdaQueryWrapper(platGreenSmartSafety);
        // 排序 默认时间倒序
        lqw.orderByDesc(PlatGreenSmartSafety::getCreateTime);
        return baseMapper.selectPage(page, lqw);
    }

    /**
     * 分页查询食堂安全管理列表
     *
     * @param lqw
     * @return 食堂安全管理集合
     */
    @Override
    public IPage<PlatGreenSmartSafety> pagingPlatGreenSmartSafetyList(PageParamVo pageParamVo, LambdaQueryWrapper<PlatGreenSmartSafety> lqw) {
        IPage<PlatGreenSmartSafety> page = new Page<>(pageParamVo.getPageNum(), pageParamVo.getPageSize());
        // 排序 默认时间倒序
        lqw.orderByDesc(PlatGreenSmartSafety::getCreateTime);
        return baseMapper.selectPage(page, lqw);
    }

    /**
     * 查询食堂安全管理列表
     *
     * @param platGreenSmartSafety 食堂安全管理
     * @return 食堂安全管理
     */
    @Override
    public List<PlatGreenSmartSafety> selectPlatGreenSmartSafetyList(PlatGreenSmartSafety platGreenSmartSafety) {
        LambdaQueryWrapper<PlatGreenSmartSafety> lqw = getLambdaQueryWrapper(platGreenSmartSafety);
        // 排序 默认时间倒序
        lqw.orderByDesc(PlatGreenSmartSafety::getCreateTime);
        return baseMapper.selectList(lqw);
    }

    /**
     * 查询食堂安全管理列表
     *
     * @param platGreenSmartSafety 食堂安全管理
     * @return 食堂安全管理
     */
    @Override
    public List<PlatGreenSmartSafety> selectPlatGreenSmartSafetyList(PlatGreenSmartSafety platGreenSmartSafety, Long limitNum) {
        LambdaQueryWrapper<PlatGreenSmartSafety> lqw = getLambdaQueryWrapper(platGreenSmartSafety);
        // 排序 默认时间倒序
        lqw.orderByDesc(PlatGreenSmartSafety::getCreateTime);
        lqw.last("limit " + limitNum);
        return baseMapper.selectList(lqw);
    }

    /**
     * 根据指定字段查询信息
     *
     * @param field      字段名称
     * @param filedValue 字段值
     * @return 食堂安全管理
     */
    @Override
    public PlatGreenSmartSafety getPlatGreenSmartSafetyByField(String field, String filedValue) {
        QueryWrapper<PlatGreenSmartSafety> lqw = new QueryWrapper<PlatGreenSmartSafety>();
        lqw.eq(field, filedValue);
        lqw.last("limit 1");
        return this.getOne(lqw, false);
    }

    /**
     * 根据指定字段查询信息列表
     *
     * @param field      字段名称
     * @param filedValue 字段值
     * @return 食堂安全管理
     */
    @Override
    public List<PlatGreenSmartSafety> selectPlatGreenSmartSafetyListByField(String field, String filedValue, Long limitNum) {
        QueryWrapper<PlatGreenSmartSafety> lqw = new QueryWrapper<PlatGreenSmartSafety>();
        lqw.eq(field, filedValue);
        lqw.last("limit " + limitNum);
        return this.list(lqw);
    }

    /**
     * 根据指定字段查询信息列表
     *
     * @param field      字段名称
     * @param filedValue 字段值
     * @return 食堂安全管理
     */
    @Override
    public List<PlatGreenSmartSafety> selectPlatGreenSmartSafetyListByField(String field, String filedValue) {
        QueryWrapper<PlatGreenSmartSafety> lqw = new QueryWrapper<PlatGreenSmartSafety>();
        lqw.eq(field, filedValue);
        return this.list(lqw);
    }

    /**
     * 判断指定字段值是否存在
     *
     * @param field      字段名称
     * @param filedValue 字段值
     */
    @Override
    public void checkFieldExist(String field, String filedValue, String tips, Long id) {
        QueryWrapper<PlatGreenSmartSafety> lqw = new QueryWrapper<PlatGreenSmartSafety>();
        lqw.eq(field, filedValue);
        lqw.ne("id", id);
        if (this.getOne(lqw, false) != null) {
            throw new RuntimeException(tips + "已存在");
        }
    }

    /**
     * 真删接口
     */
    @Override
    public void reallyDeletePlatGreenSmartSafety(LambdaQueryWrapper<PlatGreenSmartSafety> lqw) {
        baseMapper.reallyDeleteByWrapper(lqw);
    }

    /**
     * 添加食堂安全管理
     */
    @Override
    @Transactional
    public void addPlatGreenSmartSafety(String appOrg, Map<String, Object> mapField){
        List<String> keyList = Arrays.asList("name","sample","positive","negative","Ingredients","LeaveSample");
        // 先删除所有数据
        LambdaQueryWrapper<PlatGreenSmartSafety> lqw = new LambdaQueryWrapper<>();
        lqw.eq(PlatGreenSmartSafety::getAppOrg, appOrg);
        this.reallyDeletePlatGreenSmartSafety(lqw);
        if(mapField.containsKey("safetyList")){
            JSONArray safetyList = JSONArray.parseArray(mapField.get("safetyList").toString());
            List<PlatGreenSmartSafety> addList = new ArrayList<>();
            for (Object o : safetyList) {
                Map<String, Object> temp = JSONObject.parseObject(o.toString(), Map.class);
                PlatGreenSmartSafety platGreenSmartSafety = new PlatGreenSmartSafety();
                platGreenSmartSafety.setAppOrg(appOrg);
                StringUtils.setFieldValue(platGreenSmartSafety,temp,keyList,0, PlatGreenSmartSafety::setCanteenName,String.class);
                StringUtils.setFieldValue(platGreenSmartSafety,temp,keyList,1, PlatGreenSmartSafety::setSampleNum,Long.class);
                StringUtils.setFieldValue(platGreenSmartSafety,temp,keyList,2, PlatGreenSmartSafety::setPositiveNum,Long.class);
                StringUtils.setFieldValue(platGreenSmartSafety,temp,keyList,3, PlatGreenSmartSafety::setNegativeNum,Long.class);
                StringUtils.setFieldValue(platGreenSmartSafety,temp,keyList,4, PlatGreenSmartSafety::setIngredientsRate, BigDecimal.class);
                StringUtils.setFieldValue(platGreenSmartSafety,temp,keyList,5, PlatGreenSmartSafety::setLeaveSampleRate, BigDecimal.class);
                addList.add(platGreenSmartSafety);
            }
            this.saveBatch(addList);
        }
    }
    /**
     * 食堂安全管理
     */
    @Override
    public Map<String, Object> getSafetyData(String appOrg){
        QueryWrapper<PlatGreenSmartSafety> lqw = new QueryWrapper<>();
        if(!Objects.equals(appOrg,"0000")){
            lqw.eq("app_org", appOrg);
        }
        lqw.select("count(id) as canteen_count," +
                "sum(sample_num) as sample_num," +
                "sum(positive_num) as positive_num," +
                "sum(ingredients_rate) as ingredients_rate," +
                "sum(leave_sample_rate) as leave_sample_rate," +
                "sum(negative_num) as negative_num");
        lqw.last("limit 1");
        PlatGreenSmartSafety smartSafety = this.getOne(lqw);
        Map<String, Object> tempMap = new HashMap<>();
        if(StringUtils.isNull(smartSafety)){
            StringUtils.getMapData("食品留样数量", "sample", 0, tempMap);
            StringUtils.getMapData("食材抽检结果阳性", "positive", 0, tempMap);
            StringUtils.getMapData("食材抽检结果阴性", "negative", 0, tempMap);
            StringUtils.getMapData("食材抽检合格率", "ingredients", 0, tempMap);
            StringUtils.getMapData("食品留样合格率", "leaveSample", 0, tempMap);
        }else{
            StringUtils.getMapData("食品留样数量", "sample", smartSafety.getSampleNum(), tempMap);
            StringUtils.getMapData("食材抽检结果阳性", "positive", smartSafety.getPositiveNum(), tempMap);
            StringUtils.getMapData("食材抽检结果阴性", "negative", smartSafety.getNegativeNum(), tempMap);
            BigDecimal ingredientsRate = smartSafety.getIngredientsRate();
            Long totalCount = smartSafety.getCanteenCount();
            if(StringUtils.isNull(ingredientsRate)){
                StringUtils.getMapData("食材抽检合格率", "ingredients", 0,tempMap);
            }else{
                StringUtils.getMapData("食材抽检合格率", "ingredients", ingredientsRate.divide(new BigDecimal(totalCount),2, RoundingMode.HALF_UP), tempMap);
            }
            BigDecimal leaveSampleRate = smartSafety.getLeaveSampleRate();
            if(StringUtils.isNull(leaveSampleRate)){
                StringUtils.getMapData("食品留样合格率", "leaveSample", 0, tempMap);
            }else{
                StringUtils.getMapData("食品留样合格率", "leaveSample", leaveSampleRate.divide(new BigDecimal(totalCount),2, RoundingMode.HALF_UP), tempMap);
            }
        }
        return tempMap;
    }
}
