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

import cn.hutool.core.date.DateUtil;
import cn.superdesk.data.extract.enums.opCenter.*;
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.operationCenter.OperationCenterOrder;
import cn.superdesk.uniorder.dao.entity.sys.notify.SysNotify;
import cn.superdesk.uniorder.dto.param.operationCenter.base.OperationCenterParam;
import cn.superdesk.uniorder.dto.param.operationCenter.operators.OperationCenterOperatorsParam;
import cn.superdesk.uniorder.dto.param.operationCenter.order.OperationCenterOrderParam;
import cn.superdesk.uniorder.dto.vo.operationCenter.base.OperationCenterVo;
import cn.superdesk.uniorder.dto.vo.operationCenter.customer.OpCenterCustomerOperatorOrgVo;
import cn.superdesk.uniorder.dto.vo.operationCenter.operators.OperationCenterOperatorsVo;
import cn.superdesk.uniorder.dto.vo.operationCenter.order.*;
import cn.superdesk.uniorder.dto.vo.sys.sysPlatformVo;
import cn.superdesk.uniorder.dubbo.facade.operationCenter.order.DubboOperationCenterOrderService;
import cn.superdesk.uniorder.dubbo.facade.sys.notify.DubboSysNotifyService;
import cn.superdesk.uniorder.service.operationCenter.*;
import cn.superdesk.uniorder.service.organisation.SysEnterpriseService;
import cn.superdesk.uniorder.service.organisation.SysOrganizationService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * @Author : zx
 * @Create : 2023/3/24 16:34
 * Description : 运营中心 订单管理页面 接口
 */
@Slf4j
@Service(version = "1.0.0", retries = -1, timeout = 10000)
public class DubboOperationCenterOrderServiceImpl implements DubboOperationCenterOrderService {
    @Reference(version = "1.0.0", timeout = 10000, retries = -1)
    private DubboSysNotifyService dubboSysNotifyService;


    @Autowired
    private OperationCenterOrderGoodsService operationCenterOrderGoodsService;

    @Autowired
    private OperationCenterOrderService operationCenterOrderService;


    @Autowired
    private SysEnterpriseService  sysEnterpriseService;

    @Autowired
    private OperationCenterCustomerService operationCenterCustomerService;

    @Autowired
    private OperationCenterOrderTransactionLogService operationCenterOrderTransactionLogService;


    @Override
    public R<OperationCenterOrderFormVo> list(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);

            //未查到关联关系
            if (CollectionUtils.isEmpty(operatorOrgList)) {
                return new R<>(new OperationCenterOrderFormVo());
            }

            param.setOpCenterCustomerOperatorOrgList(operatorOrgList);


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

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

            }




        }








