package cn.superdesk.uniorder.dubbo.provider.operationCenter.accounting;

import cn.superdesk.data.extract.enums.opCenter.OpCenterGoodsTypeEnum;
import cn.superdesk.data.extract.enums.opCenter.OpCenterOrderBizTypeEnum;
import cn.superdesk.data.extract.enums.opCenter.OpCenterTransactionStatusEnum;
import cn.superdesk.uniorder.common.enums.accounting.order.ImportAccountingOrderExcelEnum;
import cn.superdesk.uniorder.common.enums.common.CommonAccountingStateEnum;
import cn.superdesk.uniorder.common.enums.common.CommonSettlementStateEnum;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.dao.entity.sys.notify.SysNotify;
import cn.superdesk.uniorder.dto.param.operationCenter.order.OperationCenterOrderParam;
import cn.superdesk.uniorder.dto.param.organisation.SysSupplierQueryParam;
import cn.superdesk.uniorder.dto.vo.operationCenter.accounting.UnifiedAccountingOrderInfoVo;
import cn.superdesk.uniorder.dto.vo.operationCenter.customer.OpCenterCustomerOperatorOrgVo;
import cn.superdesk.uniorder.dto.vo.operationCenter.order.OperationCenterOrderFormVo;
import cn.superdesk.uniorder.dto.vo.sys.SysSupplierVo;
import cn.superdesk.uniorder.dto.vo.sys.sysPlatformVo;
import cn.superdesk.uniorder.dubbo.facade.operationCenter.accounting.DubboUnifiedAccountingService;
import cn.superdesk.uniorder.dubbo.facade.sys.notify.DubboSysNotifyService;
import cn.superdesk.uniorder.dubbo.provider.operationCenter.order.DubboOperationCenterOrderServiceImpl;
import cn.superdesk.uniorder.service.operationCenter.OperationCenterCustomerService;
import cn.superdesk.uniorder.service.operationCenter.UnifiedAccountingOrderCreditService;
import cn.superdesk.uniorder.service.operationCenter.UnifiedAccountingOrderGoodsService;
import cn.superdesk.uniorder.service.organisation.SysEnterpriseService;
import cn.superdesk.uniorder.service.organisation.SysSupplierService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @Author : zx
 * @Create : 2023/4/27 15:46
 * Description :
 */
@Slf4j
@Service(version = "1.0.1", retries = -1, timeout = 10000)
@RequiredArgsConstructor
public class UnifiedAccountingDubboServiceImpl implements DubboUnifiedAccountingService {
    @Reference(version = "1.0.0", timeout = 10000, retries = -1)
    private DubboSysNotifyService dubboSysNotifyService;

    private final UnifiedAccountingOrderGoodsService unifiedAccountingOrderGoodsService;

    private final UnifiedAccountingOrderCreditService unifiedAccountingOrderCreditService;

    private final OperationCenterCustomerService operationCenterCustomerService;


    private final SysEnterpriseService sysEnterpriseService;


    private final  SysSupplierService unifiedSupplierService;

