package com.huimv.management.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huimv.common.exception.RRException;
import com.huimv.common.utils.R;
import com.huimv.management.dao.PeriodDao;
import com.huimv.management.dao.TransferPeriodLogDao;
import com.huimv.management.dao.UnitDao;
import com.huimv.management.entity.*;
import com.huimv.management.entity.vo.CountOut;
import com.huimv.management.entity.vo.DrinkingWaterVo;
import com.huimv.management.entity.vo.PigBaseVo;
import com.huimv.management.util.GetUserUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.common.utils.PageUtils;
import com.huimv.common.utils.Query;
import com.huimv.management.dao.YearPigBaseDao;
import com.huimv.management.service.YearPigBaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;


@Service("yearPigBaseService")
public class YearPigBaseServiceImpl extends ServiceImpl<YearPigBaseDao, YearPigBaseEntity> implements YearPigBaseService {

    @Autowired
    private YearPigBaseDao pigBaseDao;

    @Autowired
    private PeriodDao periodDao;

    @Autowired
    private UnitDao unitDao;

    @Autowired
    private TransferPeriodLogDao transferPeriodLogDao;

//    @Override
//    public PageUtils queryPage(Map<String, Object> params) {
//
//        LambdaQueryWrapper<YearPigBaseEntity> lambdaQuery = Wrappers.lambdaQuery();
//        String keyword = (String) params.get("keyword");
//        //没有参数
//        if (keyword == null || keyword.equals("")){
//            IPage<YearPigBaseEntity> page = this.page(
//                    new Query<YearPigBaseEntity>().getPage(params),
//                    new QueryWrapper<YearPigBaseEntity>()
//            );
//            return new PageUtils(page);
//        }
//
//        lambdaQuery.like(YearPigBaseEntity::getBreed,keyword);
//        IPage<YearPigBaseEntity> page = page(this.page(
//                new Query<YearPigBaseEntity>().getPage(params)
//        ), lambdaQuery);
//
//
//        return new PageUtils(page);
//    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        //构建条件查询wrapper
        QueryWrapper<DrinkingWaterVo> queryWrapper = new QueryWrapper<>();

        //耳标
        String eartag = (String) params.get("eartag");
        if (StringUtils.isNotEmpty(eartag)) {
            queryWrapper.like("base.eartag",eartag);
        }

        //性别
        String sex = (String) params.get("sex");
        if (StringUtils.isNotEmpty(sex)) {
            queryWrapper.eq("base.sex",sex);
        }

        //品种
        String breed = (String) params.get("breed");
        if (StringUtils.isNotEmpty(breed)) {
            queryWrapper.eq("base.breed",breed);
        }

        //健康状态
        String healthStatus = (String) params.get("healthStatus");
        if (StringUtils.isNotEmpty(healthStatus)) {
            queryWrapper.eq("base.health_status",Integer.parseInt(healthStatus));
        }

        //养殖状态
        String outFenceStatus = (String) params.get("outFenceStatus");
        if (StringUtils.isNotEmpty(outFenceStatus)) {
            queryWrapper.eq("base.out_fence_status",Integer.parseInt(outFenceStatus));
        }

        //栏期
        String periodId = (String) params.get("periodId");
        if (StringUtils.isNotEmpty(periodId)) {
            queryWrapper.eq("base.period_id",Integer.parseInt(periodId));
        }

        //栋舍
        String pigstyId = (String) params.get("pigstyId");
        if (StringUtils.isNotEmpty(pigstyId)) {
            queryWrapper.eq("base.pigsty_id",Integer.parseInt(pigstyId));
        }
        //单元
        String unitId = (String) params.get("unitId");
        if (StringUtils.isNotEmpty(unitId)) {
            queryWrapper.eq("base.unit_id",Integer.parseInt(unitId));
        }

        //牧场
        String farmId = (String) params.get("formFarmId");
        if (StringUtils.isNotEmpty(farmId)) {
            queryWrapper.eq("base.farm_id",Integer.parseInt(farmId));
        }
        //排除逻辑删除
        queryWrapper.apply(" base.deleted = 0  AND pigsty.deleted = 0 ");

