package vip.xiaonuo.production.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import vip.xiaonuo.production.entity.ProduceLocation;
import vip.xiaonuo.production.entity.ProductionWorkstopPlan;
import vip.xiaonuo.production.entity.vo.*;
import vip.xiaonuo.production.mapper.ProduceLocationMapper;
import vip.xiaonuo.production.mapper.ProductionUnitCostMapper;
import vip.xiaonuo.production.mapper.ProductionWorkstopPlanMapper;
import vip.xiaonuo.production.param.*;
import vip.xiaonuo.production.service.IProductionWorkstopPlanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import vip.xiaonuo.purchase.param.GongYingShangParam;
import vip.xiaonuo.sale.entity.SaleSalesman;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 生成管控车间计划 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-12
 */
@Service
public class ProductionWorkstopPlanServiceImpl extends ServiceImpl<ProductionWorkstopPlanMapper, ProductionWorkstopPlan> implements IProductionWorkstopPlanService {

    @Autowired
    private ProductionWorkstopPlanMapper planMapper;

    @Autowired
    private ProductionUnitCostMapper unitCostMapper;

    @Autowired
    private ProduceLocationMapper locationMapper;

    @Override
    public List<ProductionPlanVo> getList(ProductionPlanParam planParam) {
        String orgId = planParam.getOrgId();
        String produceName = planParam.getProduceName();
        QueryWrapper<ProduceLocation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        List<ProduceLocation> locations = locationMapper.selectList(queryWrapper);
        List<ProductionPlanVo> list = new ArrayList<>();
        if (locations.size() != 0) {
            for (ProduceLocation location : locations) {
                ProductionPlanVo planVo = new ProductionPlanVo();
                planVo.setLocationName(location.getLocationName());

                QueryWrapper<ProductionWorkstopPlan> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.ge("create_time", DateUtil.beginOfYear(new Date()));
                queryWrapper1.eq("location_name", location.getId());
                queryWrapper1.eq("produce_name", produceName);
                queryWrapper1.select(" IFNULL(sum(plan_production),'0') planProduction,IFNULL(sum(actual_production),'0') actualProduction," +
                        "produce_name produceName");
                ProductionWorkstopPlan workstopPlan = planMapper.selectOne(queryWrapper1);
                planVo.setProduceName(workstopPlan.getProduceName());
                planVo.setActualProduction(workstopPlan.getActualProduction());
                planVo.setPlanProduction(workstopPlan.getPlanProduction());

                QueryWrapper<ProductionWorkstopPlan> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.ge("create_time", DateUtil.beginOfYear(new Date()));
                queryWrapper2.eq("location_name", location.getId());
                queryWrapper2.eq("produce_name", produceName);
                queryWrapper2.select(" convert(IFNULL(avg(unit_cost),'0'),decimal(10,2)) unitCost,convert(IFNULL(avg(avg_value),'0'),decimal(10,2)) avgValue," +
                        "create_time createTime,produce_name produceName");
                queryWrapper2.groupBy("DATE_FORMAT(create_time,'%Y-%m')");
                List<ProductionWorkstopPlan> plans = planMapper.selectList(queryWrapper2);
                List<ProductionWorkPlanVo> workPlanVos = new ArrayList<>();
                if (plans.size() != 0) {
                    for (ProductionWorkstopPlan plan : plans) {
                        ProductionWorkPlanVo vo = new ProductionWorkPlanVo();
                        vo.setAvgValue(plan.getAvgValue());
                        vo.setProduceName(plan.getProduceName());
                        vo.setCreateTime(plan.getCreateTime());
                        vo.setUnitCost(plan.getUnitCost());
                        workPlanVos.add(vo);
                    }
                }

                planVo.setWorkPlanVo(workPlanVos);
                list.add(planVo);
            }
        }

        return list;
    }

