/*
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.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huimv.core.annotion.BusinessLog;
import com.huimv.core.annotion.DataScope;
import com.huimv.core.annotion.Permission;
import com.huimv.core.enums.LogAnnotionOpTypeEnum;
import com.huimv.core.pojo.page.PageResult;
import com.huimv.core.pojo.response.ResponseData;
import com.huimv.core.pojo.response.SuccessResponseData;
import com.huimv.modular.dailytabulatedata.entity.DailyTabulateData;
import com.huimv.modular.dailytabulatedata.mapper.DailyTabulateDataMapper;
import com.huimv.modular.dailytabulatedata.param.DailyTabulateDataParam;
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.result.R;
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 com.huimv.sys.modular.org.service.SysOrgService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 耳标每日汇总表控制器
 *
 * @author yinhao
 * @date 2021-08-17 14:34:00
 */
@RestController
public class DailyTabulateDataController {

    @Resource
    private DailyTabulateDataService dailyTabulateDataService;


    @RequestMapping("/dailyTabulateData/countAllSow")
    public ResponseData countAllsow(Long orgId) {
        Map list = dailyTabulateDataService.countAllsow(orgId);

        return new SuccessResponseData(list);
    }


    /**
     * 列表
     */
    @RequestMapping("/dailyTabulateData/list")
    public ResponseData list(DailyTabulateData dailyTabulateData) {
        PageResult page = dailyTabulateDataService.queryPage(dailyTabulateData);

        return new SuccessResponseData(page);
    }


    @RequestMapping("/dailyTabulateData/countAllChange")
    public ResponseData countAllChange(@RequestParam Map<String, Object> params) {
      List lsit   = dailyTabulateDataService.countAllChange(params);

        return new SuccessResponseData(lsit);
    }


