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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.AccessPermissions;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
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.base.CuMember;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.account.dto.MemberAmountDTO;
import com.hzs.member.account.dto.MemberBalanceDTO;
import com.hzs.member.account.service.ICuMemberBaseService;
import com.hzs.member.account.service.ICuMemberTradeService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.vo.ZeroElementRevokeVO;
import com.hzs.member.detail.service.ICuMemberServiceLogService;
import com.hzs.system.config.IServiceChargeServiceApi;
import com.hzs.system.config.dto.ServiceChargeDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 特殊业务-零元撤单
 **/
@RequestMapping("/manager/zeroRevoke")
@RestController
public class ZeroElementRevokeController extends BaseController {

    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private ICuMemberServiceLogService iCuMemberServiceLogService;
    @Autowired
    private ICuMemberTradeService iCuMemberTradeService;
    @Autowired
    private ICuMemberBaseService iCuMemberBaseService;

    @DubboReference
    IServiceChargeServiceApi iServiceChargeServiceApi;


    /**
     * 特殊业务-零元撤单列表
     **/
    @AccessPermissions("ZeroBuy")
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.ZERO_REVOKE, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo puCodeList(ZeroElementRevokeVO zeroElementRevokeVO) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        zeroElementRevokeVO.setPkCountry(pkCountry);
        List<ZeroElementRevokeVO> list = iCuMemberService.zeroList(zeroElementRevokeVO);
        return getDataTable(list);
    }


    /**
     * 导出
     *
     * @param response
     * @param zeroElementRevokeVO
     */
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.ZERO_REVOKE, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ZeroElementRevokeVO zeroElementRevokeVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        zeroElementRevokeVO.setPkCountry(pkCountry);
        List<ZeroElementRevokeVO> list = iCuMemberService.zeroList(zeroElementRevokeVO);
        ExcelUtil<ZeroElementRevokeVO> util = new ExcelUtil<>(ZeroElementRevokeVO.class);
        util.exportExcel(response, list, "导出零元撤单");
    }


    /**
     * 查询选择零元注册的会员
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.ZERO_REVOKE, method = EOperationMethod.SELECT)
    @GetMapping("/selected")
    public AjaxResult selected(ZeroElementRevokeVO zeroElementRevokeVO) {
        if (StringUtils.isEmpty(zeroElementRevokeVO.getPkIdListStr())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
        }
        List<ZeroElementRevokeVO> errorlist = new ArrayList<>();
        List<Long> pkIdList = Arrays.stream(zeroElementRevokeVO.getPkIdListStr().split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        zeroElementRevokeVO.setPkIdList(pkIdList);
        List<Long> list = zeroElementRevokeVO.getPkIdList();
        List<ZeroElementRevokeVO> newlist = new ArrayList<>();
        Integer pkCountry = SecurityUtils.getPkCountry();
        for (Long lo : list) {
            CuMember cm = iCuMemberService.getMemberById(lo);
            ZeroElementRevokeVO zrvo = BeanUtil.copyProperties(cm, ZeroElementRevokeVO.class);
            if (zrvo != null) {
                newlist.add(zrvo);
            }
        }
        if (CollectionUtil.isNotEmpty(newlist)) {
            for (ZeroElementRevokeVO zer : newlist) {
                //当前最大次数
                Integer approveNumber = iCuMemberServiceLogService.selectByMaxApproveNumber(zer.getPkId(),
                        EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue(), EApproveStatus.FINISH.getValue());
                zer.setChangeNumber(approveNumber + 1);
                //查询扣费金额，账户信息
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
                serviceChargeDTO.setQuantity(approveNumber + 1);
                serviceChargeDTO.setPkCountry(pkCountry);
                R<ServiceChargeDTO> serviceChargeDTOR = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                if (null == serviceChargeDTOR.getData() ||
                        null == serviceChargeDTOR.getData().getPkAccount()) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
                }
                zer.setCost(serviceChargeDTOR.getData().getCost());
                zer.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                zer.setPkAccountKey(iCuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
            }
        }
        zeroElementRevokeVO.setZeroVOList(newlist);
        zeroElementRevokeVO.setErroList(errorlist);
        return AjaxResult.success(zeroElementRevokeVO);
    }


    /**
     * 零元撤单
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.ZERO_REVOKE, method = EOperationMethod.SUBMIT)
    @PostMapping("/confirm")
    public AjaxResult confirm(@RequestBody ZeroElementRevokeVO zeroElementRevokeVO) {
        if (CollectionUtil.isEmpty(zeroElementRevokeVO.getZeroVOList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
        }
        List<ZeroElementRevokeVO> errorlist = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(zeroElementRevokeVO.getZeroVOList())) {
            List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
            if (StringUtils.isNull(zeroElementRevokeVO.getProcessType())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
            }
            Date date = new Date();
            Integer pkCountry = SecurityUtils.getPkCountry();
            zeroElementRevokeVO.setPkCountry(pkCountry);
            zeroElementRevokeVO.setPkCreator(SecurityUtils.getUserId());
            zeroElementRevokeVO.setCreationTime(date);
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            for (ZeroElementRevokeVO zrvo : zeroElementRevokeVO.getZeroVOList()) {
                Integer count = iCuMemberService.checkmsLogCount(zrvo.getPkId(), EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
                if (count > 0) {
                    zrvo.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                    errorlist.add(zrvo);
                    continue;
                }
                //当前最大次数
                Integer approveNumber = iCuMemberServiceLogService.selectByMaxApproveNumber(zrvo.getPkId(),
                        EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue(), EApproveStatus.FINISH.getValue());
                zrvo.setChangeNumber(approveNumber + 1);
                if (zeroElementRevokeVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                        zeroElementRevokeVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                    //查询扣费金额，账户信息
                    ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                    serviceChargeDTO.setType(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
                    serviceChargeDTO.setPkCountry(pkCountry);
                    serviceChargeDTO.setQuantity(approveNumber + 1);
                    R<ServiceChargeDTO> serviceChargeDTOR = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                    if (null == serviceChargeDTOR.getData() ||
                            null == serviceChargeDTOR.getData().getPkAccount()) {
                        return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
                    }
                    //接口查询金额是否足够
                    businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    businessCommissionDTO.setPkCountry(pkCountry);
                    MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                    memberAmountDTO.setPkMember(zrvo.getPkId());
                    memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                    zrvo.setCost(serviceChargeDTOR.getData().getCost());
                    zrvo.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    memberAmountDTOList.add(memberAmountDTO);
                    zeroElementRevokeVO.setMemberAmountDTOList(memberAmountDTOList);
                }
            }
            if (CollectionUtil.isNotEmpty(errorlist)) {
                return AjaxResult.error(504, ConfigMsgConstants.MEMBER_DATA_ERROR, errorlist);
            }
            businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
            if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                //接口查询金额是否足够
                List<MemberBalanceDTO> memberBalanceList = iCuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT), memberBalanceList);
                }
            }

            zeroElementRevokeVO = iCuMemberService.zeroRevokeBusiness(zeroElementRevokeVO);
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        return AjaxResult.success(zeroElementRevokeVO);
    }

    /**
     * 发起签呈 免付，需要签呈需要付费
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.ZERO_REVOKE, method = EOperationMethod.SUBMIT)
    @PostMapping("/petition")
    public AjaxResult petition(@RequestBody ZeroElementRevokeVO zeroElementRevokeVO) {
        List<ZeroElementRevokeVO> errorlist = new ArrayList<>();
        if (StringUtils.isEmpty(zeroElementRevokeVO.getZeroVOList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        if (StringUtils.isNull(zeroElementRevokeVO.getProcessType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
        }
        if (StringUtils.isNull(zeroElementRevokeVO.getSignType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SIGN_TYPE_NOT_NULL));
        }
        if (CollectionUtil.isEmpty(zeroElementRevokeVO.getUserIdList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EXAMINE_AND_APPROVE_NOT_NULL));
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        Date date = new Date();
        zeroElementRevokeVO.setPkCountry(pkCountry);
        zeroElementRevokeVO.setPkCreator(SecurityUtils.getUserId());
        zeroElementRevokeVO.setCreationTime(date);
        Set<Long> pkMemberIds = new HashSet<>();
        BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
        List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
        for (ZeroElementRevokeVO zero : zeroElementRevokeVO.getZeroVOList()) {
            if (StringUtils.isEmpty(zero.getMemberCode())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
            }
            if (StringUtils.isNull(zero.getPkId())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PKID_NOT_NULL));
            }
            Integer count = iCuMemberService.checkmsLogCount(zero.getPkId(), EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
            if (count > 0) {
                zero.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                errorlist.add(zero);
                continue;
            }
            pkMemberIds.add(zero.getPkId());

            //当前最大次数
            Integer approveNumber = iCuMemberServiceLogService.selectByMaxApproveNumber(zero.getPkId(),
                    EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue(), EApproveStatus.FINISH.getValue());
            zero.setChangeNumber(approveNumber + 1);
            if (zeroElementRevokeVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                //查询扣费金额，账户信息
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
                serviceChargeDTO.setQuantity(approveNumber + 1);
                serviceChargeDTO.setPkCountry(pkCountry);
                R<ServiceChargeDTO> serviceChargeDTOR = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                //接口查询金额是否足够
                businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                businessCommissionDTO.setPkCountry(pkCountry);
                MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                memberAmountDTO.setPkMember(zero.getPkId());
                memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                zero.setCost(serviceChargeDTOR.getData().getCost());
                zero.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                memberAmountDTOList.add(memberAmountDTO);
            }
        }
        if (CollectionUtil.isNotEmpty(errorlist)) {
            return AjaxResult.error(504, ConfigMsgConstants.MEMBER_DATA_ERROR, errorlist);
        }
        zeroElementRevokeVO.setPkMemberList(pkMemberIds);
        zeroElementRevokeVO.setMemberAmountDTOList(memberAmountDTOList);
        businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
        if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
            //接口查询金额是否足够
            if (zeroElementRevokeVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                List<MemberBalanceDTO> memberBalanceList = iCuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT), memberBalanceList);
                }
            }
        }
        iCuMemberService.zeroPetition(zeroElementRevokeVO);
        return AjaxResult.success(true);
    }

}
