package com.huimv.learn;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.SpliteratorUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.InjectorResolver;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huimv.CloudPlatformApplication;
import com.huimv.modular.basefarminfo.entity.BaseFarmInfoEntity;
import com.huimv.modular.basefarminfo.mapper.BaseFarmInfoMapper;
import com.huimv.modular.basepigpen.entity.BasePigpen;
import com.huimv.modular.basepigpen.mapper.BasePigpenMapper;
import com.huimv.modular.collectorregister.entity.CollectorRegister;
import com.huimv.modular.collectorregister.mapper.CollectorRegisterMapper;
import com.huimv.modular.constant.ConstnatValue;
import com.huimv.modular.dailytabulatedata.entity.DailyTabulateData;
import com.huimv.modular.dailytabulatedata.mapper.DailyTabulateDataMapper;
import com.huimv.modular.eartagdata.entity.EartagData;
import com.huimv.modular.eartagdata.mapper.EartagDataMapper;
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.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

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

//需要加上启动类的
@SpringBootTest(classes = CloudPlatformApplication.class)
public class test001 {


    @Resource
    private YesterdayPigMapper yesterdayPigMapper;

    @Resource
    private SysOrgMapper sysOrgMapper;

    @Resource
    private DailyTabulateDataMapper dailyTabulateDataMapper;
    @Autowired
    private EartagRegisterMapper eartagRegisterMapper   ;

    @Autowired
    private BasePigpenMapper  basePigpenMapper    ;

    @Autowired
    private EartagDataMapper eartagDataMapper;

    @Autowired
    private BaseFarmInfoMapper  baseFarmInfoMapper ;


    @Autowired
    private CollectorRegisterMapper  collectorRegisterMapper  ;












    @Test
    public void test077403 () {
        //所有采集器
        LambdaQueryWrapper<CollectorRegister> wrapper3 = Wrappers.lambdaQuery();
        //  wrapper3.eq(CollectorRegister::getDeviceCode, record.getDeviceCode());
        List<CollectorRegister> collectorRegisters = collectorRegisterMapper.selectList(wrapper3);

        for (CollectorRegister collectorRegister : collectorRegisters) {
            LambdaQueryWrapper<SysOrg> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(SysOrg::getCode, collectorRegister.getFarmCode());
            SysOrg sysOrg = sysOrgMapper.selectOne(wrapper);
            System.out.println(sysOrg);
            collectorRegister.setOrgId(sysOrg.getId());
            collectorRegisterMapper.updateById(collectorRegister);

        }
    }




    @Test
    public void test07227403 () {
        //所有采集器
        LambdaQueryWrapper<DailyTabulateData> wrapper3 = Wrappers.lambdaQuery();
          wrapper3.eq(DailyTabulateData::getFarmCode,"330381010000390");
        List<DailyTabulateData> dailyTabulateDataList = dailyTabulateDataMapper.selectList(wrapper3);


        RestTemplate restTemplateAddController = new RestTemplate();
        //放置   tokrn 到  header
        HttpHeaders headers = new HttpHeaders();
        //不需要权限了
        //headers.add("Authorization", "Bearer " + json.get("data"));
        // headers.add("Content-Type", "applicati on/json");
        Map<String, Object> requestBody = new HashMap<>(8);
        requestBody.put("dailyTabulateDataList",dailyTabulateDataList );
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(requestBody, headers);
        //用的是 199数据库  只有这一个数据库     调用他的增加办法
        String body = restTemplateAddController.postForEntity("http://127.0.0.1:9500/manager/dailytabulatedata/addByFarm", httpEntity, String.class).getBody();
        System.out.println(body);

        JSONObject jsonObject = JSON.parseObject(body);
        Integer code =(Integer) jsonObject.get("code");


    }












/*
        //赋值orgid

        for (CollectorRegister collectorRegister : collectorRegisters) {

            QueryWrapper<> queryWrapper = new QueryWrapper<>();
            List<CollectorRegister> collectorRegisters = collectorRegisterMapper.selectList(queryWrapper);

            //组织id

        }

        for (EartagRegister eartagDatum : eartagData) {


        }*/


