package com.hzs.retail.member.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.enums.ECategory;
import com.hzs.common.core.enums.EOperationBusiness;
import com.hzs.common.core.enums.EOperationMethod;
import com.hzs.common.core.enums.EOperationModule;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.member.account.CuMemberAccount;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.account.service.ICuMemberAccountService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.retail.member.param.ShareDeleteParam;
import com.hzs.retail.member.param.ShareParentDeleteParam;
import com.hzs.retail.member.param.ShareRetailMemberParam;
import com.hzs.retail.member.vo.ShareRetailMemberVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 新零售会员管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/manage/share-retail-member")
public class ShareRetailMemberController extends BaseController {

    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private ICuMemberAccountService iCuMemberAccountService;

    /**
     * 无订单会员列表
     *
     * @param param
     * @return
     */
    @GetMapping("/share-list")
    public TableDataInfo shareList(ShareRetailMemberParam param) {
        param.setPkCountry(SecurityUtils.getPkCountry());
        param.setSystemType(SecurityUtils.getSystemType());

        // 返回数据列表
        List<ShareRetailMemberVO> resultList = new ArrayList<>();

        startPage();
        List<CuMemberExt> cuMemberExtList = iCuMemberService.listRetailMemberNotOrder(param);
        if (CollectionUtil.isNotEmpty(cuMemberExtList)) {
            for (CuMemberExt cuMemberExt : cuMemberExtList) {
                resultList.add(BeanUtil.copyProperties(cuMemberExt, ShareRetailMemberVO.class));
            }
        }

        TableDataInfo tableDataInfo = getDataTable(cuMemberExtList);
        tableDataInfo.setRows(resultList);
        return tableDataInfo;
    }

    /**
     * 删除分享会员
     *
     * @param param
     * @return
     */
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.SHARE_DELETE, method = EOperationMethod.DELETE)
    @PostMapping("/share-delete")
    public AjaxResult shareDelete(@Valid @RequestBody ShareDeleteParam param) {
        // 校验会员下面是否挂人了
        if (iCuMemberService.count(Wrappers.<CuMember>lambdaQuery()
                .eq(CuMember::getPkParent, param.getPkMember())
                .eq(CuMember::getCategory, ECategory.NORMAL.getValue())
        ) > 0) {
            return AjaxResult.error("当前会员有推荐其它会员，不能删除");
        }

        // 校验会员账户是否有余额
        CuMemberAccount cuMemberAccount = iCuMemberAccountService.getOne(Wrappers.<CuMemberAccount>lambdaQuery()
                .eq(CuMemberAccount::getPkMember, param.getPkMember())
        );
        if (cuMemberAccount.getAccount1().compareTo(BigDecimal.ZERO) > 0
                || cuMemberAccount.getAccount2().compareTo(BigDecimal.ZERO) > 0
                || cuMemberAccount.getAccount4().compareTo(BigDecimal.ZERO) > 0
        ) {
            // 消费、现金、奖金，有一个账户有余额就不能删除
            return AjaxResult.error("当前会员存在余额，不能删除");
        }

        // 校验会员下是否有订单
        List<Long> checkMemberList = iCuMemberService.checkMemberOrder(Collections.singletonList(param.getPkMember()));
        if (CollectionUtil.isNotEmpty(checkMemberList)) {
            return AjaxResult.error("当前会员存在订单，不能删除");
        }

        iCuMemberService.shareDelete(param.getPkMember(), SecurityUtils.getUserId());
        return AjaxResult.success();
    }

    /**
     * 获取伞下删除数据
     *
     * @param pkMember
     * @return
     */
    @GetMapping("/share-parent-list")
    public AjaxResult shareParentList(@RequestParam Long pkMember) {
        StringBuilder memberCode = new StringBuilder();

        List<CuMemberExt> cuMemberExtList = iCuMemberService.queryBloodKinshipUnderUmbrella(pkMember);
        if (CollectionUtil.isNotEmpty(cuMemberExtList)) {
            for (CuMemberExt cuMemberExt : cuMemberExtList) {
                memberCode.append(cuMemberExt.getMemberCode()).append(",");
            }
        }

        return AjaxResult.success("", memberCode);
    }


    /**
     * 删除伞下会员
     *
     * @param param
     * @return
     */
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.SHARE_DELETE, method = EOperationMethod.DELETE)
    @PostMapping("/share-parent-delete")
    public AjaxResult deleteParentShare(@Valid @RequestBody ShareParentDeleteParam param) {
        List<String> memberCodeList = Arrays.asList(param.getPkMemberStr().split(","));
        // 需要删除的会员
        List<CuMember> memberList = iCuMemberService.list(Wrappers.<CuMember>lambdaQuery()
                .in(CuMember::getMemberCode, memberCodeList)
        );
        Map<Long, CuMember> memberMap = memberList.stream().collect(Collectors.toMap(CuMember::getPkId, value -> value));

        List<Long> pkMemberList = memberList.stream().map(CuMember::getPkId).collect(Collectors.toList());
        // 校验会员账户是否有余额
        StringBuilder errStr = new StringBuilder();
        List<CuMemberAccount> cuMemberAccountList = iCuMemberAccountService.list(Wrappers.<CuMemberAccount>lambdaQuery()
                .in(CuMemberAccount::getPkMember, pkMemberList)
        );
        for (CuMemberAccount cuMemberAccount : cuMemberAccountList) {
            if (cuMemberAccount.getAccount1().compareTo(BigDecimal.ZERO) > 0
                    || cuMemberAccount.getAccount2().compareTo(BigDecimal.ZERO) > 0
                    || cuMemberAccount.getAccount4().compareTo(BigDecimal.ZERO) > 0
            ) {
                // 消费、现金、奖金，有一个账户有余额就不能删除
                errStr.append(memberMap.get(cuMemberAccount.getPkMember()).getMemberCode()).append("，");
            }
        }
        if (StringUtils.isNotEmpty(errStr.toString())) {
            return AjaxResult.error("会员 " + errStr + " 存在余额，不能删除");
        }

        // 校验会员下是否有订单
        List<Long> checkMemberList = iCuMemberService.checkMemberOrder(pkMemberList);
        if (CollectionUtil.isNotEmpty(checkMemberList)) {
            for (Long pkMember : checkMemberList) {
                if (pkMemberList.contains(pkMember)) {
                    errStr.append(memberMap.get(pkMember).getMemberCode()).append("，");
                }
            }
        }
        if (StringUtils.isNotEmpty(errStr.toString())) {
            return AjaxResult.error("会员 " + errStr + " 存在订单，不能删除");
        }

        iCuMemberService.shareParentDelete(memberList, SecurityUtils.getUserId());
        return AjaxResult.success();
    }

}
