package com.hzs.member.empty.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.enums.EDelFlag;
import com.hzs.common.domain.member.empty.CuMemberEmpty;
import com.hzs.common.domain.member.empty.CuMemberEmptyCode;
import com.hzs.common.domain.member.empty.CuMemberEmptyDetail;
import com.hzs.common.domain.member.empty.CuMemberEmptyProduct;
import com.hzs.common.domain.member.empty.ext.CuMemberEmptyDetailExt;
import com.hzs.member.empty.dto.EmptyMemberDTO;
import com.hzs.member.empty.dto.EmptyMemberDetailDTO;
import com.hzs.member.empty.dto.MemberEmptyDetailDTO;
import com.hzs.member.empty.mapper.CuMemberEmptyDetailMapper;
import com.hzs.member.empty.param.MemberEmptyAddParam;
import com.hzs.member.empty.service.ICuMemberEmptyCodeService;
import com.hzs.member.empty.service.ICuMemberEmptyDetailService;
import com.hzs.member.empty.service.ICuMemberEmptyProductService;
import com.hzs.member.empty.service.ICuMemberEmptyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 空单批次明细 服务实现类
 *
 * @author hzs
 * @since 2023-06-16
 */
@Service
public class CuMemberEmptyDetailServiceImpl extends ServiceImpl<CuMemberEmptyDetailMapper, CuMemberEmptyDetail> implements ICuMemberEmptyDetailService {