/**      运营中心-1.00
        //运营商id不为空时，要将运营中心运营商id转化为业务运营商id -- 以及所属平台code 可以是多个23,24
        if (StringUtils.isNotBlank(param.getOperatorId())) {

            OperationCenterOperatorsParam operatorsParam =new OperationCenterOperatorsParam();
            List<Long> operatorIdList = getChange(param.getOperatorId());
            operatorsParam.setOperatorsIdList(operatorIdList);
            List<OperationCenterOperatorsVo> opCenterOperatorList = operationCenterOperatorsService.getOpCenterOperatorList(operatorsParam);
            param.setOpCenterOperatorList(opCenterOperatorList);

        }

*/
        OperationCenterOrderFormVo formVo =new OperationCenterOrderFormVo();
        log.info("运营中心-订单管理-列表,处理后的参数====param:{}", JSON.toJSONString(param));
        PageHelper.startPage(param.getPageNumber(), param.getPageSize());
        List<OperationCenterOrderVo> resultList = operationCenterOrderService.getOperatorCenterOrderList(param);
        //将状态由通过枚举 int->string
        for (OperationCenterOrderVo vo : resultList) {
            vo.setOrderBizTypeDesc(null != vo.getOrderBizTypeId()?OpCenterOrderBizTypeEnum.getDescByCode(vo.getOrderBizTypeId()):"");

            vo.setTransactionStatusDesc(null != vo.getTransactionStatusId()?OpCenterTransactionStatusEnum.getDescByCode(vo.getTransactionStatusId()):"");

            vo.setPlatformAftersaleStatusDesc(null != vo.getPlatformAftersaleStatusId()?OpCenterPlatformAftersaleStatusEnum.getDescByCode(vo.getPlatformAftersaleStatusId()):"");

            vo.setOrderPayStatusDesc(null != vo.getOrderPayStatus()?OpCenterOrderPayStatusEnum.getDescByCode(vo.getOrderPayStatus()):"");
        }

        formVo.setOperationCenterOrderVos(resultList);
        Map<String, Object> mapCount = operationCenterOrderService.getOrderStatisticsCount(param);
        formVo.setOrderCount((Long) mapCount.get("orderCount"));
        formVo.setOrderGoodsAmountCount((BigDecimal) mapCount.get("orderGoodsAmountCount"));
        formVo.setTransportAmountCount((BigDecimal)mapCount.get("transportAmountCount"));
        formVo.setDiscountAmountCount((BigDecimal)mapCount.get("discountAmountCount"));
        formVo.setOrderPriceCount((BigDecimal)mapCount.get("orderPriceCount"));
        formVo.setOrderSettlementAmountCount((BigDecimal)mapCount.get("orderSettlementAmountCount"));

        PageInfo<OperationCenterOrderVo> page       = new PageInfo<OperationCenterOrderVo>(resultList);
        PageHelper.clearPage();

        return new R<OperationCenterOrderFormVo>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(),formVo );

    }





    @Override
    public R<OperationCenterOrderDetailsVo> getOperationCenterOrderDetails(Long id) {
        R<OperationCenterOrderDetailsVo> result = new R<>();
        if (null == id) {
            return result;
        }
        //订单信息
        OperationCenterOrder operationCenterOrderEntity = operationCenterOrderService.findById(id);

        //订单关联商品信息
        List<OperationCenterOrderGoodsVO> operationCenterOrderGoodsVOList = operationCenterOrderGoodsService.getOrderGoodsListByOrderSn(operationCenterOrderEntity.getBizPlatformCode(),operationCenterOrderEntity.getOrderSn());
        if (CollectionUtils.isNotEmpty(operationCenterOrderGoodsVOList)) {
//            for (OperationCenterOrderGoodsVO vo : operationCenterOrderGoodsVOList) {
//                vo.setGoodsTypeDesc(null != vo.getGoodsTypeId()? OpCenterGoodsTypeEnum.getDescByCode(vo.getGoodsTypeId()):"");
//            }
            //排除 商户承担运费
            operationCenterOrderGoodsVOList=operationCenterOrderGoodsVOList.stream()
                    .filter(x->x.getGoodsTypeId() != OpCenterGoodsTypeEnum.商户承担运费.getCode())
                    .map(vo->{
                            vo.setGoodsTypeDesc(null != vo.getGoodsTypeId()? OpCenterGoodsTypeEnum.getDescByCode(vo.getGoodsTypeId()):"");
                            return vo;
                    }).collect(Collectors.toList());
        }

        //订单关联流水信息
        List<OperationCenterOrderTransactionLogVo> operationCenterOrderTransactionLogVoList =   operationCenterOrderTransactionLogService.getOrderTransactionListByOrderSn(operationCenterOrderEntity.getBizPlatformCode(), operationCenterOrderEntity.getOrderSn());

        if (CollectionUtils.isNotEmpty(operationCenterOrderTransactionLogVoList)) {
            operationCenterOrderTransactionLogVoList = operationCenterOrderTransactionLogVoList.stream()
                    .filter(x -> x.getGoodsTypeId() != OpCenterGoodsTypeEnum.商户承担运费.getCode())
                    .map(vo -> {
                        vo.setGoodsTypeDesc(null != vo.getGoodsTypeId() ? OpCenterGoodsTypeEnum.getDescByCode(vo.getGoodsTypeId()) : "");
                        vo.setPayStatusDesc(null != vo.getPayStatusId() ? OpCenterOrderPayStatusEnum.getDescByCode(vo.getPayStatusId()) : "");
                        return vo;
                    }).collect(Collectors.toList());
        }


        OperationCenterOrderDetailsVo vo = new OperationCenterOrderDetailsVo();

        BeanUtils.copyProperties(operationCenterOrderEntity, vo);
        vo.setFinishTime(null != operationCenterOrderEntity.getFinishTime() ? DateUtil.format(operationCenterOrderEntity.getFinishTime(), "yyyy-MM-dd HH:mm:ss") : "");
        vo.setTradingTime(null != operationCenterOrderEntity.getTradingTime() ? DateUtil.format(operationCenterOrderEntity.getTradingTime(), "yyyy-MM-dd HH:mm:ss") : "");
        vo.setOrderCreateTime(null != operationCenterOrderEntity.getOrderCreateTime() ? DateUtil.format(operationCenterOrderEntity.getOrderCreateTime(), "yyyy-MM-dd HH:mm:ss") : "");
        vo.setSendTime(null != operationCenterOrderEntity.getSendTime() ? DateUtil.format(operationCenterOrderEntity.getSendTime(), "yyyy-MM-dd HH:mm:ss") : "");

        vo.setOrderBizTypeDesc(null != vo.getOrderBizTypeId()?OpCenterOrderBizTypeEnum.getDescByCode(vo.getOrderBizTypeId().intValue()):"");

        vo.setTransactionStatusDesc(null != vo.getTransactionStatusId()? OpCenterTransactionStatusEnum.getDescByCode(vo.getTransactionStatusId().intValue()):"");

        vo.setPlatformAfterSaleStatusDesc(null != vo.getPlatformAftersaleStatusId()? OpCenterPlatformAftersaleStatusEnum.getDescByCode(vo.getPlatformAftersaleStatusId().intValue()):"");

        vo.setOrderPayStatusDesc(null != vo.getOrderPayStatus()? OpCenterOrderPayStatusEnum.getDescByCode(vo.getOrderPayStatus().intValue()):"");


        vo.setOperationCenterOrderGoodsVOList(operationCenterOrderGoodsVOList);
        vo.setOperationCenterOrderTransactionLogVoList(operationCenterOrderTransactionLogVoList);


        //判断是否是售后单,并且退单原单号不能为空才关联原订单
        if (OpCenterOrderBizTypeEnum.售后.getCode().intValue()==operationCenterOrderEntity.getOrderBizTypeId()
                && StringUtils.isNotBlank(operationCenterOrderEntity.getRefundOriginOrderSn()) ) {
            List<OperationCenterOrderVo> orderByOrderVos = operationCenterOrderService.getOrderByOrderNo(operationCenterOrderEntity.getBizPlatformCode(),operationCenterOrderEntity.getRefundOriginOrderSn(),null);

            for (OperationCenterOrderVo orderByOrderVo : orderByOrderVos) {
                orderByOrderVo.setOrderBizTypeDesc(null != orderByOrderVo.getOrderBizTypeId()?OpCenterOrderBizTypeEnum.getDescByCode(orderByOrderVo.getOrderBizTypeId().intValue()):"");
                orderByOrderVo.setOrderPayStatusDesc(null != orderByOrderVo.getOrderPayStatus()? OpCenterOrderPayStatusEnum.getDescByCode(orderByOrderVo.getOrderPayStatus().intValue()):"");
                orderByOrderVo.setTransactionStatusDesc(null != orderByOrderVo.getTransactionStatusId()? OpCenterTransactionStatusEnum.getDescByCode(orderByOrderVo.getTransactionStatusId().intValue()):"");

            }


            vo.setOperationCenterOrderVoList(orderByOrderVos);
        }
        //判断该订单时 订单类型 -关联售后
        if (OpCenterOrderBizTypeEnum.订单.getCode().intValue()==operationCenterOrderEntity.getOrderBizTypeId() ) {
            List<OperationCenterOrderVo> orderByOrderVos = operationCenterOrderService.getOrderByOrderNo(operationCenterOrderEntity.getBizPlatformCode(),null,operationCenterOrderEntity.getOrderSn());

            for (OperationCenterOrderVo orderByOrderVo : orderByOrderVos) {
                orderByOrderVo.setOrderBizTypeDesc(null != orderByOrderVo.getOrderBizTypeId()?OpCenterOrderBizTypeEnum.getDescByCode(orderByOrderVo.getOrderBizTypeId().intValue()):"");
                orderByOrderVo.setOrderPayStatusDesc(null != orderByOrderVo.getOrderPayStatus()? OpCenterOrderPayStatusEnum.getDescByCode(orderByOrderVo.getOrderPayStatus().intValue()):"");
                orderByOrderVo.setTransactionStatusDesc(null != orderByOrderVo.getTransactionStatusId()? OpCenterTransactionStatusEnum.getDescByCode(orderByOrderVo.getTransactionStatusId().intValue()):"");

            }


            vo.setOperationCenterOrderVoList(orderByOrderVos);
        }



        result.setData(vo);
        return result;
    }

    @Override
    public String exportExcelOperationCenterOrder(OperationCenterOrderParam param, LoginSysUser loginSysUser) {
        log.info("导出运营中心报表 exportExcelOperationCenterOrder params: \n{}", JSON.toJSONString(param));
        if (null == param.getId()){ //id为空 列表导出

        //校验参数
        //当订单的列表为空时，不允许导出
        PageHelper.startPage(1, 1);
        List<OperationCenterOrderVo> resultList = operationCenterOrderService.getOperatorCenterOrderList(param);
        if (CollectionUtils.isEmpty(resultList)) {
            return "订单列表数据为空，不允许导出";
        }
        //1天≤当前“订单时间”的日期范围（结束日期-开始日期）天数≤180天
        if (!dateScope(param.getOrderBeginTime(), param.getOrderEndTime())) {
            return "目前仅支持导出订单时间日期范围最多180天的数据，请重新选择后查询再导出";
        }

        }else { //id 不为空时
            OperationCenterOrder order = operationCenterOrderService.findById(param.getId());
            param.setId(null);
            param.setOrderSn(order.getOrderSn());
        }

        CompletableFuture.runAsync(() -> {
            try {
                SysNotify sysNotify = operationCenterOrderService.exportExcelOperationCenterOrder(param);
                // 通知
                dubboSysNotifyService.notifyExportExcelScoreOrderReconciliationNotYet(sysNotify, loginSysUser);
            } catch (Exception e) {
                log.error("导出运营中心报表 exportExcelOperationCenterOrder params: \n{}", AnJsonUtils.toJson(param), e);
            }
        });
        return "导出任务已经接收,正在处理中...";
    }

    /**
     * 判断beginTime-endTime 是否在180天内
     */
    public static boolean dateScope(String beginTime, String endTime) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date beginDate = format.parse(beginTime);
            Date endDate = format.parse(endTime);
            long times = endDate.getTime() - beginDate.getTime() ;
            int days = (int) (times / (1000 * 3600 * 24) + 1);
            log.info("导出订单时间为：day->{}", days);
            if (days >= 1 && days <= 180) {
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("dateScope：-->beginTime:{}-endTime:{}===转化异常",beginTime,endTime);
            return false;
        }
    }

    /**
     * 将string 转化成 list
     */
    private Set<Long> getChange(String str) {
        Set<Long> result =new HashSet<>();
        String[] split = str.split(",");
        for (String num : split) {
            result.add(Long.parseLong(num));
        }
        return result;
    }
}
