package cn.superdesk.uniorder.service.scheduler.impl;

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderDimCreateByEnum;
import cn.superdesk.uniorder.common.enums.common.CommonAccountingDateTypeEnum;
import cn.superdesk.uniorder.common.enums.common.CommonAccountingStateEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.jd.SysQuartzScheduleTaskStatementOfAccountIsPauseEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.jd.SysQuartzScheduleTaskStatementOfAccountRunStateEnum;
import cn.superdesk.uniorder.common.exception.UnifiedOrderRuntimeException;
import cn.superdesk.uniorder.common.exception.utils.AssertUtils;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.numerical.*;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.security.JwtUtil;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.dao.entity.accounting.unified.customer.AccountingUnifiedCustomer;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderExample;
import cn.superdesk.uniorder.dao.entity.scheduler.SysQuartzScheduleTaskStatementOfAccount;
import cn.superdesk.uniorder.dao.entity.scheduler.SysQuartzScheduleTaskStatementOfAccountExample;
import cn.superdesk.uniorder.dao.mapper.base.UnifiedOrderMapper;
import cn.superdesk.uniorder.dao.mapper.base.UnifiedOrderMapperExCustomerDimGoods;
import cn.superdesk.uniorder.dao.mapper.scheduler.SysQuartzScheduleTaskStatementOfAccountMapper;
import cn.superdesk.uniorder.dto.param.accounting.AutoCreateScheduleTaskStatementOfAccountParam;
import cn.superdesk.uniorder.dto.param.accounting.AutoCreateScheduleTaskStatementOfAccountReportVo;
import cn.superdesk.uniorder.dto.param.accounting.unified.customer.UnifiedCustomerCreateDimGoodsParam;
import cn.superdesk.uniorder.dto.param.accounting.unified.customer.UnifiedCustomerCreateDimGoodsParamJsonStruct;
import cn.superdesk.uniorder.dto.param.accounting.unified.customer.UnifiedCustomerCreateDimOrderParam;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.notyet.CustomerUnAccountingDimGoodsVo;
import cn.superdesk.uniorder.service.accounting.unified.customer.AccountingUnifiedCustomerService;
import cn.superdesk.uniorder.service.accounting.unified.customer.AccountingUnifiedCustomerServiceOpCreateDimGoods;
import cn.superdesk.uniorder.service.accounting.unified.customer.AccountingUnifiedCustomerServiceOpCreateDimOrder;
import cn.superdesk.uniorder.service.scheduler.SysQuartzScheduleTaskStatementOfAccountService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 定时任务-时刻任务-对账单
 * @Author: linjinyu
 * @Email linjinyu@avic-s.com
 * @CreateDate: 2020-12-17 16:35:26
 * @UpdateUser: linjinyu
 * @UpdateDate: 2020-12-17 16:35:26
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class SysQuartzScheduleTaskStatementOfAccountServiceImpl implements SysQuartzScheduleTaskStatementOfAccountService {

    @Autowired
    private SysQuartzScheduleTaskStatementOfAccountMapper sysQuartzScheduleTaskStatementOfAccountMapper;

    @Autowired
    private UnifiedOrderMapper                   unifiedOrderMapper;
    @Autowired
    private UnifiedOrderMapperExCustomerDimGoods unifiedOrderMapperExCustomerDimGoods;

//	@Autowired
//	private UnifiedOrderService unifiedOrderService;

    @Autowired
    private AccountingUnifiedCustomerService                 accountingUnifiedCustomerService;
    @Autowired
    private AccountingUnifiedCustomerServiceOpCreateDimOrder accountingUnifiedCustomerServiceOpCreateDimOrder;
    @Autowired
    private AccountingUnifiedCustomerServiceOpCreateDimGoods accountingUnifiedCustomerServiceOpCreateDimGoods;


    /****************************************** extends BaseService 部分 start ******************************************/

    @Override
    public int insertSelective(SysQuartzScheduleTaskStatementOfAccount entity) {
        return sysQuartzScheduleTaskStatementOfAccountMapper.insertSelective(entity);
    }

    @Override
    public int updateByPrimaryKeySelective(SysQuartzScheduleTaskStatementOfAccount entity) {
        return sysQuartzScheduleTaskStatementOfAccountMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void deleteObj(Long id) {
    }

    @Override
    public SysQuartzScheduleTaskStatementOfAccount findById(Long id) {
        return sysQuartzScheduleTaskStatementOfAccountMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<SysQuartzScheduleTaskStatementOfAccount> findByPaging(Map<String, Object> conditions, Integer pageNun, Integer pageSize) {
        return null;
    }

    @Override
    public List<SysQuartzScheduleTaskStatementOfAccount> findAll(Map<String, Object> queryMap) {
        return null;
    }

    /****************************************** extends BaseService 部分   end ******************************************/


    @Override
    public void addSysQuartzScheduleTaskStatementOfAccount(SysQuartzScheduleTaskStatementOfAccount entity) {
        sysQuartzScheduleTaskStatementOfAccountMapper.insertSelective(entity);
    }


    @Override
    public void updateSysQuartzScheduleTaskStatementOfAccount(SysQuartzScheduleTaskStatementOfAccount entity) {
        SysQuartzScheduleTaskStatementOfAccount originEntity = sysQuartzScheduleTaskStatementOfAccountMapper.selectByPrimaryKey(entity.getId());
        AssertUtils.notNull(originEntity);
        AnBeanUtils.copy(entity, originEntity);
        sysQuartzScheduleTaskStatementOfAccountMapper.updateByPrimaryKey(originEntity);
    }

    @Override
    public void deleteSysQuartzScheduleTaskStatementOfAccount(Long id) {
        sysQuartzScheduleTaskStatementOfAccountMapper.deleteByPrimaryKey(id);
    }

    @Override
    public SysQuartzScheduleTaskStatementOfAccount findSysQuartzScheduleTaskStatementOfAccountById(Long id) {
        SysQuartzScheduleTaskStatementOfAccount entity = sysQuartzScheduleTaskStatementOfAccountMapper.selectByPrimaryKey(id);
        AssertUtils.notNull(entity);
        return entity;
    }

    @Override
    public R<List<SysQuartzScheduleTaskStatementOfAccount>> pageQuery(Map<String, Object> conditions, int pageNun, int pageSize) {

        log.info("SysQuartzScheduleTaskStatementOfAccount pageQuery {}", AnJsonUtils.toJson(conditions));

        // 样例 保留
//		SysQuartzScheduleTaskStatementOfAccount sysQuartzScheduleTaskStatementOfAccountConditions = AnBeanUtils.mapToBean(conditions,SysQuartzScheduleTaskStatementOfAccount.class);

        SysQuartzScheduleTaskStatementOfAccountExample          example  = new SysQuartzScheduleTaskStatementOfAccountExample();
        SysQuartzScheduleTaskStatementOfAccountExample.Criteria criteria = example.createCriteria();

        /****************************************** 查询条件 start ******************************************/

//		conditions: {outVirtId: "", serviceNo: "", runState: "", dimCreateBy: ""}
//		因为前羰这个传 , 所以要这样处理

//		企业名称
//				中航物业管理有限公司
//			outVirtId
        if (null != conditions.get("outVirtId") && StringUtils.isNotBlank(AnStringUtils.getString(conditions.get("outVirtId")))) {
            criteria.andOutVirtIdEqualTo(AnLongUtils.getLong(conditions.get("outVirtId")));
        }
//		订单类型
//				请选择 LNSS-楼内闪送
//			serviceNo
        if (null != conditions.get("serviceNo") && StringUtils.isNotBlank(AnStringUtils.getString(conditions.get("serviceNo")))) {
            criteria.andServiceNoEqualTo(AnStringUtils.getString(conditions.get("serviceNo")));
        }
//		任务状态
//			runState
//		---- 运行状态:-1-失败;0-待命;1-成功
        if (null != conditions.get("runState") && StringUtils.isNotBlank(AnStringUtils.getString(conditions.get("runState")))) {
            criteria.andRunStateEqualTo(AnIntegerUtils.getInteger(conditions.get("runState")));
        }
//		账单类型
//			dimCreateBy
//		---- 对账单 创建维度:0-订单;1-商品;2-流水;
        if (null != conditions.get("dimCreateBy") && StringUtils.isNotBlank(AnStringUtils.getString(conditions.get("dimCreateBy")))) {
            criteria.andDimCreateByEqualTo(AnIntegerUtils.getInteger(conditions.get("dimCreateBy")));
        }
        /****************************************** 查询条件 start ******************************************/

        PageHelper.startPage(pageNun, pageSize);
        List<SysQuartzScheduleTaskStatementOfAccount>     resultList = sysQuartzScheduleTaskStatementOfAccountMapper.selectByExample(example);
        PageInfo<SysQuartzScheduleTaskStatementOfAccount> page       = new PageInfo<SysQuartzScheduleTaskStatementOfAccount>(resultList);
        PageHelper.clearPage();

        return new R<List<SysQuartzScheduleTaskStatementOfAccount>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), resultList);

    }


    /****************************************** 生成 任务 start ******************************************/
    /**
     * 按条件 得出 订单 按  企业 订单来源 排列组合 创建对账单 时刻任务
     *
     * @param params
     */
    public AutoCreateScheduleTaskStatementOfAccountReportVo autoCreateScheduleTaskStatementOfAccountDimOrder(String token, AutoCreateScheduleTaskStatementOfAccountParam params) {

        AutoCreateScheduleTaskStatementOfAccountReportVo report = new AutoCreateScheduleTaskStatementOfAccountReportVo();

        String userId;
        // 考虑到有可能要批量删除
        Date batchTime = DateUtil.date();

        if (null == token && null != params.getIsTest() && params.getIsTest().equals(1)) {
            userId = "1";
        } else {
            userId = JwtUtil.checkTokenAndGetUserId(token);
        }


//		未对账订单 数据 获取
        // 此sql 就是单纯的查 order 表
//		List<UnifiedOrderCustomerNotCheckVo > result = unifiedOrderMapperEx.getCustomerUnAccountingDimOrderList(params);

        // 不写sql 做法
        UnifiedOrderExample          example  = new UnifiedOrderExample();
        UnifiedOrderExample.Criteria criteria = example.createCriteria();

        // 时间 过滤未对账订单 范围
        criteria.andCreateTimeBetween(params.getStartTime(), params.getEndTime());

        if (null != params.getOutVirtId()) {
            criteria.andPurchaseVirtIdEqualTo(params.getOutVirtId());
        }
        if (null != params.getServiceNo()) {
            criteria.andServiceNoEqualTo(params.getServiceNo());
        }

        criteria.andAccountingStateCustomerEqualTo(CommonAccountingStateEnum.未对账.getKey());

        List<UnifiedOrder> processOrderList = unifiedOrderMapper.selectByExample(example);

        // 如果条件 没有数据 直接 返回
        if (AnCollectionUtils.isEmpty(processOrderList)) {
            report.setCountStatementOfAccount(0);

            return report;
        }

        Map<String, List<UnifiedOrder>> transferMapGroupByOrgAndVirtAndServiceNo = processOrderList.parallelStream()
                .collect(Collectors.groupingBy(e -> fetchGroupKeyByOrgAndVirtAndServiceNoDimOrder(e), Collectors.toList()));

        for (Map.Entry<String, List<UnifiedOrder>> _entry : transferMapGroupByOrgAndVirtAndServiceNo.entrySet()) {

            String scheduleTaskStatementOfAccountName = checkAndGetScheduleTaskStatementOfAccountName(_entry.getKey(), params.getStartTime(), params.getEndTime());

            if (null == scheduleTaskStatementOfAccountName) {
                // TODO 重复生的计数器
                continue;
            }

            log.info("\n{}\n{}", _entry.getKey(), AnJsonUtils.toJson(_entry.getValue()));

            String[] unPackageInfo = _entry.getKey().split("_");

            SysQuartzScheduleTaskStatementOfAccount sysQuartzScheduleTaskStatementOfAccount = new SysQuartzScheduleTaskStatementOfAccount();

//			params.getDimCreateBy()
            sysQuartzScheduleTaskStatementOfAccount.setDimCreateBy(AccountingOrderDimCreateByEnum.订单.getKey());

            sysQuartzScheduleTaskStatementOfAccount.setStatementOfAccountName(scheduleTaskStatementOfAccountName);
            // TODO 写死 对账单类型 1-客户结算;2-供应商结算;
            sysQuartzScheduleTaskStatementOfAccount.setStatementOfAccountType(1);

            sysQuartzScheduleTaskStatementOfAccount.setServiceId(0);
            sysQuartzScheduleTaskStatementOfAccount.setServiceNo(unPackageInfo[4]);
            sysQuartzScheduleTaskStatementOfAccount.setServiceName(unPackageInfo[5]);

            sysQuartzScheduleTaskStatementOfAccount.setCycleBeginTime(params.getStartTime());
            sysQuartzScheduleTaskStatementOfAccount.setCycleEndTime(params.getEndTime());

            sysQuartzScheduleTaskStatementOfAccount.setSysOrgId(0L);
            sysQuartzScheduleTaskStatementOfAccount.setSysVirtId(0L);

            sysQuartzScheduleTaskStatementOfAccount.setOutOrgId(AnLongUtils.getLong(unPackageInfo[0]));
            sysQuartzScheduleTaskStatementOfAccount.setOutVirtId(AnLongUtils.getLong(unPackageInfo[2]));

            // 状态 是否暂停:1暂停、0启用
            sysQuartzScheduleTaskStatementOfAccount.setIsPause(0);
            // 运行状态:-1-失败;0-待命;1-成功
            sysQuartzScheduleTaskStatementOfAccount.setRunState(0);

            sysQuartzScheduleTaskStatementOfAccount.setParams(AnJsonUtils.toJson(params));
            sysQuartzScheduleTaskStatementOfAccount.setParamsSnapshot(AnJsonUtils.toJson(_entry.getValue()));

            // TODO
            sysQuartzScheduleTaskStatementOfAccount.setJobId(0L);

            sysQuartzScheduleTaskStatementOfAccount.setCreateTime(batchTime);
            sysQuartzScheduleTaskStatementOfAccount.setCreateUserId(AnLongUtils.getLong(userId));

            sysQuartzScheduleTaskStatementOfAccountMapper.insert(sysQuartzScheduleTaskStatementOfAccount);
        }


        report.setCountStatementOfAccount(transferMapGroupByOrgAndVirtAndServiceNo.size());

        return report;

    }

    private String fetchGroupKeyByOrgAndVirtAndServiceNoDimOrder(UnifiedOrder unifiedOrder) {
        return
                unifiedOrder.getProjectId() +
                        "_" + unifiedOrder.getProjectName() +
                        "_" + unifiedOrder.getPurchaseVirtId() +
                        "_" + unifiedOrder.getPurchaseVirtName() +
                        "_" + unifiedOrder.getServiceNo() +
                        "_" + unifiedOrder.getServiceName();
    }

    /**
     * 订单
     * 12_深圳南光大厦_65_中航技国际经贸发展有限公司深圳分公司_LNSS_闪送订单 2020-09-01 00:00:00<->2020-09-30 23:59:59
     * 商品
     * 65_中航技国际经贸发展有限公司深圳分公司_LNSS_闪送订单 2020-09-01 00:00:00<->2020-09-30 23:59:59
     *
     * @param entryKey
     * @param startTime
     * @param endTime
     * @return
     */
    private String checkAndGetScheduleTaskStatementOfAccountName(String entryKey, Date startTime, Date endTime) {

        // TODO check mark by linjinyu at 202012181700

        return entryKey + " " + DateUtil.format(startTime, AnDateHelper.DATE_TIME_STRING) + "<->" + DateUtil.format(endTime, AnDateHelper.DATE_TIME_STRING);
    }

    public AutoCreateScheduleTaskStatementOfAccountReportVo autoCreateScheduleTaskStatementOfAccountDimGoods(String token, AutoCreateScheduleTaskStatementOfAccountParam params) {

        AutoCreateScheduleTaskStatementOfAccountReportVo report = new AutoCreateScheduleTaskStatementOfAccountReportVo();

        LoginSysUser loginSysUser;
        // 考虑到有可能要批量删除
        Date batchTime = DateUtil.date();

        if (null == token && null != params.getIsTest() && params.getIsTest().equals(1)) {
            loginSysUser = LoginSysUser.builder().sysUserId(1L).build();
        } else {
            loginSysUser = JwtUtil.getLoginSysUser(token);
        }

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

        // DATE_TIME_STRING
        paramsQuery.put("startTime", DateUtil.format(params.getStartTime(), AnDateHelper.CURRENT_DATE));
        paramsQuery.put("endTime", DateUtil.format(params.getEndTime(), AnDateHelper.CURRENT_DATE));

        if (null != params.getOutVirtId()) {
            paramsQuery.put("purchaseVirtId", params.getOutVirtId());
        }
        if (null != params.getServiceNo()) {
            paramsQuery.put("serviceNo", params.getServiceNo());
        }

        paramsQuery.put("accountingStateCustomer", CommonAccountingStateEnum.未对账.getKey());

        List<CustomerUnAccountingDimGoodsVo> processList = unifiedOrderMapperExCustomerDimGoods.getCustomerUnAccountingDimGoodsList(paramsQuery);

        // 如果条件 没有数据 直接 返回
        if (AnCollectionUtils.isEmpty(processList)) {
            report.setCountStatementOfAccount(0);

            return report;
        }

        Map<String, List<CustomerUnAccountingDimGoodsVo>> transferMapGroupByOrgAndVirtAndServiceNo = processList.parallelStream()
                .collect(Collectors.groupingBy(e -> fetchGroupKeyByOrgAndVirtAndServiceNoDimOrder(e), Collectors.toList()));


        for (Map.Entry<String, List<CustomerUnAccountingDimGoodsVo>> _entry : transferMapGroupByOrgAndVirtAndServiceNo.entrySet()) {

            String scheduleTaskStatementOfAccountName = checkAndGetScheduleTaskStatementOfAccountName(_entry.getKey(), params.getStartTime(), params.getEndTime());

            log.info("\n{}\n{}", _entry.getKey(), AnJsonUtils.toJson(_entry.getValue()));

            String[] unPackageInfo = _entry.getKey().split("_");

            SysQuartzScheduleTaskStatementOfAccount sysQuartzScheduleTaskStatementOfAccount = new SysQuartzScheduleTaskStatementOfAccount();

            // params.getDimCreateBy()
            sysQuartzScheduleTaskStatementOfAccount.setDimCreateBy(AccountingOrderDimCreateByEnum.商品.getKey());

            sysQuartzScheduleTaskStatementOfAccount.setStatementOfAccountName(scheduleTaskStatementOfAccountName);
            // TODO 写死 对账单类型 1-客户结算;2-供应商结算;
            sysQuartzScheduleTaskStatementOfAccount.setStatementOfAccountType(1);

            sysQuartzScheduleTaskStatementOfAccount.setServiceId(0);
            sysQuartzScheduleTaskStatementOfAccount.setServiceNo(unPackageInfo[2]);
            sysQuartzScheduleTaskStatementOfAccount.setServiceName(unPackageInfo[3]);

            sysQuartzScheduleTaskStatementOfAccount.setCycleBeginTime(params.getStartTime());
            sysQuartzScheduleTaskStatementOfAccount.setCycleEndTime(params.getEndTime());

            sysQuartzScheduleTaskStatementOfAccount.setSysOrgId(0L);
            sysQuartzScheduleTaskStatementOfAccount.setSysVirtId(0L);

            sysQuartzScheduleTaskStatementOfAccount.setOutOrgId(0L);
            sysQuartzScheduleTaskStatementOfAccount.setOutVirtId(AnLongUtils.getLong(unPackageInfo[0]));

            // 状态 是否暂停:1暂停、0启用
            sysQuartzScheduleTaskStatementOfAccount.setIsPause(0);
            // 运行状态:-1-失败;0-待命;1-成功
            sysQuartzScheduleTaskStatementOfAccount.setRunState(0);

            sysQuartzScheduleTaskStatementOfAccount.setParams(AnJsonUtils.toJson(params));

            /****************************************** 差异 start ******************************************/

            List<UnifiedCustomerCreateDimGoodsParamJsonStruct> paramsSnapshot = new ArrayList<>();
            for (CustomerUnAccountingDimGoodsVo vo : _entry.getValue()) {

                UnifiedCustomerCreateDimGoodsParamJsonStruct paramJsonStruct = new UnifiedCustomerCreateDimGoodsParamJsonStruct();
                paramJsonStruct.setUnifiedOrderId(vo.getUnifiedOrderId());
                paramJsonStruct.setUnifiedOrderGoodsId(vo.getUnifiedOrderGoodsId());
                paramJsonStruct.setGoodsId(vo.getGoodsId());

                paramsSnapshot.add(paramJsonStruct);
            }
            sysQuartzScheduleTaskStatementOfAccount.setParamsSnapshot(AnJsonUtils.toJson(paramsSnapshot));
            /****************************************** 差异   end ******************************************/

            // TODO
            sysQuartzScheduleTaskStatementOfAccount.setJobId(0L);

            sysQuartzScheduleTaskStatementOfAccount.setCreateTime(batchTime);
            sysQuartzScheduleTaskStatementOfAccount.setCreateUserId(loginSysUser.getSysUserId());

            sysQuartzScheduleTaskStatementOfAccountMapper.insert(sysQuartzScheduleTaskStatementOfAccount);
        }

        report.setCountStatementOfAccount(transferMapGroupByOrgAndVirtAndServiceNo.size());

        return report;

    }

    private String fetchGroupKeyByOrgAndVirtAndServiceNoDimOrder(CustomerUnAccountingDimGoodsVo vo) {
        return
//				unifiedOrder.getProjectId() +
//						"_" + unifiedOrder.getProjectName() +
//						"_" +
                vo.getPurchaseVirtId() +
                        "_" + vo.getPurchaseVirtName() +
                        "_" + vo.getServiceNo() +
                        "_" + vo.getServiceName();
    }


    /****************************************** 生成 任务   end ******************************************/

    /**
     * @return
     */
    public List<SysQuartzScheduleTaskStatementOfAccount> getToDoSysQuartzScheduleTaskStatementOfAccountList(int pageNun, int pageSize) {

        List<SysQuartzScheduleTaskStatementOfAccount> resultList = null;

//		int pageNun  = 1;
//		int pageSize = 10;

        PageHelper.startPage(pageNun, pageSize);

        SysQuartzScheduleTaskStatementOfAccountExample example = new SysQuartzScheduleTaskStatementOfAccountExample();
        example.createCriteria()
                .andIsPauseEqualTo(SysQuartzScheduleTaskStatementOfAccountIsPauseEnum.启用.getKey())
                .andRunStateEqualTo(SysQuartzScheduleTaskStatementOfAccountRunStateEnum.待命.getKey());

        resultList = sysQuartzScheduleTaskStatementOfAccountMapper.selectByExampleWithBLOBs(example);

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

        return resultList;
    }

    /**
     * 单个任务 执行 TODO 未重构之前 大概 是分别组装 各维度要的参数再去调用
     *
     * @param entity
     */
    public void runTaskSysQuartzScheduleTaskStatementOfAccount(SysQuartzScheduleTaskStatementOfAccount entity) {


        log.info("执行任务-runTaskSysQuartzScheduleTaskStatementOfAccount-{}", AnJsonUtils.toJson(entity));


        AccountingUnifiedCustomer accountingUnifiedCustomer = null;

        // 是否已处理
        Integer isProcessed = 0;

        if (null != entity.getAccountingOrderSn()) {
            isProcessed = 1;
            accountingUnifiedCustomer = accountingUnifiedCustomerService.findByAccountingOrderSn(entity.getAccountingOrderSn());

            log.info("执行任务-runTaskSysQuartzScheduleTaskStatementOfAccount-对账单-已存在-{}-任务结束", AnJsonUtils.toJson(accountingUnifiedCustomer));
        }

        Date runTime = DateUtil.date();

        LoginSysUser loginSysUser = LoginSysUser.builder().sysUserId(1L).build();

        if (isProcessed.compareTo(0) == 0) {


            switch (AccountingOrderDimCreateByEnum.get(entity.getDimCreateBy())) {
                case 订单:

                    log.info("订单维度 {}", isProcessed);

                    List<UnifiedOrder> unifiedOrderList = AnJsonUtils.toList(entity.getParamsSnapshot(), UnifiedOrder.class);
                    UnifiedCustomerCreateDimOrderParam unifiedCustomerCreateDimOrderParam = new UnifiedCustomerCreateDimOrderParam();

//				    unifiedCustomerCreateDimOrderParam.setIds();

                    // 周期类型 1-发货时间;2-下单时间;3-完成时间;
                    unifiedCustomerCreateDimOrderParam.setDateType(CommonAccountingDateTypeEnum.下单时间.getKey());

                    unifiedCustomerCreateDimOrderParam.setStartTime(entity.getCycleBeginTime());
                    unifiedCustomerCreateDimOrderParam.setEndTime(entity.getCycleEndTime());

                    unifiedCustomerCreateDimOrderParam.setServiceNo(entity.getServiceNo());

//				    unifiedCustomerCreateDimOrderParam.setDzMoney();
//				    unifiedCustomerCreateDimOrderParam.setOrderQuantity();

//				    unifiedCustomerCreateDimOrderParam.setPurchaseUserId();
//				    unifiedCustomerCreateDimOrderParam.setPurchaseUserName();
//				    unifiedCustomerCreateDimOrderParam.setPurchasePhone();

//				    unifiedCustomerCreateDimOrderParam.setBankInfoId();

//				    unifiedCustomerCreateDimOrderParam.setIsSendEmail();
//				    unifiedCustomerCreateDimOrderParam.setEndTime();

                    accountingUnifiedCustomer = accountingUnifiedCustomerServiceOpCreateDimOrder.opCreateAccountingDimOrderPreProcess(loginSysUser.getSysUserId(), unifiedOrderList, unifiedCustomerCreateDimOrderParam);

                    break;
                case 商品:

                    log.info("商品维度 {}", isProcessed);

                    UnifiedCustomerCreateDimGoodsParam unifiedCustomerCreateDimGoodsParam = new UnifiedCustomerCreateDimGoodsParam();

                    unifiedCustomerCreateDimGoodsParam.setStartTime(entity.getCycleBeginTime());
                    unifiedCustomerCreateDimGoodsParam.setEndTime(entity.getCycleEndTime());

                    unifiedCustomerCreateDimGoodsParam.setOutVirtId(entity.getOutVirtId());

                    unifiedCustomerCreateDimGoodsParam.setServiceNo(entity.getServiceNo());

                    unifiedCustomerCreateDimGoodsParam.setJsonStr(AnJsonUtils.toList(entity.getParamsSnapshot(), UnifiedCustomerCreateDimGoodsParamJsonStruct.class));

//				    unifiedCustomerCreateDimGoodsParam.setBankInfoId();
//
//				    unifiedCustomerCreateDimGoodsParam.setPurchaseUserId();
//				    unifiedCustomerCreateDimGoodsParam.setPurchaseUserName();
//				    unifiedCustomerCreateDimGoodsParam.setPurchasePhone();
//
//				    unifiedCustomerCreateDimGoodsParam.setAccountingAmount();
//				    unifiedCustomerCreateDimGoodsParam.setOrderQuantity();

//				    unifiedCustomerCreateDimGoodsParam.setIsSendEmail();
//				    unifiedCustomerCreateDimGoodsParam.setEmailAddress();

                    accountingUnifiedCustomer = accountingUnifiedCustomerServiceOpCreateDimGoods.opCreateAccountingDimGoodsPreProcess(unifiedCustomerCreateDimGoodsParam, loginSysUser);
                    break;
                case 流水:
                    throw new UnifiedOrderRuntimeException(500, "客户结算 对账单 目前不支持 流水维度");
                default:
                    throw new UnifiedOrderRuntimeException(500, "客户结算 对账单 没有命中 有逻辑问题");

            }
        }

        /****************************************** 更新任务 状态 start ******************************************/

        Date finishTime = DateUtil.date();

        SysQuartzScheduleTaskStatementOfAccount forUpdateStat = new SysQuartzScheduleTaskStatementOfAccount();
        forUpdateStat.setId(entity.getId());

        if (null == accountingUnifiedCustomer) {
            forUpdateStat.setRunState(SysQuartzScheduleTaskStatementOfAccountRunStateEnum.失败.getKey());
        } else {
            forUpdateStat.setRunState(SysQuartzScheduleTaskStatementOfAccountRunStateEnum.成功.getKey());
            forUpdateStat.setAccountingOrderSn(accountingUnifiedCustomer.getAccountingOrderSn());
        }

        forUpdateStat.setRunTime(runTime);
        forUpdateStat.setFinishTime(finishTime);
        forUpdateStat.setResult(AnJsonUtils.toJson(accountingUnifiedCustomer));

        sysQuartzScheduleTaskStatementOfAccountMapper.updateByPrimaryKeySelective(forUpdateStat);

        /****************************************** 更新任务 状态   end ******************************************/
    }


}
