/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.huimv.modular.dailytabulatedata.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.core.annotion.Wrapper;
import com.huimv.core.context.login.LoginContextHolder;
import com.huimv.core.factory.PageFactory;
import com.huimv.core.pojo.page.PageResult;
import com.huimv.core.pojo.response.SuccessResponseData;
import com.huimv.modular.dailytabulatedata.entity.DailyTabulateData;
import com.huimv.modular.dailytabulatedata.entity.DailyVo;
import com.huimv.modular.dailytabulatedata.mapper.DailyTabulateDataMapper;
import com.huimv.modular.dailytabulatedata.service.DailyTabulateDataService;
import com.huimv.modular.eartagregister.entity.EartagRegister;
import com.huimv.modular.eartagregister.mapper.EartagRegisterMapper;
import com.huimv.modular.yesterdaypig.entity.YesterdayPig;
import com.huimv.modular.yesterdaypig.mapper.YesterdayPigMapper;
import com.huimv.sys.modular.org.entity.SysOrg;
import com.huimv.sys.modular.org.mapper.SysOrgMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Struct;
import java.util.*;

/**
 * 耳标每日汇总表service接口实现类
 *
 * @author yinhao
 * @date 2021-08-17 14:34:00
 */
@Service
public class DailyTabulateDataServiceImpl extends ServiceImpl<DailyTabulateDataMapper, DailyTabulateData> implements DailyTabulateDataService {


    //（1：配种舍，2：分娩舍，3：保育舍，4：育成育肥舍，5：空怀舍，6：后备母猪舍，
    // 7：公猪舍，8：病死猪场内收集点，9：病死猪集中收集点，10：病死猪无害化处理中心
    @Autowired
    private EartagRegisterMapper eartagRegisterMapper ;

    @Autowired
    private SysOrgMapper sysOrgMapper ;

    @Autowired
    private YesterdayPigMapper yesterdayPigMapper ;

    @Override
    public Map countAllsow(Long orgId) {
        HashMap<String, Object> endMap = new HashMap<>();
        QueryWrapper<DailyTabulateData> wrapper = new QueryWrapper<>();

        wrapper.ge("statistic_date",DateUtil.offsetDay(DateUtil.beginOfDay(DateUtil.date()),-7));
        wrapper.eq("org_id",orgId);
        List<DailyTabulateData> list = this.list(wrapper);
        if (list.size() < 2){
            endMap.put("sowTotalStockValue",0);
            endMap.put("sowTotalStockType",null);
        }else {
            Integer  dailyTabulateData = list.get(0).getStockTotal();
            Integer yesterdayData = list.get(1).getStockTotal();
            if (dailyTabulateData > yesterdayData){
                endMap.put("sowTotalStockValue",dailyTabulateData -yesterdayData);
                endMap.put("sowTotalStockType",true);
            }
            if (dailyTabulateData.equals(yesterdayData)){
                endMap.put("sowTotalStockValue",0);
                endMap.put("sowTotalStockType",null);
            }
            if (dailyTabulateData < yesterdayData){
                endMap.put("sowTotalStockValue",yesterdayData - dailyTabulateData);
                endMap.put("sowTotalStockType",false);
            }

        }


        endMap.put("data",list);
        return endMap;

    }

    @Override
    public PageResult queryPage(DailyTabulateData dailyTabulateData) {
        QueryWrapper<DailyTabulateData> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(dailyTabulateData)) {

            Long orgId = dailyTabulateData.getOrgId();
            if (ObjectUtil.isNotEmpty(orgId)) {
                QueryWrapper<SysOrg> sysOrgQueryWrapper = new QueryWrapper<>();
                sysOrgQueryWrapper.eq("pid",orgId);
                List<SysOrg> sysOrgs = sysOrgMapper.selectList(sysOrgQueryWrapper);
                List<Long> list = new ArrayList<>();
                for (SysOrg sysOrg : sysOrgs) {
                    list.add(sysOrg.getId());
                }
                list.add(orgId);
                queryWrapper.in("org_id", list);
                queryWrapper.eq("statistic_date", DateUtil.beginOfDay(new Date()));
            }

        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));

    }

    @Override
    public List countAllChange(Map<String, Object> params) {
        List<DailyVo> list = new ArrayList<>();

        String orgId = (String)params.get("orgId");
        String startDate = (String)params.get("startDate");
        String endDate = (String)params.get("endDate");
        String type = (String)params.get("type");


        QueryWrapper<DailyTabulateData> wrapper = new QueryWrapper<>();
        wrapper.eq("org_id",orgId);
        if (startDate != null && startDate.length() > 0){
            if (startDate.length()==7){
                startDate = startDate+"-01";
            }
            if ( startDate.length()==4){
                startDate = startDate+"-01-01";
            }
        }

        if (endDate != null && endDate.length() > 0){
            if ( endDate.length()==4){
                endDate = endDate+"-12-30";
            }
            if ( endDate.length()==7){
                endDate = endDate+"-30";
            }
        }


        wrapper.ge(StringUtils.isNotBlank(startDate),"statistic_date",startDate);
        wrapper.le(StringUtils.isNotBlank(endDate),"statistic_date",endDate);
        wrapper.groupBy("ydate");
        wrapper.orderByDesc("statistic_date");

        if ("1".equals(type)){
            if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
                wrapper.last("limit 7");
            }
            list = baseMapper.selectDay(wrapper);
        }
        if ("2".equals(type)){
            if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
                wrapper.last("limit 6");
            }
            list = baseMapper.selectMonth(wrapper);
        }
        if ("3".equals(type)){
            if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
                wrapper.last("limit 5");
            }
            list = baseMapper.selectYear(wrapper);
        }

        return list;
    }

    @Override
    public PageResult farmList(Map<String, Object> params) {

        String minStockTotal = (String)params.get("minStockTotal");
        String maxStockTotal = (String)params.get("maxStockTotal");
        String minStockNew = (String)params.get("minStockNew");
        String maxStockNew = (String)params.get("maxStockNew");
        String minOfflineNo = (String)params.get("minOfflineNo");
        String maxOfflineNo = (String)params.get("maxOfflineNo");
        String orgId = (String)params.get("orgId");
        if (ObjectUtil.isEmpty(orgId)){
            orgId = LoginContextHolder.me().getSysLoginUserOrgId()+"";
        }
        QueryWrapper<DailyTabulateData> wrapper = new QueryWrapper<>();
        wrapper.eq("org_id",orgId);
        if (StringUtils.isNotBlank(minStockTotal)){
            wrapper.ge("stock_total",Integer.parseInt(minStockTotal));
        }
        if (StringUtils.isNotBlank(maxStockTotal)){
            wrapper.le("stock_total",Integer.parseInt(maxStockTotal));
        }
        if (StringUtils.isNotBlank(minStockNew)){
            wrapper.ge("stock_new",Integer.parseInt(minStockNew));
        }
        if (StringUtils.isNotBlank(maxStockNew)){
            wrapper.le("stock_new",Integer.parseInt(maxStockNew));
        }
        if (StringUtils.isNotBlank(minOfflineNo)){
            wrapper.ge("offline_no",Integer.parseInt(minOfflineNo));
        }
        if (StringUtils.isNotBlank(maxOfflineNo)){
            wrapper.le("offline_no",Integer.parseInt(maxOfflineNo));
        }

        return new PageResult<>(this.page(PageFactory.defaultPage(),wrapper));
    }
}