    @Test
    public void test07745503 () {
        //所有采集器
        LambdaQueryWrapper<EartagRegister> wrapper3 = Wrappers.lambdaQuery();
        //  wrapper3.eq(CollectorRegister::getDeviceCode, record.getDeviceCode());
        List<EartagRegister> eartagData = eartagRegisterMapper.selectList(wrapper3);

        for (EartagRegister eartagDatum : eartagData) {
            LambdaQueryWrapper<CollectorRegister> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(CollectorRegister::getDeviceCode, eartagDatum.getDeviceCode());
            CollectorRegister collectorRegisters = collectorRegisterMapper.selectOne(wrapper);
            eartagDatum.setStage(collectorRegisters.getStage());
            eartagDatum.setOrgId(collectorRegisters.getOrgId());
            eartagDatum.setFarmCode(collectorRegisters.getFarmCode());

            System.out.println(eartagDatum.getId());
            eartagRegisterMapper.updateById(eartagDatum);
        }
    }



         //eartag_data 里面也要有一条  --采集时间为注册时间

        @Test
        public void test0774555503 () {
            //所有采集器
            LambdaQueryWrapper<EartagRegister> wrapper3 = Wrappers.lambdaQuery();
            //  wrapper3.eq(CollectorRegister::getDeviceCode, record.getDeviceCode());
            List<EartagRegister> eartagData = eartagRegisterMapper.selectList(wrapper3);

            for (EartagRegister eartagDatum : eartagData) {
                LambdaQueryWrapper<CollectorRegister> wrapper = Wrappers.lambdaQuery();
                wrapper.eq(CollectorRegister::getDeviceCode, eartagDatum.getDeviceCode());
                CollectorRegister collectorRegisters = collectorRegisterMapper.selectOne(wrapper);
                eartagDatum.setStage(collectorRegisters.getStage());
                eartagDatum.setOrgId(collectorRegisters.getOrgId());
                eartagDatum.setFarmCode(collectorRegisters.getFarmCode());
                System.out.println(eartagDatum.getId());
                eartagRegisterMapper.updateById(eartagDatum);
            }
        }
































    //整理数据
    @Test
    public void test07741103 () {
        //首先处理设备编码

/*
        //通过
        QueryWrapper<> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("eartag_no", String.valueOf(i));
        List<EartagRegister> eartagData = eartagRegisterMapper.selectList(queryWrapper);
        for (EartagRegister eartagDatum : eartagData) {
*/
    }

        @Test
        public void test0001() {
            System.out.println("--------------start");
            QueryWrapper<DailyTabulateData> wrapper = new QueryWrapper<>();
            wrapper.eq("statistic_date",DateUtil.beginOfDay(new Date()));
            dailyTabulateDataMapper.delete(wrapper);

            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);

                System.out.println(orgIds);
                QueryWrapper<EartagRegister> eartagRegisterQueryWrapper = new QueryWrapper<>();
                eartagRegisterQueryWrapper.in("org_id",orgIds);
                List<EartagRegister> eartagRegisters = eartagRegisterMapper.selectList(eartagRegisterQueryWrapper);

                System.out.println(eartagRegisters+"erbiao");
                //计算日龄
                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++;
                    }
                    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+stock3+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();
                int offSow =0;
                if ( yesterdayPigs.size()-allSow > 0){
                    offSow = yesterdayPigs.size()-allSow;
                }
                //新增耳标
                nowEartagClone.removeAll(yesterdayEartag);
                int newSow = 0;
                if ( allSow-yesterdayPigs.size() > 0){
                    newSow = allSow-yesterdayPigs.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);
                dailyTabulateData.setStock6(stock6);
                //这个是什么意思
                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) + "%";
        }




    }
