package com.fjhx.form.service.impl;

import com.fjhx.account.entity.account.po.AccountRunningWater;
import com.fjhx.account.service.account.AccountPaymentService;
import com.fjhx.account.service.account.AccountRunningWaterService;
import com.fjhx.common.enums.FlowStatusEnum1;
import com.fjhx.customer.service.customer.CustomerService;
import com.fjhx.flow.entity.flow.po.FlowExample;
import com.fjhx.flow.service.flow.FlowExampleService;
import com.fjhx.form.mapper.StatisticsMapper;
import com.fjhx.form.service.StatisticsService;
import com.fjhx.mes.entity.production.po.ProductionOrder;
import com.fjhx.mes.service.production.ProduceOrderService;
import com.fjhx.purchase.service.subscribe.SubscribeDetailService;
import com.fjhx.sale.entity.contract.po.Contract;
import com.fjhx.sale.entity.contract.vo.ContractVo;
import com.fjhx.sale.entity.purchase.vo.EhsdPurchaseVo;
import com.fjhx.sale.entity.sale.po.SaleQuotation;
import com.fjhx.sale.mapper.contract.ContractProductMapper;
import com.fjhx.sale.mapper.sample.SampleMapper;
import com.fjhx.sale.service.sale.SaleQuotationService;
import com.fjhx.wms.entity.stock.dto.StockSelectDto;
import com.fjhx.wms.entity.stock.dto.StockWaitDetailsSelectDto;
import com.fjhx.wms.service.stock.StockService;
import com.fjhx.wms.service.stock.StockWaitDetailsService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.system.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class StatisticsServiceImpl implements StatisticsService {
    @Autowired
    private FlowExampleService flowExampleService;
    @Autowired
    private AccountRunningWaterService accountRunningWaterService;
    @Autowired
    private SubscribeDetailService subscribeDetailService;
    @Autowired
    private SampleMapper sampleMapper;
    @Autowired
    private ContractProductMapper contractProductMapper;
    @Autowired
    private AccountPaymentService accountPaymentService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private StatisticsMapper statisticsMapper;
    @Autowired
    private SaleQuotationService saleQuotationService;
    @Autowired
    private ProduceOrderService produceOrderService;
    @Autowired
    private StockService stockService;
    @Autowired
    private StockWaitDetailsService stockWaitDetailsService;

    /**
     * 工作统计
     */
    @Override
    public Map<String, Long> workStatistics() {
        Long userId = SecurityUtils.getUserId();

        //权限过滤：子公司看自己的,总公司看全部
        boolean flag;//是否是总公司
        Long companyId = SecurityUtils.getCompanyId();
        if (Objects.equals(companyId, 100L)) {
            //总公司直接忽略归属公司条件
            companyId = null;
            flag = true;
        } else {
            flag = false;
        }
        Long finalCompanyId = companyId;//isEstimate

        //统计待审批数据
        long waitFlowCount = flowExampleService.count(q -> q.in(FlowExample::getStatus, 1, 0).eq(FlowExample::getHandleUserId, userId));
        //待报价 总公司对内报价单 子公司 报价评估
        long waitQuotationCount = saleQuotationService.count(q -> q
                .ne(!flag, SaleQuotation::getStatus, FlowStatusEnum1.DRAFT.getKey())//子公司
                .ne(SaleQuotation::getStatus, FlowStatusEnum1.UPDATE.getKey())//总公司
                .eq(!flag, SaleQuotation::getCompanyId, finalCompanyId)
        );
        //待投产
        long waitProduceCount = produceOrderService.count(q -> q
                .isNull(ProductionOrder::getProduceTime)
                .eq(!flag, ProductionOrder::getCompanyId, finalCompanyId)
        );
        //待入库
        StockWaitDetailsSelectDto stockWaitDetailsSelectDto = new StockWaitDetailsSelectDto();
        stockWaitDetailsSelectDto.setType(1);
        long waitInStockCount = stockWaitDetailsService.getPage(stockWaitDetailsSelectDto).getTotal();
        //待出库
        StockWaitDetailsSelectDto stockWaitDetailsSelectDto1 = new StockWaitDetailsSelectDto();
        stockWaitDetailsSelectDto1.setType(2);
        long waitOutStockCount = stockWaitDetailsService.getPage(stockWaitDetailsSelectDto1).getTotal();
        //到账认领待认领计数-总公司
        long waitClaimCount = accountRunningWaterService.count(q -> q
                .eq(AccountRunningWater::getReceived, 10)
                .eq(AccountRunningWater::getIsClaim, 0)
                .eq(!flag, AccountRunningWater::getCompanyId, finalCompanyId)
        );
        //库存预警-子公司看
        long stockWarnCount = stockService.stockWarningPage(new StockSelectDto()).getTotal();

        //总数
        long sumCount = waitFlowCount + waitQuotationCount + waitProduceCount + waitInStockCount + waitOutStockCount;

        if (flag) {
            sumCount += waitClaimCount;//总公司待认领
        } else {
            sumCount += stockWarnCount;//子公司库存预警
        }


        //输出结果
        Map<String, Long> map = new HashMap<>();
        map.put("waitFlowCount", waitFlowCount);
        map.put("waitQuotationCount", waitQuotationCount);
        map.put("waitProduceCount", waitProduceCount);
        map.put("waitInStockCount", waitInStockCount);
        map.put("waitOutStockCount", waitOutStockCount);
        map.put("waitClaimCount", waitClaimCount);
        map.put("stockWarnCount", stockWarnCount);
        map.put("sumCount", sumCount);


//        //到账认领计数
//        long claimCount = accountRunningWaterService.count(q -> q.eq(AccountRunningWater::getReceived, 10).ne(AccountRunningWater::getIsClaim, 1));
//        //待采购数量
//        long waitPurchaseCount = subscribeDetailService.count(q -> q.in(SubscribeDetail::getStatus, Arrays.asList(15, 30)));
//        //样品交接单
//        Page<Object> page = new Page<>();
//        page.setCurrent(1);
//        page.setSize(1);
//        IWrapper<Sample> wrapper = IWrapper.getWrapper();
//        wrapper.eq("t2.`status`", 30);
//        wrapper.ge("t1.expend_quantity", 0);
//        long sampleHandoverCount = sampleMapper.sampleHandoverList(page, wrapper).getTotal();
//        //合同样品单
//        IWrapper<ContractProduct> wrapper1 = IWrapper.getWrapper();
//        wrapper.eq("t2.`status`", 30);
//        wrapper.ge("t1.expend_quantity", 0);
//        long contractHandoverCount = contractProductMapper.contractHandoverPage(page, wrapper1).getTotal();
//        //待打款
//        long waitAccountPayCount = accountPaymentService.count(q -> q.ne(AccountPayment::getStatus, 10));

        //总数
//        long sumCount = unreadMailCount + waitFlowCount + claimCount + waitPurchaseCount + sampleHandoverCount + contractHandoverCount + waitAccountPayCount;


//        map.put("unreadMailCount", unreadMailCount);
//        map.put("waitFlowCount", waitFlowCount);
//        map.put("claimCount", claimCount);
//        map.put("waitPurchaseCount", waitPurchaseCount);
//        map.put("sampleHandoverCount", sampleHandoverCount);
//        map.put("contractHandoverCount", contractHandoverCount);
//        map.put("waitAccountPayCount", waitAccountPayCount);
//        map.put("sumCount", sumCount);


        return map;
    }

    @Override
    public List<ContractVo> getRecentContractShipmentList() {
        IWrapper<Object> wrapper = IWrapper.getWrapper();

        //不是业务员看所有


        SysUser sysUser = UserUtil.getUserInfo();
        if (StringUtils.isNotEmpty(sysUser.getUserCode())) {
            //是业务员
            List<Long> authIdList = customerService.getAuthIdList();
            if (authIdList.size() == 0) {
                return new ArrayList<>();
            }
            wrapper.in("t1", Contract::getBuyCorporationId, authIdList);
        }
        wrapper.ge("DATEDIFF(t1.shipment_time,NOW())", 0);
        wrapper.le("DATEDIFF(t1.shipment_time,NOW())", 7);
        wrapper.apply("t1.sumPackQuantity<t1.quantity");
        List<ContractVo> contractSaitShipmentList = statisticsMapper.getRecentContractShipmentList(wrapper);
        return contractSaitShipmentList;
    }

    @Override
    public List<EhsdPurchaseVo> getRecentPurchaseArrivalList() {
        IWrapper<Object> wrapper = IWrapper.getWrapper();
        wrapper.ge("DATEDIFF(pa.arrival_time,NOW())", 0);
        wrapper.le("DATEDIFF(pa.arrival_time,NOW())", 7);
        wrapper.eq("p.status", 30);
        List<EhsdPurchaseVo> contractSaitShipmentList = statisticsMapper.getRecentPurchaseArrivalList(wrapper);
        return contractSaitShipmentList;
    }
}