    @Autowired
    private ICuMemberEmptyService iCuMemberEmptyService;
    @Autowired
    private ICuMemberEmptyCodeService iCuMemberEmptyCodeService;
    @Autowired
    private ICuMemberEmptyProductService iCuMemberEmptyProductService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CuMemberEmptyDetailExt addData(MemberEmptyAddParam param, Long userId, Integer pkCountry) {
        // 生成会员编号
        List<String> memberCodeList = iCuMemberEmptyCodeService.createCodeBatch(1, pkCountry, userId);

        // 空单批次ID
        Long pkMemberEmpty = param.getPkMemberEmpty();
        if (null == pkMemberEmpty) {
            // 空单批次为空，需要新建批次数据
            CuMemberEmpty cuMemberEmpty = new CuMemberEmpty();
            cuMemberEmpty.setBusinessCode(iCuMemberEmptyService.queryLastCode());
            cuMemberEmpty.setPkCreator(userId);
            cuMemberEmpty.setPkCountry(pkCountry);
            iCuMemberEmptyService.save(cuMemberEmpty);

            pkMemberEmpty = cuMemberEmpty.getPkId();
        }

        // 插入空单明细
        CuMemberEmptyDetail cuMemberEmptyDetail = new CuMemberEmptyDetail();
        cuMemberEmptyDetail.setPkMemberEmpty(pkMemberEmpty);
        cuMemberEmptyDetail.setMemberCode(memberCodeList.get(0));
        cuMemberEmptyDetail.setPkCreator(userId);
        cuMemberEmptyDetail.setPkCountry(pkCountry);
        cuMemberEmptyDetail.setPkSettleCountry(pkCountry);
        if (this.save(cuMemberEmptyDetail)) {
            return baseMapper.queryEmptyDetail(Collections.singletonList(cuMemberEmptyDetail.getPkId())).get(0);
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delData(List<CuMemberEmptyDetail> emptyDetailList, Long userId, Integer pkCountry) {
        Date nowDate = new Date();

        // 空单明细ID列表
        List<Long> detailIdList = emptyDetailList.stream().map(CuMemberEmptyDetail::getPkId).collect(Collectors.toList());
        // 空单明细会员编号列表
        List<String> memberCodeList = emptyDetailList.stream().map(CuMemberEmptyDetail::getMemberCode).collect(Collectors.toList());

        // 删除空单会员编号
        UpdateWrapper<CuMemberEmptyCode> codeUpdateWrapper = new UpdateWrapper<>();
        codeUpdateWrapper.in("MEMBER_CODE", memberCodeList);
        codeUpdateWrapper.eq(SystemFieldConstants.DEL_FLAG, EDelFlag.UN_DELETE.getValue());
        codeUpdateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.DELETE.getValue());
        codeUpdateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
        codeUpdateWrapper.set(SystemFieldConstants.MODIFIED_TIME, nowDate);
        iCuMemberEmptyCodeService.update(codeUpdateWrapper);

        // 删除空单明细产品
        UpdateWrapper<CuMemberEmptyProduct> productUpdateWrapper = new UpdateWrapper<>();
        productUpdateWrapper.in("PK_MEMBER_EMPTY_DETAIL", detailIdList);
        productUpdateWrapper.eq(SystemFieldConstants.DEL_FLAG, EDelFlag.UN_DELETE.getValue());
        productUpdateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.DELETE.getValue());
        productUpdateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
        productUpdateWrapper.set(SystemFieldConstants.MODIFIED_TIME, nowDate);
        iCuMemberEmptyProductService.update(productUpdateWrapper);

        // 删除空单明细
        UpdateWrapper<CuMemberEmptyDetail> detailUpdateWrapper = new UpdateWrapper<>();
        detailUpdateWrapper.in(SystemFieldConstants.PK_ID, detailIdList);
        detailUpdateWrapper.eq(SystemFieldConstants.DEL_FLAG, EDelFlag.UN_DELETE.getValue());
        detailUpdateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.DELETE.getValue());
        detailUpdateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
        detailUpdateWrapper.set(SystemFieldConstants.MODIFIED_TIME, nowDate);
        this.update(detailUpdateWrapper);
    }


    @Override
    public int deleteNotInData(Long pkMemberEmpty, List<Long> pkIdList, Long userId) {
        return baseMapper.deleteNotInData(pkMemberEmpty, pkIdList, userId);
    }

    @Override
    public List<Long> querySeqList(Integer param) {
        return baseMapper.querySeqList(param);
    }

    @Override
    public int insertBatch(List<CuMemberEmptyDetail> detailList, Long userId) {
        return baseMapper.insertBatch(detailList, userId);
    }

    @Override
    public int updateBatch(List<CuMemberEmptyDetail> detailList, Long userId) {
        return baseMapper.updateBatch(detailList, userId);
    }

    @Override
    public int updateAbnormalBatch(List<MemberEmptyDetailDTO> paramList, Long userId) {
        return baseMapper.updateAbnormalBatch(paramList, userId);
    }

    @Override
    public String checkPlaceParent(String memberCode, String parentCode, Long pkMemberEmpty) {
        return baseMapper.checkPlaceParent(memberCode, parentCode, pkMemberEmpty);
    }

    @Override
    public Map<Integer, List<CuMemberEmptyDetail>> checkPlaceDeptRepeat(String placeParentCode) {
        // key：左区、右区， value：空单数据列表（会员编号、安置编号、安置部门）
        Map<Integer, List<CuMemberEmptyDetail>> resultMap = new HashMap<>();

        List<CuMemberEmptyDetail> resultList = baseMapper.checkPlaceDeptRepeat(placeParentCode);
        if (CollectionUtil.isNotEmpty(resultList)) {
            for (CuMemberEmptyDetail emptyDetail : resultList) {
                // 按规则进行整合数据
                resultMap.computeIfAbsent(emptyDetail.getPlaceDept(), k -> new ArrayList<>()).add(emptyDetail);
            }
        }
        return resultMap;
    }

    @Override
    public Map<String, List<EmptyMemberDetailDTO>> queryMemberByPhone(List<EmptyMemberDTO> paramList) {
        Map<String, List<EmptyMemberDetailDTO>> resultMap = new HashMap<>();
        List<EmptyMemberDTO> resultList = baseMapper.queryMemberByPhone(paramList);
        if (CollectionUtil.isNotEmpty(resultList)) {
            for (EmptyMemberDTO emptyMemberDTO : resultList) {
                // 按合并规则进行整合数据
                resultMap.computeIfAbsent(emptyMemberDTO.getPhone(), k -> new ArrayList<>()).addAll(emptyMemberDTO.getDetailList());
            }
        }
        return resultMap;
    }

    @Override
    public String checkPhoneInPlaceParent(String memberCode, String phone, Long pkMemberEmpty) {
        return baseMapper.checkPhoneInPlaceParent(memberCode, phone, pkMemberEmpty);
    }

    @Override
    public List<CuMemberEmptyDetailExt> queryPlaceParentTop(Long pkMemberEmpty) {
        return baseMapper.queryPlaceParentTop(pkMemberEmpty);
    }

    @Override
    public List<CuMemberEmptyDetailExt> queryParentTop(Long pkMemberEmpty) {
        return baseMapper.queryParentTop(pkMemberEmpty);
    }

    @Override
    public List<CuMemberEmptyDetailExt> queryPlaceParentTopAndProduct(Long pkMemberEmpty) {
        return baseMapper.queryPlaceParentTopAndProduct(pkMemberEmpty);
    }

    @Override
    public List<CuMemberEmptyDetailExt> queryPlaceParentTree(Long pkId, Long pkMemberEmpty) {
        return baseMapper.queryPlaceParentTree(pkId, pkMemberEmpty);
    }

    @Override
    public List<CuMemberEmptyDetailExt> queryParentTree(Long pkId, Long pkMemberEmpty) {
        return baseMapper.queryParentTree(pkId, pkMemberEmpty);
    }

    @Override
    public List<CuMemberEmptyDetailExt> queryPlaceParentTreeAndProduct(Long pkId, Long pkMemberEmpty) {
        return baseMapper.queryPlaceParentTreeAndProduct(pkId, pkMemberEmpty);
    }

    @Override
    public List<CuMemberEmptyDetailExt> queryEmptyDetailList(Long pkMemberEmpty) {
        return baseMapper.queryEmptyDetailList(pkMemberEmpty);
    }

    @Override
    public List<CuMemberEmptyDetailExt> queryDetailAndProductList(Long pkMemberEmpty) {
        return baseMapper.queryDetailAndProductList(pkMemberEmpty);
    }

    @Override
    public List<CuMemberEmptyDetailExt> queryEmptyDetail(List<Long> detailIdList) {
        return baseMapper.queryEmptyDetail(detailIdList);
    }

}