        IPage<PigBaseVo> page = pigBaseDao.list(new Query<>().getPage(params),queryWrapper);



        return new PageUtils(page);
    }


    @Override
    public void batchLairage(String[] eartags,Integer periodId) {
        for (String eartag : eartags) {
            UpdateWrapper<YearPigBaseEntity> updateWrapper = new UpdateWrapper<YearPigBaseEntity>();
            updateWrapper.eq("eartag",eartag).set("period_id",periodId);
            update(updateWrapper);
        }
    }

    @Override
    public void such(Integer[] ids) {
        pigBaseDao.such(ids);
    }

    @Override
    public void suchApp(String[] ids) {
        pigBaseDao.suchApp(ids);
    }

    @Override
    public Integer findByoutFenceStatus(int i, Integer farmId) {
        LambdaQueryWrapper<YearPigBaseEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(YearPigBaseEntity::getFarmId,farmId);
        wrapper.eq(YearPigBaseEntity::getOutFenceStatus,i);
        Integer integer = pigBaseDao.selectCount(wrapper);
        return integer;
    }

    //查看认养状态
    @Override
    public Integer findByFosterStatus(int i, Integer formFarmId) {
        LambdaQueryWrapper<YearPigBaseEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(YearPigBaseEntity::getFarmId,formFarmId);
        wrapper.eq(YearPigBaseEntity::getFosterStatus,i);
        Integer integer = pigBaseDao.selectCount(wrapper);
        return integer;
    }

    @Override
    public   Map<String ,Object> queryPageByRelationship(Map<String, Object> params) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {

        Map<String, Object> result = new HashMap<>();
        String eartag_no = (String) params.get("eartag");
        System.out.println(eartag_no);
        YearPigBaseEntity  self = baseMapper.selectOne(Wrappers.<YearPigBaseEntity>lambdaQuery().eq(YearPigBaseEntity::getEartag, eartag_no));
        System.out.println(self);
        // result.put("self",   self  );

        System.out.println("父亲ID"+self.getFatherEartag());   System.out.println("母亲ID"+self.getMotherEartag());
        String math = self.getMotherEartag();

        YearPigBaseEntity father = self.getFatherEartag() == null ? null :  baseMapper.selectOne(Wrappers.<YearPigBaseEntity>lambdaQuery().eq(YearPigBaseEntity::getEartag, self.getFatherEartag()));
        YearPigBaseEntity mother = self.getMotherEartag() == null ? null :  baseMapper.selectOne(Wrappers.<YearPigBaseEntity>lambdaQuery().eq(YearPigBaseEntity::getEartag, math));


        //父亲父母
        // result.put("father", father);
        // result.put("mother", mother);
        YearPigBaseEntity fathermother = father == null ? null :  baseMapper.selectOne(Wrappers.<YearPigBaseEntity>lambdaQuery().eq(YearPigBaseEntity::getEartag, father.getFatherEartag()));
        YearPigBaseEntity fatherfather = father == null ? null :  baseMapper.selectOne(Wrappers.<YearPigBaseEntity>lambdaQuery().eq(YearPigBaseEntity::getEartag, father.getMotherEartag()));
        //  result.put("fathermother", fathermother);
        // result.put("fatherfather", fatherfather);
        //母亲父母
        YearPigBaseEntity mothermother = mother == null ? null :  baseMapper.selectOne(Wrappers.<YearPigBaseEntity>lambdaQuery().eq(YearPigBaseEntity::getEartag, mother.getFatherEartag()));
        YearPigBaseEntity  motherfather = mother == null ? null :  baseMapper.selectOne(Wrappers.<YearPigBaseEntity>lambdaQuery().eq(YearPigBaseEntity::getEartag, mother.getMotherEartag()));
        //  result.put("mothermother", mothermother);
        // result.put("motherfather", motherfather);




        Object[] intArr = new Object[7];
        Map<String, String> selfmap = BeanUtils.describe(self);
        selfmap.put("name","self");
        Map<String, String> fathermap = BeanUtils.describe(father);
        fathermap.put("name","father");
        Map<String, String> mothermap = BeanUtils.describe(mother);
        mothermap.put("name","mother");
        Map<String, String> fathermothermap = BeanUtils.describe(fathermother);
        fathermothermap.put("name","fathermother");
        Map<String, String> fatherfatherself = BeanUtils.describe(fatherfather);
        fatherfatherself.put("name","fatherfather");
        Map<String, String> mothermotherself = BeanUtils.describe(mothermother);
        mothermotherself.put("name","mothermother");
        Map<String, String> motherfatherself = BeanUtils.describe(motherfather);
        motherfatherself.put("name","motherfather");


        intArr[0] = selfmap;
        intArr[1] = fathermap;
        intArr[2] = mothermap;
        intArr[3] = fathermothermap;
        intArr[4] = fatherfatherself;
        intArr[5] = mothermotherself;
        intArr[6] = motherfatherself;

        result.put("value",intArr);
        return   result;
    }



    @Override
    public List<CountOut> suchStatistics(String startTime, String endTime, Integer farmId) {
        QueryWrapper<YearPigBaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("farm_id", farmId);

        //开始时间
        if (StringUtils.isNotEmpty(startTime)) {
            wrapper.ge("out_fence_time", startTime);
        }
        //开始时间
        if (StringUtils.isNotEmpty(endTime)) {
            wrapper.le("out_fence_time", endTime);
        }
        wrapper.apply("deleted = 0 AND out_fence_status = 1 ");

        List<CountOut> endList  = pigBaseDao.suchStatistics(farmId,wrapper);
        return endList;
    }

    @Override
    public List<CountOut> suchStatisteicsMonth(String startTime, String endTime, int farmId) {

        QueryWrapper<YearPigBaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("farm_id", farmId);

        //开始时间
        if (StringUtils.isNotEmpty(startTime)) {
            wrapper.ge("out_fence_time", startTime);
        }
        //开始时间
        if (StringUtils.isNotEmpty(endTime)) {
            wrapper.le("out_fence_time", endTime);
        }
        wrapper.apply("deleted = 0 AND out_fence_status = 1 ");

        List<CountOut> endList  = pigBaseDao.suchStatisticsMonth(farmId,wrapper);
        return endList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transferPeriod(HashMap<String, Object> map, HttpServletRequest request) {

        List<Integer> pigIds = (List<Integer>) map.get("pigIds");
        Integer unitId = (Integer) map.get("unitId");

        if (CollUtil.isEmpty(pigIds) || unitId == null) {
            throw new RRException("参数有误,请检查!",1001);
        }

        List<TransferPeriodLogEntity> logEntityList = new ArrayList<>();
        YearPigBaseEntity yearPigBaseEntity = new YearPigBaseEntity();
        //获取当前操作用户
        SysUserEntity user = null;
        try {
            user = GetUserUtil.getUser(request);
        } catch (Exception e) {
            throw new RRException("获取用户信息异常!");
        }
        String username = user.getUsername();

        for (Integer pigId : pigIds) {

            YearPigBaseEntity oldEntity = baseMapper.selectById(pigId);
            if (oldEntity == null) {
                throw new RRException("查不到id为" + pigId + "的猪的信息,请检查参数!",1001);
            }
            if (oldEntity.getUnitId().equals(unitId)) {
                throw new RRException(oldEntity.getEartag() + "所转单元不能和原单元相同!",1001);
            }

            UnitEntity unitEntity = unitDao.selectById(unitId);
            if (unitEntity == null) {
                throw new RRException("查不到id为" + unitId + "的单元的信息,请检查参数!",1001);
            }

            TransferPeriodLogEntity entity = new TransferPeriodLogEntity();
            entity.setFarmId(unitEntity.getFarmId());
            entity.setPigId(pigId);
            entity.setEarTag(oldEntity.getEartag());
            entity.setOldPigstyId(oldEntity.getPigstyId());
            entity.setNewPigstyId(unitEntity.getPigstyId());
            entity.setOldUnitId(oldEntity.getUnitId());
            entity.setNewUnitId(unitId);
            entity.setOldPeriodId(oldEntity.getPeriodId());
            entity.setNewPeriodId(unitEntity.getCurrentPeriodId());
            entity.setOperatorUsername(username);
            logEntityList.add(entity);

            yearPigBaseEntity.setId(pigId);
            yearPigBaseEntity.setPigstyId(unitEntity.getPigstyId());
            yearPigBaseEntity.setUnitId(unitId);
            yearPigBaseEntity.setPeriodId(unitEntity.getCurrentPeriodId());
            updateById(yearPigBaseEntity);
        }
        transferPeriodLogDao.batchInsert(logEntityList);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transferPeriodClient(HashMap<String, Object> map, HttpServletRequest request) {
        String earTags = (String) map.get("earTags");

        Integer unitId = (Integer) map.get("unitId");

        if (StringUtils.isBlank(earTags) || unitId == null) {
            throw new RRException("参数有误,请检查!",1001);
        }
        String[] earTagList = earTags.split(",");

        List<TransferPeriodLogEntity> logEntityList = new ArrayList<>();
        YearPigBaseEntity yearPigBaseEntity = new YearPigBaseEntity();
        //获取当前操作用户
        SysUserEntity user = null;
        try {
            user = GetUserUtil.getUser(request);
        } catch (Exception e) {
            throw new RRException("获取用户信息异常!");
        }
        String username = user.getUsername();

        LambdaQueryWrapper<YearPigBaseEntity> queryWrapper = Wrappers.lambdaQuery();
        for (String eatTag : earTagList) {
            queryWrapper.eq(YearPigBaseEntity::getEartag,eatTag);
            YearPigBaseEntity oldEntity = baseMapper.selectOne(queryWrapper);
            queryWrapper.clear();

            if (oldEntity == null) {
                throw new RRException("查不到earTag为" + eatTag + "的猪的信息,请检查参数!",1001);
            }

            if (oldEntity.getUnitId().equals(unitId)) {
                throw new RRException(oldEntity.getEartag() + "所转单元不能和原单元相同!",1001);
            }

            UnitEntity unitEntity = unitDao.selectById(unitId);
            if (unitEntity == null) {
                throw new RRException("查不到id为" + unitId + "的单元的信息,请检查参数!",1001);
            }

            TransferPeriodLogEntity entity = new TransferPeriodLogEntity();
            entity.setFarmId(unitEntity.getFarmId());
            entity.setPigId(oldEntity.getId());
            entity.setEarTag(eatTag);
            entity.setOldPigstyId(oldEntity.getPigstyId());
            entity.setNewPigstyId(unitEntity.getPigstyId());
            entity.setOldUnitId(oldEntity.getUnitId());
            entity.setNewUnitId(unitId);
            entity.setOldPeriodId(oldEntity.getPeriodId());
            entity.setNewPeriodId(unitEntity.getCurrentPeriodId());
            entity.setOperatorUsername(username);
            logEntityList.add(entity);

            yearPigBaseEntity.setId(oldEntity.getPigstyId());
            yearPigBaseEntity.setUnitId(unitId);
            yearPigBaseEntity.setPeriodId(unitEntity.getCurrentPeriodId());
            updateById(yearPigBaseEntity);
        }
        transferPeriodLogDao.batchInsert(logEntityList);
    }


    //查询栏期下是否有小猪
    @Override
    public Integer countByPeriodId(Integer currentPeriodId) {
        QueryWrapper<YearPigBaseEntity> wrapper = new QueryWrapper<YearPigBaseEntity>();
        wrapper.eq("period_id",currentPeriodId);
        return baseMapper.selectCount(wrapper);
    }

    @Override
    public PageUtils fattenList(Map<String, Object> params) {
        //构建条件查询wrapper
        QueryWrapper<DrinkingWaterVo> queryWrapper = new QueryWrapper<>();

        //耳标
        String eartag = (String) params.get("eartag");
        if (StringUtils.isNotEmpty(eartag)) {
            queryWrapper.like("base.eartag",eartag);
        }

        //性别
        String sex = (String) params.get("sex");
        if (StringUtils.isNotEmpty(sex)) {
            queryWrapper.eq("base.sex",sex);
        }

        //品种
        String breed = (String) params.get("breed");
        if (StringUtils.isNotEmpty(breed)) {
            queryWrapper.eq("base.breed",breed);
        }

        //健康状态
        String healthStatus = (String) params.get("healthStatus");
        if (StringUtils.isNotEmpty(healthStatus)) {
            queryWrapper.eq("base.health_status",Integer.parseInt(healthStatus));
        }

        //养殖状态
        String outFenceStatus = (String) params.get("outFenceStatus");
        if (StringUtils.isNotEmpty(outFenceStatus)) {
            queryWrapper.eq("base.out_fence_status",Integer.parseInt(outFenceStatus));
        }

        //栏期
        String periodId = (String) params.get("periodId");
        if (StringUtils.isNotEmpty(periodId)) {
            queryWrapper.eq("base.period_id",Integer.parseInt(periodId));
        }

        //栋舍
        String pigstyId = (String) params.get("pigstyId");
        if (StringUtils.isNotEmpty(pigstyId)) {
            queryWrapper.eq("base.pigsty_id",Integer.parseInt(pigstyId));
        }
        //单元
        String unitId = (String) params.get("unitId");
        if (StringUtils.isNotEmpty(unitId)) {
            queryWrapper.eq("base.unit_id",Integer.parseInt(unitId));
        }

        //牧场
        String farmId = (String) params.get("formFarmId");
        if (StringUtils.isNotEmpty(farmId)) {
            queryWrapper.eq("base.farm_id",Integer.parseInt(farmId));
        }
        //排除逻辑删除
        queryWrapper.apply(" base.deleted = 0  AND pigsty.deleted = 0 AND base.out_fence_status = 0 ");

        IPage<PigBaseVo> page = pigBaseDao.fattenList(new Query<>().getPage(params),queryWrapper);



        return new PageUtils(page);
    }

    @Override
    public HashMap<String, Integer> statisticsAll(Map<String, Object> params) {
        HashMap<String,Integer> resultMap = new HashMap<>();
        String formFarmId = (String)params.get("formFarmId");
        LambdaQueryWrapper<YearPigBaseEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(StringUtils.isNotBlank(formFarmId),YearPigBaseEntity::getFarmId,Integer.parseInt(formFarmId));
        //出栏
        wrapper.eq(YearPigBaseEntity::getOutFenceStatus,1);
        Integer outFence = pigBaseDao.selectCount(wrapper);
        wrapper.clear();
        resultMap.put("outFence",outFence);
        //育肥
        wrapper.eq(StringUtils.isNotBlank(formFarmId),YearPigBaseEntity::getFarmId,Integer.parseInt(formFarmId));
        wrapper.eq(YearPigBaseEntity::getOutFenceStatus,0);
        Integer fence = pigBaseDao.selectCount(wrapper);
        wrapper.clear();
        resultMap.put("fence",fence);
        //认养
        wrapper.eq(StringUtils.isNotBlank(formFarmId),YearPigBaseEntity::getFarmId,Integer.parseInt(formFarmId));
        wrapper.eq(YearPigBaseEntity::getFosterStatus,1);
        Integer foster = pigBaseDao.selectCount(wrapper);
        wrapper.clear();
        resultMap.put("foster",foster);


        //未认养
        wrapper.eq(StringUtils.isNotBlank(formFarmId),YearPigBaseEntity::getFarmId,Integer.parseInt(formFarmId));
        wrapper.eq(YearPigBaseEntity::getFosterStatus,0);
        Integer noFoster = pigBaseDao.selectCount(wrapper);
        wrapper.clear();
        resultMap.put("noFoster",noFoster);



        return resultMap;
    }
}