    /**
     * 列表(牧场)
     */
    @RequestMapping("/dailyTabulateData/farmList")
    public ResponseData f(@RequestParam Map<String, Object> params) {
        PageResult page = dailyTabulateDataService.farmList(params);

        return new SuccessResponseData(page);
    }


//测试中
   /* @Resource
    private SysOrgService sysOrgService;

    @Resource
    private EartagRegisterMapper eartagRegisterMapper;

    @Resource
    private SysOrgMapper sysOrgMapper;

    @Resource
    private YesterdayPigMapper yesterdayPigMapper;
    @Resource
    private DailyTabulateDataMapper dailyTabulateDataMapper;


    @Scheduled(cron = "0 * * * * ?")
    public void test() {
        System.out.println("--------------start");
        QueryWrapper<SysOrg> sysOrgQueryWrapper1 = new QueryWrapper<>();
        sysOrgQueryWrapper1.eq("status",0);
        List<SysOrg> list = sysOrgMapper.selectList(sysOrgQueryWrapper1);
        Date now = new Date();
        for (SysOrg sysOrg : list) {
            Long orgId = sysOrg.getId();
            QueryWrapper<SysOrg> sysOrgQueryWrapper = new QueryWrapper<>();
            sysOrgQueryWrapper.like("pids",orgId);
            sysOrgQueryWrapper.eq("status",0);
            List<SysOrg> sysOrgs = sysOrgMapper.selectList(sysOrgQueryWrapper);
            List<Long> orgIds = CollectionUtil.newArrayList();
            for (SysOrg org : sysOrgs) {
                orgIds.add(org.getId());
            }
            orgIds.add(orgId);


            QueryWrapper<EartagRegister> eartagRegisterQueryWrapper = new QueryWrapper<>();
            eartagRegisterQueryWrapper.in("org_id",orgIds);
            List<EartagRegister> eartagRegisters = eartagRegisterMapper.selectList(eartagRegisterQueryWrapper);
            //计算日龄
            Integer ratio1 = 0, ratio2 = 0, ratio3 = 0, ratio4 = 0;
            //（1：配种舍，2：分娩舍，3：保育舍，4：育成育肥舍，5：空怀舍，6：后备母猪舍，
            // 7：公猪舍，8：病死猪场内收集点，9：病死猪集中收集点，10：病死猪无害化处理中心
            Set<String> nowEartag = CollectionUtil.newHashSet();
            int stock1 =0,stock2=0,stock3=0,stock4=0,stock5=0,stock6=0,stock7=0;
            for (EartagRegister eartagRegister : eartagRegisters) {
                Integer stage = eartagRegister.getStage();
                if (stage == 1  ){
                    stock1++;
                }
                if (stage == 2  ){
                    stock2++;
                }
                if (stage == 3  ){
                    stock3++;
                }
                if (stage == 4  ){
                    stock4++;
                }
                if (stage == 5  ){
                    stock5++;
                }
                if (stage == 6  ){
                    stock6++;
                }
                if (stage == 7  ){
                    stock7++;
                }
                nowEartag.add(eartagRegister.getEartagNo());

                Integer dayAge = eartagRegister.getAge();
                if (dayAge != null) {
                    if (dayAge > 240 && dayAge < 600) {
                        ratio1++;
                    }

                    if (dayAge >= 600 && dayAge < 960) {
                        ratio2++;
                    }

                    if (dayAge >= 960 && dayAge < 1320) {
                        ratio3++;
                    }

                    if (dayAge >= 1320) {
                        ratio4++;
                    }
                }

            }
            //母猪总存栏
            int allSow = stock1+stock2+stock5+stock6;
            String ratioStr1 = calculateUtil(BigDecimal.valueOf(ratio1), BigDecimal.valueOf(allSow));
            String ratioStr2 = calculateUtil(BigDecimal.valueOf(ratio2), BigDecimal.valueOf(allSow));
            String ratioStr3 = calculateUtil(BigDecimal.valueOf(ratio3), BigDecimal.valueOf(allSow));
            String ratioStr4 = calculateUtil(BigDecimal.valueOf(ratio4), BigDecimal.valueOf(allSow));

            //昨日耳标
            QueryWrapper<YesterdayPig> yesterdayPigQueryWrapper = new QueryWrapper<>();
            yesterdayPigQueryWrapper.in("org_id",orgIds);
            List<YesterdayPig> yesterdayPigs = yesterdayPigMapper.selectList(yesterdayPigQueryWrapper);
            Set<String> yesterdayEartag = CollectionUtil.newHashSet();
            for (YesterdayPig yesterdayPig : yesterdayPigs) {
                yesterdayEartag.add(yesterdayPig.getEartagNo());
            }

            Set<String> yesterdayEartagClone = ObjectUtil.cloneByStream(yesterdayEartag);
            Set<String> nowEartagClone = ObjectUtil.cloneByStream(nowEartag);
            //离线耳标
            yesterdayEartagClone.removeAll(nowEartag);
            int offSow = yesterdayEartagClone.size();
            //新增耳标
            nowEartagClone.removeAll(yesterdayEartag);
            int newSow = nowEartagClone.size();



            //添加到每日表
            QueryWrapper<DailyTabulateData> dailyTabulateDataQueryWrapper = new QueryWrapper<>();
            dailyTabulateDataQueryWrapper.eq("statistic_date", DateUtil.beginOfDay(now));
            dailyTabulateDataQueryWrapper.eq("org_id",orgId);
            DailyTabulateData  dailyTabulateData = dailyTabulateDataMapper.selectOne(dailyTabulateDataQueryWrapper);
            if (dailyTabulateData == null) {
                dailyTabulateData = new DailyTabulateData();
            }

            dailyTabulateData.setOrgId(orgId);
            dailyTabulateData.setStock1(stock1);
            dailyTabulateData.setStock2(stock2);
            dailyTabulateData.setStock3(stock3);
            dailyTabulateData.setStock4(stock4);
            dailyTabulateData.setStock5(stock5);
            if (eartagRegisters.size() > 0){
                dailyTabulateData.setFarmCode(eartagRegisters.get(0).getFarmCode());
            }
            dailyTabulateData.setStockTotal(allSow);
            dailyTabulateData.setStatisticDate(now);
            dailyTabulateData.setStockNew(newSow);
            dailyTabulateData.setOfflineNo(offSow);
            dailyTabulateData.setRatio1(ratio1 + " (" + ratioStr1 + ")");
            dailyTabulateData.setRatio2(ratio2 + " (" + ratioStr2 + ")");
            dailyTabulateData.setRatio3(ratio3 + " (" + ratioStr3 + ")");
            dailyTabulateData.setRatio4(ratio4 + " (" + ratioStr4 + ")");
            dailyTabulateData.setSowStock(stock1 + stock2 + stock3);
            dailyTabulateData.setOrgName(sysOrg.getName());
            if (dailyTabulateData.getId() == null) {
                dailyTabulateDataMapper.insert(dailyTabulateData);
            } else {
                dailyTabulateDataMapper.updateById(dailyTabulateData);
            }
        }
    }
    //计算百分比
    public String calculateUtil(BigDecimal a, BigDecimal b) {
        return b == null ? "-" :
                b.compareTo(new BigDecimal(0)) == 0 ? "-" :
                        a == null ? "0.00%" :
                                a.multiply(new BigDecimal(100)).divide(b, 2, BigDecimal.ROUND_HALF_UP) + "%";
    }*/
}