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

import cn.hutool.core.collection.CollUtil;
import com.hzs.common.core.annotation.AccessPermissions;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.MemberFieldConstants;
import com.hzs.common.core.constant.msg.FinanceMsgConstants;
import com.hzs.common.core.enums.*;
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.ext.CuMemberAccountExt;
import com.hzs.common.domain.system.sys.SysUser;
import com.hzs.common.security.service.UserTokenService;
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.CuMemberFrozenParam;
import com.hzs.member.account.dto.CuMemberRechargeAccountParam;
import com.hzs.member.account.service.ICuMemberAccountService;
import com.hzs.member.account.service.ICuMemberBaseService;
import com.hzs.member.account.service.ICuMemberRechargeService;
import com.hzs.member.account.vo.*;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.system.sys.dto.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 冻结金额
 *
 * @author hzs
 * @since 2022-09-08
 */
@RestController
@RequestMapping("/manager/frozen")
public class CuMemberFrozenAmountController extends BaseController {

    @Autowired
    ICuMemberRechargeService cuMemberRechargeService;

    @Autowired
    ICuMemberService cuMemberService;

    @Autowired
    ICuMemberBaseService baseService;

    @Autowired
    ICuMemberAccountService cuMemberAccountService;

    @Autowired
    private UserTokenService userTokenService;

    @Autowired
    ITransactionCommonService iTransactionCommonService;

