package com.gree.mall.miniapp.logic.material.withdrawal;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.miniapp.bean.material.settlement.SettlementAmountBean;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.enums.PayTypeEnum;
import com.gree.mall.miniapp.enums.SettlementStatusEnum;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.plus.entity.*;
import com.gree.mall.miniapp.plus.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class WithdrawalLogic {

    private final CommonLogic commonLogic;
    private final WithdrawalOrderService withdrawalOrderService;
    private final WithdrawalOrderItemService withdrawalOrderItemService;
    private final WorkerBankService workerBankService;
    private final SettlementOrderService settlementOrderService;
    private final SettlementOrderItemService settlementOrderItemService;
    private final WebsitUserService websitUserService;
    private final AdminWebsitService adminWebsitService;
    /**
     * 申请提现
     * @param workerBankId
     */
    @Transactional
    public void add(String workerBankId){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        WorkerBank workerBank = workerBankService.getById(workerBankId);
        if(workerBank == null){
            throw new RemoteServiceException("银行卡不存在");
        }
        String workerId = workerBank.getWorkerId();
        //所有网点
        List<WebsitUser> websitUsers = websitUserService.lambdaQuery().eq(WebsitUser::getUserId, workerId).list();
        if(CollectionUtils.isEmpty(websitUsers)){
            throw new RemoteServiceException("您暂无网点");
        }
        //所有结算单
        List<SettlementOrder> list = settlementOrderService.lambdaQuery()
                .eq(SettlementOrder::getStatus,SettlementStatusEnum.WAIT_ING.getKey())
                .eq(SettlementOrder::getPayType, PayTypeEnum.WECHAT.getKey())
                .eq(SettlementOrder::getWorkerId, workerId).list();

        if(CollectionUtils.isEmpty(list)){
            throw new RemoteServiceException("暂无可提现的单");
        }
        List<String> settlementOrderIds = list.stream().map(SettlementOrder::getSettlementOrderId).collect(Collectors.toList());
        //所有结算明细
        List<SettlementOrderItem> settlementOrderItems = settlementOrderItemService.lambdaQuery().in(SettlementOrderItem::getSettlementOrderId, settlementOrderIds).list();

        List<WithdrawalOrder> withdrawalOrders = new ArrayList<>();
        List<WithdrawalOrderItem> withdrawalOrderItems = new ArrayList<>();

        //将结算单变更为提现中
        settlementOrderService.lambdaUpdate()
                .set(SettlementOrder::getStatus,SettlementStatusEnum.ING.getKey())
                .in(SettlementOrder::getSettlementOrderId,settlementOrderIds).update();

        //可提现
        //for(WebsitUser websitUser : websitUsers) {

            //查询所有未提现过的
            SettlementAmountBean settlementAmountBean = this.totalAmount(workerBank.getWorkerId(),null, list);
            BigDecimal ktxAmount = settlementAmountBean.getKtx();
            if(ktxAmount == null || ktxAmount.doubleValue() == 0){
                return;
            }

            //AdminWebsit adminWebsit = adminWebsitService.getById(websitUser.getWebsitId());

            List<SettlementOrder> ktxList = list.stream()
                    //.filter(v ->StringUtils.equals(v.getWebsitId(),websitUser.getWebsitId()))
                    .collect(Collectors.toList());

//            List<SettlementOrderItem> ktxItemList = settlementOrderItems.stream()
//                    .filter(v -> StringUtils.equals(v.getWebsitId(), websitUser.getWebsitId())).collect(Collectors.toList());

            //表头
            WithdrawalOrder withdrawalOrder = new WithdrawalOrder();
            withdrawalOrder.setId(IdWorker.getIdStr());
            withdrawalOrder.setCompanyWechatId(currentCompanyWechat.getCompanyWechatId());
            withdrawalOrder.setCompanyWechatName(currentCompanyWechat.getCurrentCompanyName());
//            withdrawalOrder.setWebsitId(websitUser.getWebsitId());
//            withdrawalOrder.setWebsitName(adminWebsit.getName());
            withdrawalOrder.setWorkerId(workerId);
            withdrawalOrder.setWorkerName(currentCompanyWechat.getUser().getNickName());
            withdrawalOrder.setWorkerMobile(currentCompanyWechat.getUser().getMobile());
            withdrawalOrder.setAmount(ktxAmount);
            withdrawalOrder.setBank(workerBank.getBank());
            withdrawalOrder.setBankNo(workerBank.getBankNo());
            withdrawalOrder.setSubBank(workerBank.getSubBank());
            withdrawalOrder.setBankUserName(workerBank.getBankUserName());
            withdrawalOrder.setIdcard(workerBank.getIdcard());
            withdrawalOrder.setCreateTime(new Date());
            withdrawalOrder.setCreateBy(currentCompanyWechat.getUser().getNickName());
            withdrawalOrders.add(withdrawalOrder);

            //表体
            for(SettlementOrder settlementOrder : ktxList){
                WithdrawalOrderItem item = new WithdrawalOrderItem();
                item.setWithdrawalOrderId(withdrawalOrder.getId());
                item.setOrderId(settlementOrder.getSettlementOrderId());
                item.setGoodsType(settlementOrder.getGoodsType());
                item.setNum(settlementOrder.getNum());
                //item.setPrice(settlementOrder.getGoodsAmount());
                item.setTotalPrice(settlementOrder.getTotalAmount());
                item.setSettlementType(settlementOrder.getSettlementType());
                item.setWorkerAmount(settlementOrder.getWorkerAmount());
                item.setWebsitAmount(settlementOrder.getWebsitAmount());
                item.setCreateTime(new Date());
                item.setCreateBy(currentCompanyWechat.getUser().getNickName());
                item.setWorkerId(withdrawalOrder.getWorkerId());
                item.setWorkerName(withdrawalOrder.getWorkerName());
                item.setWorkerMobile(withdrawalOrder.getWorkerMobile());
//                item.setWebsitId(withdrawalOrder.getWebsitId());
//                item.setWebsitName(withdrawalOrder.getWebsitName());
                withdrawalOrderItems.add(item);
            }
        //}
        if(CollectionUtils.isEmpty(withdrawalOrders)){
            throw new RemoteServiceException("暂无可提现的金额");
        }
        withdrawalOrderService.saveBatch(withdrawalOrders);
        withdrawalOrderItemService.saveBatch(withdrawalOrderItems);
    }


    /**
     * 提现订单
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<WithdrawalOrder> list(String startTime,String endTime,Integer pageNum,Integer pageSize){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        Page<WithdrawalOrder> page = withdrawalOrderService.lambdaQuery()
                .between(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime),WithdrawalOrder::getCreateTime,startTime,endTime)
                .eq(WithdrawalOrder::getWorkerId,currentCompanyWechat.getUser().getWorkerNumber())
                .orderByDesc(WithdrawalOrder::getCreateTime).page(new Page<>(pageNum, pageSize));
        return page;
    }

    /**
     * 提现订单明细
     */
    public IPage<WithdrawalOrderItem> listDetail(String id,Integer pageNum,Integer pageSize){
        Page<WithdrawalOrderItem> page = withdrawalOrderItemService.lambdaQuery()
                .eq(WithdrawalOrderItem::getWithdrawalOrderId,id)
                .orderByDesc(WithdrawalOrderItem::getCreateTime).page(new Page<>(pageNum, pageSize));
        return page;
    }



    /**
     * 提现详情
     * @param id
     * @return
     */
    public WithdrawalOrder detail(String id){
        return withdrawalOrderService.getById(id);
    }

    public SettlementAmountBean totalAmount(){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        return this.totalAmount(currentCompanyWechat.getUser().getWorkerNumber(),null,null);
    }

    /**
     * 结算金额统计
     * @param workerId
     * @return
     */
    public SettlementAmountBean totalAmount(String workerId,String websitId,List<SettlementOrder> list){

        if(CollectionUtils.isEmpty(list)) {
            list = settlementOrderService.lambdaQuery()
                    //.eq(SettlementOrder::getStatus, SettlementStatusEnum.WAIT_ING.getKey())
                    .eq(SettlementOrder::getPayType, PayTypeEnum.WECHAT.getKey())
                    .eq(SettlementOrder::getWorkerId, workerId).list();
        }
        if(StringUtils.isNotBlank(websitId)){
            list = list.stream().filter(v -> StringUtils.equals(websitId,v.getWebsitId())).collect(Collectors.toList());
        }
        //可提现
        BigDecimal ktx = list.stream()
                .filter(v -> StringUtils.equals(v.getStatus(),SettlementStatusEnum.WAIT_ING.getKey()))
                .map(SettlementOrder::getWorkerAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);

        //提现中
        BigDecimal txz = list.stream()
                .filter(v -> StringUtils.equals(v.getStatus(),SettlementStatusEnum.ING.getKey()))
                .map(SettlementOrder::getWorkerAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);

        List<String> stringsDjs = new ArrayList<>();

        stringsDjs.add("WAIT");
        stringsDjs.add("YC");


        //待结算
        BigDecimal djs = list.stream()
                .filter(v -> stringsDjs.contains(v.getStatus()))
                .map(SettlementOrder::getWorkerAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);

        List<String> strings = new ArrayList<>();

        strings.add("OK");
        strings.add("LINE");

        //已到账
        BigDecimal ydz = list.stream()
                .filter(v -> strings.contains(v.getStatus()))
                .map(SettlementOrder::getWorkerAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);

        SettlementAmountBean bean = new SettlementAmountBean();
        bean.setKtx(ktx);
        bean.setTxz(txz);
        bean.setDjs(djs);
        bean.setYjs(ydz);
        bean.setZsy(djs.add(ydz));
        return bean;
    }

}