    @Override
    public R<List<UnifiedAccountingOrderInfoVo>> getOrderGoodsList(OperationCenterOrderParam param) {
        //将参数进行转化
        ConversionParameters(param);


        PageHelper.startPage(param.getPageNumber(), param.getPageSize());
        //查询列表
        List<UnifiedAccountingOrderInfoVo> result = unifiedAccountingOrderGoodsService.getOrderGoodsList(param);
        PageInfo<UnifiedAccountingOrderInfoVo> page = new PageInfo<>(result);



        param.setFlag(1);//查询统计
        List<UnifiedAccountingOrderInfoVo> count = unifiedAccountingOrderGoodsService.getOrderGoodsList(param);
        Map<String, Object> headData = new HashMap<>();


        headData.put("countRows",count.get(0).getCountRows());
        headData.put("goodsOrderAmountCount",count.get(0).getGoodsOrderAmountCount()==null?0.00:count.get(0).getGoodsOrderAmountCount());
        headData.put("settlementAmountCount",count.get(0).getSettlementAmountCount()==null?0.00:count.get(0).getSettlementAmountCount());


        result = result.stream()
                .map(vo -> {
                    //订单类型
                    vo.setOrderBizTypeDesc(null != vo.getOrderBizTypeId()? OpCenterOrderBizTypeEnum.getDescByCode(vo.getOrderBizTypeId()):"");
                   //商品类型
                    vo.setGoodsTypeDesc(null != vo.getGoodsTypeId()? OpCenterGoodsTypeEnum.getDescByCode(vo.getGoodsTypeId()):"");
                    //交易状态
                    vo.setTransactionStatusDesc(null != vo.getTransactionStatusId()? OpCenterTransactionStatusEnum.getDescByCode(vo.getTransactionStatusId()):"");
                    //对账状态
                    vo.setAccountingStatusDesc(null !=vo.getAccountingStatus()? CommonAccountingStateEnum.getDesc(vo.getAccountingStatus()):"");
                    return vo;
                }).collect(Collectors.toList());


        return new R<>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), result,headData);

    }

    @Override
    public R<List<UnifiedAccountingOrderInfoVo>> getOrderCreditList(OperationCenterOrderParam param) {
        //将参数进行转化

        ConversionParameters(param);



        PageHelper.startPage(param.getPageNumber(), param.getPageSize());

        List<UnifiedAccountingOrderInfoVo> result = unifiedAccountingOrderCreditService.getOrderCreditList(param);

        PageInfo<UnifiedAccountingOrderInfoVo> page = new PageInfo<>(result);

        param.setFlag(1);//查询统计
        List<UnifiedAccountingOrderInfoVo> count = unifiedAccountingOrderCreditService.getOrderCreditList(param);


        Map<String, Object> headData = new HashMap<>();


        headData.put("countRows",count.get(0).getCountRows());
        headData.put("orderAmount",count.get(0).getOrderAmount()==null?0.00:count.get(0).getOrderAmount());

        result = result.stream()
                .map(vo -> {
                    //订单类型
                    vo.setOrderBizTypeDesc(null != vo.getOrderBizTypeId()? OpCenterOrderBizTypeEnum.getDescByCode(vo.getOrderBizTypeId()):"");
                    //商品类型
                    vo.setGoodsTypeDesc(null != vo.getGoodsTypeId()? OpCenterGoodsTypeEnum.getDescByCode(vo.getGoodsTypeId()):"");
                    //交易状态
                    vo.setTransactionStatusDesc(null != vo.getTransactionStatusId()? OpCenterTransactionStatusEnum.getDescByCode(vo.getTransactionStatusId()):"");
                    //对账状态
                    vo.setAccountingStatusDesc(null !=vo.getAccountingStatus()? CommonAccountingStateEnum.getDesc(vo.getAccountingStatus()):"");
                    //是否参与结算
                    vo.setIsSettlementDesc(null !=vo.getIsSettlement()? CommonSettlementStateEnum.getDesc(vo.getIsSettlement()):"");
                    return vo;
                }).collect(Collectors.toList());

        return new R<>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), result,headData);
    }

    @Override
    public R<String> importExcelOrderList(OperationCenterOrderParam param, LoginSysUser loginSysUser) {
        //将参数进行转化

        ConversionParameters(param);


        CompletableFuture.runAsync(() -> {
            try {
               SysNotify sysNotify = unifiedAccountingOrderGoodsService.exportExcelOrder(param);
                // 通知
                dubboSysNotifyService.notifyExportExcelScoreOrderReconciliationNotYet(sysNotify, loginSysUser);
            } catch (Exception e) {
                log.error("导出运营商结算报表 importExcelOrderList {} -> 执行 异常:{}", AnJsonUtils.toJson(param), e);
            }
        });


        return new R<>("200","导出任务已经接收,正在处理中...",true);


    }



    /**
     * 将入参进行转化
     */
    private OperationCenterOrderParam ConversionParameters(OperationCenterOrderParam param) {
        //将参数进行转化

        //新增客户-运营商-项目-企业查查询项-判断是否选中
        if (StringUtils.isNotBlank(param.getCustomerId())) {

            //直接通过客户id 查询运营商-项目关联关系
            Map<String, Object> conditions = new HashMap<>();
            conditions.put("customerId", param.getCustomerId());
            if (StringUtils.isNotBlank(param.getOperatorIds())) {
                conditions.put("operatorIds", param.getOperatorIds());
            }

            //根据客户 & 运营商 ->关联关系  存在关联全部项目
            List<OpCenterCustomerOperatorOrgVo> operatorOrgList = operationCenterCustomerService.getLinkOperatorAndOrg(conditions);


            param.setOpCenterCustomerOperatorOrgList(operatorOrgList);


            //项目的直接用子查询来限制

            //企业单独塞查询项-根据企业id查询 业务项目id 和 业务企业id--企业需要用平台编码来区分
            if (StringUtils.isNotBlank(param.getEnterpriseIds())) {
                List<sysPlatformVo> sysPlatformVos= sysEnterpriseService.getvirtBizIdById(param.getEnterpriseIds());
                param.setSysPlatformVirList(sysPlatformVos);

            }


        }

        if (StringUtils.isNotBlank(param.getBizPlatformCode())) {
            //
            String bizPlatFormCode = Arrays.stream(param.getBizPlatformCode().split(",")).map(x -> "'" + x + "'").collect(Collectors.joining(","));
            param.setBizPlatformCode(bizPlatFormCode);
        }


        if (StringUtils.isNotBlank(param.getSupplierIds())) {
            //通过供应商id 查询供应商 所属平台 和 业务方供应商id
            SysSupplierQueryParam queryParam = new SysSupplierQueryParam();
            queryParam.setSupplierIds(param.getSupplierIds());
            List<SysSupplierVo> supplierList = unifiedSupplierService.findSupplierList(queryParam);
            param.setSupplierList(supplierList);
        }
        return param;
    }


}