    @Override
    public ProductionWorkPlanTargetVo getTarget(ProductionTargetParam targetParam) {
        String orgId = targetParam.getOrgId();
        String time = targetParam.getTime();
        String year = time.substring(0, 4);
        String month = time.substring(5, 7);
        int last = Integer.parseInt(year) - 1;
        ProductionPlanVo2 vd = planMapper.getTarget(time + "-01 00:00:00", time + "-31 23:59:59",
                last + "-" + month + "-01 00:00:00", last + "-" + month + "-31 23:59:59", orgId, "饲料级VD3");
        ProductionPlanVo2 vd2 = planMapper.getTarget(time + "-01 00:00:00", time + "-31 23:59:59",
                last + "-" + month + "-01 00:00:00", last + "-" + month + "-31 23:59:59", orgId, "VD3结晶");
        ProductionPlanVo2 vd3 = planMapper.getTarget(time + "-01 00:00:00", time + "-31 23:59:59",
                last + "-" + month + "-01 00:00:00", last + "-" + month + "-31 23:59:59", orgId, "胆固醇");
        ProductionPlanVo2 vd4 = planMapper.getTarget(time + "-01 00:00:00", time + "-31 23:59:59",
                last + "-" + month + "-01 00:00:00", last + "-" + month + "-31 23:59:59", orgId, "25-羟基VD3");
        ProductionPlanVo2 vd5 = planMapper.getTarget(time + "-01 00:00:00", time + "-31 23:59:59",
                last + "-" + month + "-01 00:00:00", last + "-" + month + "-31 23:59:59", orgId, "维生素A微粒");

        ProductionWorkPlanTargetVo vo = new ProductionWorkPlanTargetVo();
        //饲料级VD3
        if (ObjectUtil.isNotEmpty(vd)) {
            String monthValue = vd.getMonthValue();
            String lastMonthValue = vd.getLastMonthValue();
            vo.setComplete(monthValue);
            if ("0".equals(lastMonthValue) || null == lastMonthValue) {
                vo.setCompleteRate("0");
            } else {
                double v = (Double.valueOf(month) - Double.valueOf(lastMonthValue)) / Double.valueOf(lastMonthValue);
                DecimalFormat def = new DecimalFormat("0.00");
                if (v > 1.00) {
                    vo.setCompleteRate("100");
                } else {
                    vo.setCompleteRate(def.format(v * 100));
                }
            }
        }
        //VD3结晶
        if (ObjectUtil.isNotEmpty(vd2)) {
            String monthValue = vd2.getMonthValue();
            String lastMonthValue = vd2.getLastMonthValue();
            vo.setVisitNum(monthValue);
            if ("0".equals(lastMonthValue) || null == lastMonthValue) {
                vo.setVisitNumRate("0");
            } else {
                double v = (Double.valueOf(month) - Double.valueOf(lastMonthValue)) / Double.valueOf(lastMonthValue);
                DecimalFormat def = new DecimalFormat("0.00");
                if (v > 1.00) {
                    vo.setVisitNumRate("100");
                } else {
                    vo.setVisitNumRate(def.format(v * 100));
                }
            }
        }
        //胆固醇
        if (ObjectUtil.isNotEmpty(vd3)) {
            String monthValue = vd3.getMonthValue();
            String lastMonthValue = vd3.getLastMonthValue();
            vo.setSaleMoney(monthValue);
            if ("0".equals(lastMonthValue) || null == lastMonthValue) {
                vo.setSaleMoneyRate("0");
            } else {
                double v = (Double.valueOf(month) - Double.valueOf(lastMonthValue)) / Double.valueOf(lastMonthValue);
                DecimalFormat def = new DecimalFormat("0.00");
                if (v > 1.00) {
                    vo.setSaleMoneyRate("100");
                } else {
                    vo.setSaleMoneyRate(def.format(v * 100));
                }
            }
        }
        //25-羟基VD3
        if (ObjectUtil.isNotEmpty(vd4)) {
            String monthValue = vd4.getMonthValue();
            String lastMonthValue = vd4.getLastMonthValue();
            vo.setSaleDeliverMoney(monthValue);
            if ("0".equals(lastMonthValue) || null == lastMonthValue) {
                vo.setSaleDeliverMoneyRate("0");
            } else {
                double v = (Double.valueOf(month) - Double.valueOf(lastMonthValue)) / Double.valueOf(lastMonthValue);
                DecimalFormat def = new DecimalFormat("0.00");
                if (v > 1.00) {
                    vo.setSaleDeliverMoneyRate("100");
                } else {
                    vo.setSaleDeliverMoneyRate(def.format(v * 100));
                }
            }
        }
        //维生素A微粒
        if (ObjectUtil.isNotEmpty(vd5)) {
            String monthValue = vd5.getMonthValue();
            String lastMonthValue = vd5.getLastMonthValue();
            vo.setReceiveMoney(monthValue);
            if ("0".equals(lastMonthValue) || null == lastMonthValue) {
                vo.setReceiveMoneyRate("0");
            } else {
                double v = (Double.valueOf(month) - Double.valueOf(lastMonthValue)) / Double.valueOf(lastMonthValue);
                DecimalFormat def = new DecimalFormat("0.00");
                if (v > 1.00) {
                    vo.setReceiveMoneyRate("100");
                } else {
                    vo.setReceiveMoneyRate(def.format(v * 100));
                }
            }
        }
        vo.setEnergyMoney("0");
        vo.setEnergyMoneyRate("0");
        return vo;
    }

