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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
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.core.utils.TransactionUtils;
import com.hzs.member.account.service.ICuMemberBaseService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.vo.NotActivePointVO;
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;

/**
 * @description: 特殊业务-未激活点位
 * @author: zhang jing
 * @date: 2022/12/29 11:39
 * @param:
 * @return:
 **/
@RequestMapping("/manager/notActive")
@RestController
public class NotActivePointController extends BaseController {

    @Autowired
    private ICuMemberService cuMemberService;

    @Autowired
    public void setCuMemberService(ICuMemberService cuMemberService) {
        this.cuMemberService = cuMemberService;
    }

    @Autowired
    private ICuMemberServiceLogService memberServiceLogService;
    @DubboReference
    private IServiceChargeServiceApi serviceChargeServiceApi;
    @Autowired
    private ICuMemberBaseService cuMemberBaseService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;


    /**
     * @description: 特殊业务-未激活点位列表
     * @author: zhang jing
     * @date: 2022/11/17 15:39
     * @param: []
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.NOT_ACTIVE_POINT, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo puCodeList(NotActivePointVO NotActivePointVO) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        NotActivePointVO.setPkCountry(pkCountry);
        List<NotActivePointVO> list = cuMemberService.notActiveList(NotActivePointVO);
        return getDataTable(list);
    }


    /**
     * 导出
     *
     * @param response
     * @param NotActivePointVO
     */
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.NOT_ACTIVE_POINT, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, NotActivePointVO NotActivePointVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        NotActivePointVO.setPkCountry(pkCountry);
        List<NotActivePointVO> list = cuMemberService.notActiveList(NotActivePointVO);
        if (CollectionUtil.isNotEmpty(list)) {
            // 获取需要翻译的枚举翻译
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EPayStatus.values());
            Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE,
                    EnumsPrefixConstants.KEY_AWARD);
            list.forEach(itm -> {
                //注册等级key
                itm.setPkSettleGradeVal(transactionMap1.get(itm.getPkSettleGrade()));
                itm.setPkAwardsVal(transactionMap1.get(itm.getPkAwards()));
                itm.setPayStatusVal(transactionMap.get(EnumsPrefixConstants.PAY_STATUS + itm.getPayStatus()));
            });
        }
        ExcelUtil<NotActivePointVO> util = new ExcelUtil<>(NotActivePointVO.class);
        util.exportExcel(response, list, "导出未激活点位");
    }


    /**
     * @description: 查询选择零元注册的会员
     * @author: zhang jing
     * @date: 2023/3/27 17:52
     * @param: [updateCodeVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.NOT_ACTIVE_POINT, method = EOperationMethod.SELECT)
    @GetMapping("/selected")
    public AjaxResult selected(NotActivePointVO NotActivePointVO) {
        if (StringUtils.isEmpty(NotActivePointVO.getPkIdListStr())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
        }
        List<Long> pkIdList = Arrays.stream(NotActivePointVO.getPkIdListStr().split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        NotActivePointVO.setPkIdList(pkIdList);
        List<Long> list = NotActivePointVO.getPkIdList();
        List<NotActivePointVO> newlist = new ArrayList<>();
        Integer pkCountry = SecurityUtils.getPkCountry();
        for (Long lo : list) {
            CuMember cm = cuMemberService.getMemberById(lo);
            NotActivePointVO zrvo = BeanUtil.copyProperties(cm, NotActivePointVO.class);
            if (zrvo != null) {
                newlist.add(zrvo);
            }
        }
        if (CollectionUtil.isNotEmpty(newlist)) {
            for (NotActivePointVO zer : newlist) {
                //当前最大次数
                Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(zer.getPkId(),
                        EApprovalBusiness.NOT_ACTIVE_POINT.getValue(), EApproveStatus.FINISH.getValue());
                zer.setChangeNumber(approveNumber + 1);
                //查询扣费金额，账户信息
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.NOT_ACTIVE_POINT.getValue());
                serviceChargeDTO.setQuantity(approveNumber + 1);
                serviceChargeDTO.setPkCountry(pkCountry);
                R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.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(cuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
            }
        }
        return AjaxResult.success(newlist);
    }


    /**
     * @description: 未激活点位
     * @author: zhang jing
     * @date: 2022/12/30 10:22
     * @param: [postageParams]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.NOT_ACTIVE_POINT, method = EOperationMethod.SUBMIT)
    @PostMapping("/confirm")
    public AjaxResult confirm(@RequestBody NotActivePointVO notActivePointVO) {
        if (CollectionUtil.isEmpty(notActivePointVO.getNotActiveVOList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
        }
        List<NotActivePointVO> errorlist = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(notActivePointVO.getNotActiveVOList())) {
            if (StringUtils.isNull(notActivePointVO.getProcessType())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
            }
            Date date = new Date();
            Long userID = SecurityUtils.getUserId();
            Integer pkCountry = SecurityUtils.getPkCountry();
            notActivePointVO.setPkCountry(pkCountry);
            notActivePointVO.setPkCreator(userID);
            notActivePointVO.setCreationTime(date);
            for (NotActivePointVO zrvo : notActivePointVO.getNotActiveVOList()) {
                if (cuMemberService.checkLowerMember(zrvo.getPkId())) {
                    //伞下存在推荐或安置
                    zrvo.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UMBRELLA_VALUE));
                }
                Integer count = cuMemberService.checkmsLogCount(zrvo.getPkId(), EApprovalBusiness.NOT_ACTIVE_POINT.getValue());
                if (count > 0) {
                    zrvo.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                    errorlist.add(zrvo);
                    continue;
                }
                zrvo.setChangeNumber(1);
            }
            if (CollectionUtil.isNotEmpty(errorlist)) {
                return AjaxResult.error(504, ConfigMsgConstants.MEMBER_DATA_ERROR, errorlist);
            }
            notActivePointVO = cuMemberService.notActiveRevokeBusiness(notActivePointVO);
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        return AjaxResult.success(notActivePointVO);
    }

    /**
     * @description: 发起签呈 免付，需要签呈
     * @author: zhang jing
     * @date: 2023/3/4 11:06
     * @param: [updateCodeVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.NOT_ACTIVE_POINT, method = EOperationMethod.SUBMIT)
    @PostMapping("/petition")
    public AjaxResult petition(@RequestBody NotActivePointVO notActivePointVO) {
        List<NotActivePointVO> errorlist = new ArrayList<>();
        if (StringUtils.isEmpty(notActivePointVO.getNotActiveVOList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        if (StringUtils.isNull(notActivePointVO.getProcessType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
        }
        if (StringUtils.isNull(notActivePointVO.getSignType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SIGN_TYPE_NOT_NULL));
        }
        if (CollectionUtil.isEmpty(notActivePointVO.getUserIdList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EXAMINE_AND_APPROVE_NOT_NULL));
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        notActivePointVO.setPkCountry(pkCountry);
        notActivePointVO.setPkCreator(userID);
        notActivePointVO.setCreationTime(date);
        Set<Long> pkMemberIds = new HashSet<>();
        for (NotActivePointVO zero : notActivePointVO.getNotActiveVOList()) {
            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));
            }
            if (cuMemberService.checkLowerMember(zero.getPkId())) {
                //伞下存在推荐或安置
                zero.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UMBRELLA_VALUE));
            }
            Integer count = cuMemberService.checkmsLogCount(zero.getPkId(), EApprovalBusiness.NOT_ACTIVE_POINT.getValue());
            if (count > 0) {
                zero.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                errorlist.add(zero);
                continue;
            }
            pkMemberIds.add(zero.getPkId());
        }
        if (CollectionUtil.isNotEmpty(errorlist)) {
            return AjaxResult.error(504, ConfigMsgConstants.MEMBER_DATA_ERROR, errorlist);
        }
        notActivePointVO.setPkMemberList(pkMemberIds);

        cuMemberService.notActivePetition(notActivePointVO);
        return AjaxResult.success(true);
    }

}