    /**
     * 根据用户编号查询用户余额
     *
     * @param cuMemberBalanceVO 用户编号
     * @return AjaxResult
     */
    @Log(module = EOperationModule.RECHARGE, business = EOperationBusiness.FREEZE, method = EOperationMethod.SELECT, remark = "查余额")
    @PostMapping("/balance-show")
    public AjaxResult showMemberBalance(@RequestBody CuMemberBalanceVO cuMemberBalanceVO) {
        List<Integer> accountTypes = cuMemberBalanceVO.getAccountTypes();
        String memberCode = cuMemberBalanceVO.getMemberCode();
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (CollUtil.isEmpty(accountTypes)) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.SELECT_WALLET_TYPE));
        }
        Assert.notNull(memberCode, TransactionUtils.getContent(FinanceMsgConstants.USER_NUMBER_CANNOT_EMPTY));
        List<CuMemberRechargeAccountParam> accountParams = cuMemberAccountService.queryMemberAccountByMemberCode(memberCode, accountTypes, pkCountry);
        //页面是否显示禁止账户
        if (CollUtil.isNotEmpty(accountParams)) {
            for (CuMemberRechargeAccountParam param : accountParams) {
                getIsShowAccount(param);
            }
        }
        return AjaxResult.success(accountParams);

    }


    /**
     * 获取是否显示禁止的账户信息
     *
     * @param param 入参
     * @return CuMemberRechargeAccountParam
     */

    private CuMemberRechargeAccountParam getIsShowAccount(CuMemberRechargeAccountParam param) {
        Integer accountValueById = baseService.getAccountValueById(param.getPkAccount());
        param.setIsShowLockConsume(EYesNo.YES.getIntValue());
        if (accountValueById.equals(EAccount.BONUS.getValue())) {
            param.setIsShowLockTransfer(EYesNo.YES.getIntValue());
            param.setIsShowLockWithdraw(EYesNo.YES.getIntValue());
        } else if (accountValueById > EAccount.BONUS.getValue()) {
            param.setIsShowLockTransfer(EYesNo.NO.getIntValue());
            param.setIsShowLockWithdraw(EYesNo.NO.getIntValue());
        } else {
            param.setIsShowLockTransfer(EYesNo.YES.getIntValue());
            param.setIsShowLockWithdraw(EYesNo.NO.getIntValue());
        }
        return param;
    }

    /**
     * 发起签呈显示
     *
     * @param memberFrozenParam 冻结参数
     * @return AjaxResult
     */
    @Log(module = EOperationModule.RECHARGE, business = EOperationBusiness.FREEZE, method = EOperationMethod.SELECT, remark = "发起签呈")
    @PostMapping("/show-frozen-petition")
    public AjaxResult showMemberPetition(@RequestBody CuMemberFrozenParam memberFrozenParam) {
        memberFrozenParam.setPkCountry(SecurityUtils.getPkCountry());
        SysUser sysUser = userTokenService.getLoginUser().getLoginSysUser();
        memberFrozenParam.setSysUser(sysUser);
        return AjaxResult.success(cuMemberAccountService.showFrozenAmountPetition(memberFrozenParam));
    }

    /**
     * 单笔冻结账户金额
     *
     * @param memberFrozenParam 账户冻结信息参数
     * @return AjaxResult
     */
    @Log(module = EOperationModule.RECHARGE, business = EOperationBusiness.FREEZE, method = EOperationMethod.INSERT, remark = "单笔账户冻结")
    @PostMapping("/frozen-amount")
    public AjaxResult frozenAmount(@RequestBody CuMemberFrozenParam memberFrozenParam) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        LoginUser loginUser = userTokenService.getLoginUser();
        List<String> memberCodes = memberFrozenParam.getMemberCodes();
        if (CollUtil.isEmpty(memberCodes)) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.USER_NUMBER_CANNOT_EMPTY));
        }
        List<Long> pkMembers = cuMemberAccountService.selectPkMembersByMemberCode(memberCodes, pkCountry);
        if (CollUtil.isEmpty(pkMembers)) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.ACCOUNT_INFORMATION_NOT_EXIS));
        }
        memberFrozenParam.setPkCountry(pkCountry);
        memberFrozenParam.setPkMembers(pkMembers);
        memberFrozenParam.setLoginUser(loginUser);
        return toAjax(cuMemberAccountService.frozenAmount(memberFrozenParam));
    }


    /**
     * 批量冻结账户金额
     *
     * @param memberFrozenParam 账户冻结信息参数
     * @return AjaxResult
     */
    @Log(module = EOperationModule.RECHARGE, business = EOperationBusiness.FREEZE, method = EOperationMethod.INSERT, remark = "批量账户冻结")
    @PostMapping("/batch-frozen-amount")
    public AjaxResult batchFrozenAmount(@RequestBody CuMemberFrozenParam memberFrozenParam) {
        LoginUser loginUser = userTokenService.getLoginUser();
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<String> memberCodes = memberFrozenParam.getMemberCodes();
        if (CollUtil.isEmpty(memberCodes)) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.USER_NUMBER_CANNOT_EMPTY));
        }

        List<Long> pkMembers = cuMemberAccountService.selectPkMembersByMemberCode(memberCodes, SecurityUtils.getPkCountry());
        if (CollUtil.isNotEmpty(pkMembers) && pkMembers.size() != memberCodes.size()) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.SUBMITTED_MEMBERS_NOT_MATCH_DATABASE));
        }
        memberFrozenParam.setPkMembers(pkMembers);
        memberFrozenParam.setLoginUser(loginUser);
        memberFrozenParam.setPkCountry(pkCountry);
        return toAjax(cuMemberAccountService.frozenAmount(memberFrozenParam));
    }


    /**
     * 批量导入冻结账户
     *
     * @param file
     * @return AjaxResult
     * @throws Exception
     */
    @PostMapping("/import-member-code")
    @Log(module = EOperationModule.RECHARGE, business = EOperationBusiness.FREEZE, method = EOperationMethod.IMPORT)
    public AjaxResult importMemberCode(MultipartFile file) throws Exception {
        ExcelUtil<TemplateVO> util = new ExcelUtil<>(TemplateVO.class);
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<TemplateVO> templateVOList = util.importExcel(file.getInputStream(), 0);
        if (CollUtil.isEmpty(templateVOList)) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.RECHAGER_IMPORT_DATA_ERROR));
        }
        List<String> memberCodes = templateVOList.stream().map(TemplateVO::getMemberCode).collect(Collectors.toList());
        List<CuMemberWalletDetailVO> memberAccountVOList = cuMemberAccountService.queryMemberAccountAllByMemberCodes(memberCodes, pkCountry);
        return AjaxResult.success(memberAccountVOList);
    }


    /**
     * 下载模板
     *
     * @return
     */
    @PostMapping("/download-template")
    @Log(module = EOperationModule.RECHARGE, business = EOperationBusiness.FREEZE, method = EOperationMethod.EXPORT, remark = "下载模板")
    public void downloadTemplate(HttpServletResponse response) {
        List<TemplateVO> list = new ArrayList<>();
        ExcelUtil<TemplateVO> util = new ExcelUtil<>(TemplateVO.class);
        util.exportExcel(response, list, TransactionUtils.getContent(FinanceMsgConstants.FREEZE_TEMPLATE));
    }

    /**
     * 冻结明细
     *
     * @param cuMemberAccountVO 查询入参
     * @return TableDataInfo
     */
    @AccessPermissions("FreezeDetail")
    @Log(module = EOperationModule.FREEZE_DETAIL, business = EOperationBusiness.FREEZE_DETAIL, method = EOperationMethod.SELECT)
    @PostMapping("/frozen-list")
    public TableDataInfo frozenAmountList(@RequestBody CuMemberAccountVO cuMemberAccountVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        cuMemberAccountVO.setPkCountry(pkCountry);
        startPage();
        Object[] objects = cuMemberAccountService.queryMemberAccountByMemberCodeAndName(cuMemberAccountVO);
        TableDataInfo tableDataInfo = getDataTable((List<CuMemberAccountExt>) objects[0]);
        tableDataInfo.setRows((List<CuMemberAccountExtVO>) objects[1]);
        return tableDataInfo;
    }


    /**
     * 冻结明细列表导出
     *
     * @param response          响应
     * @param cuMemberAccountVO 查询入参
     */
    @Log(module = EOperationModule.FREEZE_DETAIL, business = EOperationBusiness.FREEZE_DETAIL, method = EOperationMethod.EXPORT)
    @PostMapping("/frozen-export")
    public void export(HttpServletResponse response, CuMemberAccountVO cuMemberAccountVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        cuMemberAccountVO.setPkCountry(pkCountry);
        List<CuMemberAccountExportVO> memberAccountExtVOList = cuMemberAccountService.selectFrozenAmountExport(cuMemberAccountVO);
        // 列控制需
        ExcelUtil<CuMemberAccountExportVO> util = new ExcelUtil<>(CuMemberAccountExportVO.class, getShowField(cuMemberAccountVO));
        util.exportExcel(response, memberAccountExtVOList, "冻结金额导出");
    }

    /**
     * 根据前台提交的账号id返回显示字段
     *
     * @param cuMemberAccountVO 查询入参
     * @return List<String>
     */
    private List<String> getShowField(CuMemberAccountVO cuMemberAccountVO) {
        List<Integer> selectedPkAccounts = cuMemberAccountVO.getPkAccounts();
        List<String> fields = new ArrayList<>();
        fields.add("memberCode");
        fields.add("memberName");
        if (CollUtil.isNotEmpty(selectedPkAccounts)) {
            for (Integer accountValue : selectedPkAccounts) {
                fields.add(MemberFieldConstants.ACCOUNT + accountValue);
                fields.add(MemberFieldConstants.AVAILABLE_ACCOUNT + accountValue);
                if (accountValue < 11) {
                    fields.add(MemberFieldConstants.LOCK_ACCOUNT + accountValue);
                    fields.add(MemberFieldConstants.LOCK_TRANSFER_ACCOUNT + accountValue);
                }

                fields.add(MemberFieldConstants.SETTLE_ACCOUNT + accountValue);
                fields.add(MemberFieldConstants.SETTLE_AVAILABLE_ACCOUNT + accountValue);
                if (accountValue < 11) {
                    fields.add(MemberFieldConstants.LOCK_SETTLE_ACCOUNT + accountValue);
                    fields.add(MemberFieldConstants.LOCK_SETTLE_TRANSFER_ACCOUNT + accountValue);
                }
                if (accountValue == 4) {
                    fields.add(MemberFieldConstants.WITHDRAW_ACCOUNT + accountValue);
                    fields.add(MemberFieldConstants.LOCK_WITHDRAW_ACCOUNT + accountValue);
                }
            }
        }
        return fields;
    }


}