    @Override
    public List<ProductionPlanDetailVo> getDetail(ProductionDetailParam detailParam) {
        String orgId = detailParam.getOrgId();
        Integer type = detailParam.getType();
        Integer dataType = detailParam.getDataType();
        List<ProductionPlanDetailVo> list = new ArrayList<>();
        QueryWrapper<ProductionWorkstopPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        queryWrapper.select(" convert(IFNULL(sum(actual_production),'0'),decimal(10,2)) actualProduction,create_time createTime");
        switch (dataType) {
            case 0:
                queryWrapper.like("produce_name", "饲料级VD3");
                break;
            case 1:
                queryWrapper.like("produce_name", "VD3结晶");
                break;
            case 2:
                queryWrapper.like("produce_name", "胆固醇");
                break;
        }

        if (0 == type) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%y-%m')");
            List<ProductionWorkstopPlan> plans = planMapper.selectList(queryWrapper);
            for (ProductionWorkstopPlan plan : plans) {
                ProductionPlanDetailVo vo = new ProductionPlanDetailVo();
                vo.setValues(plan.getActualProduction());
                vo.setCreateTime(sdf.format(plan.getCreateTime()));
                list.add(vo);
            }
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%y')");
            List<ProductionWorkstopPlan> plans = planMapper.selectList(queryWrapper);
            for (ProductionWorkstopPlan plan : plans) {
                ProductionPlanDetailVo vo = new ProductionPlanDetailVo();
                vo.setValues(plan.getActualProduction());
                vo.setCreateTime(sdf.format(plan.getCreateTime()));
                list.add(vo);
            }
        }
        return list;
    }

    @Override
    public List<ProductionVo> listScreen(ProductionScreenParam screenParam) {
        String orgId = screenParam.getOrgId();
        String produceName = screenParam.getProduceName();
        QueryWrapper<ProductionWorkstopPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        if (StringUtils.isNotBlank(produceName)) {
            queryWrapper.like("produce_name", produceName);
        }
        queryWrapper.select(" convert(IFNULL(sum(actual_production),'0'),decimal(10,2)) actualProduction," +
                "convert(IFNULL(sum(plan_production),'0'),decimal(10,2)) planProduction,create_time createTime");
        queryWrapper.groupBy("DATE_FORMAT(create_time,'%y-%m')");
        List<ProductionWorkstopPlan> plans = planMapper.selectList(queryWrapper);
        List<ProductionVo> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        if (plans.size() != 0) {
            for (ProductionWorkstopPlan plan : plans) {
                ProductionVo vo = new ProductionVo();
                vo.setActualProduction(plan.getActualProduction());
                vo.setPlanProduction(plan.getPlanProduction());
                vo.setCreateTime(sdf.format(plan.getCreateTime()));
                list.add(vo);
            }
        }
        return list;
    }

    @Override
    public IPage<ProductionWorkstopPlan> getTop(ProductionPageParam pageParam) {
        String orgId = pageParam.getOrgId();
        Integer pageNum = pageParam.getPageNum();
        Integer pageSize = pageParam.getPageSize();
        Page<ProductionWorkstopPlan> page = new Page<>(pageNum, pageSize);
        QueryWrapper<ProductionWorkstopPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId).groupBy("location_name");
        IPage<ProductionWorkstopPlan> planMapperTop = planMapper.getTop(queryWrapper, page);
        List<ProductionWorkstopPlan> records = planMapperTop.getRecords();
        if (records.size() != 0) {
            List<ProductionWorkstopPlan> plans = jsonArraySort(records, true);
            for (int i = 0; i < pageSize; i++) {
                ProductionWorkstopPlan workstopPlan = plans.get(i);
                workstopPlan.setId((pageNum-1) *pageSize + i+ 1 );
            }
            planMapperTop.setRecords(plans);
        }
        return planMapperTop;
    }
    @Autowired
    private ProduceLocationMapper produceLocationMapper;

    @Override
    public List<ProductionLocationVo> listLocation(ProductionVoParam voParam) {
        String orgId = voParam.getOrgId();
        List<ProduceLocation> produceLocations = produceLocationMapper.selectList(new QueryWrapper<ProduceLocation>().eq(StringUtils.isNotBlank(orgId), "org_id", orgId).orderByAsc("location_id"));
       List<ProductionLocationVo> list =new ArrayList();
        for (ProduceLocation produceLocation : produceLocations) {
            ProductionLocationVo productionLocationVo = new ProductionLocationVo();
            productionLocationVo.setLocationId(produceLocation.getLocationId() +"");
            productionLocationVo.setLocationName(produceLocation.getLocationName());
            productionLocationVo.setOrgId(produceLocation.getOrgId());
            list.add(productionLocationVo);
        }

//        QueryWrapper<ProductionWorkstopPlan> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId).groupBy("location_id");
//        List<ProductionWorkstopPlan> workstopPlans = planMapper.selectList(queryWrapper);
//        List<ProductionLocationVo> list = new ArrayList<>();
//        for (ProductionWorkstopPlan workstopPlan : workstopPlans) {
//            ProductionLocationVo vo = new ProductionLocationVo();
//            vo.setLocationId(workstopPlan.getLocationId());
//            vo.setLocationName(workstopPlan.getLocationName());
//            vo.setOrgId(workstopPlan.getOrgId());
//            list.add(vo);
//        }
        return list;
    }

    @Override
    public List<ProductionNameVo> listProductionName(ProductionVoParam voParam) {
        List<ProductionNameVo> list = new ArrayList<>();
        ProductionNameVo vo = new ProductionNameVo();
        vo.setProduceName("饲料级VD3");
        list.add(vo);
        ProductionNameVo vo2 = new ProductionNameVo();
        vo2.setProduceName("VD3结晶");
        list.add(vo2);
        ProductionNameVo vo3 = new ProductionNameVo();
        vo3.setProduceName("胆固醇");
        list.add(vo3);
        ProductionNameVo vo4 = new ProductionNameVo();
        vo4.setProduceName("25-羟基D3");
        list.add(vo4);
        ProductionNameVo vo5 = new ProductionNameVo();
        vo5.setProduceName("维生素A微粒");
        list.add(vo5);
        return list;
    }

    /*数组排序*/
    public static List<ProductionWorkstopPlan> jsonArraySort(List<ProductionWorkstopPlan> jsonArr, boolean is_desc) {
        //存放排序结果json数组
        List<ProductionWorkstopPlan> salesmanList = new ArrayList<>();
        //用于排序的list
        List<ProductionWorkstopPlan> list = new ArrayList<>();
        //将参数json数组每一项取出，放入list

        for (int i = 0; i <jsonArr.size() ; i++) {
            list.add(jsonArr.get(i));
        }

        //快速排序，重写compare方法，完成按指定字段比较，完成排序
        Collections.sort(list, new Comparator<ProductionWorkstopPlan>() {
            @Override
            public int compare(ProductionWorkstopPlan o1, ProductionWorkstopPlan o2) {
                //如果用String接会导致一位数和两位数混合比对的时候不能准确比出来，要用int类型接
                //String valA = new String();
                //String valB = new String();
                Float valA = 0.00f;
                Float valB = 0.00f;
                try {
                    valA = Float.parseFloat(o1.getActualProduction());
                    valB = Float.parseFloat(o2.getActualProduction());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //是升序还是降序
                if (is_desc) {
                    return -valA.compareTo(valB);
                } else {
                    return -valB.compareTo(valA);
                }

            }
        });
        //将排序后结果放入结果jsonArray
        for (int i = 0; i < jsonArr.size(); i++) {
            salesmanList.add(list.get(i));
        }

        return salesmanList;
    }
}
