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

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
import com.hzs.common.core.domain.FileResult;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.DateUtils;
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.base.CuMember;
import com.hzs.common.domain.member.detail.CuMemberChangeLog;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.base.param.ForgetPasswordParam;
import com.hzs.member.base.param.MemberDataParam;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.service.IMemberInfoService;
import com.hzs.common.core.utils.UploadFileUtil;
import com.hzs.member.base.vo.*;
import com.hzs.member.sms.service.IApiCodeService;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 会员控制器
 */
@Slf4j
@RequestMapping("/api/member")
@RestController
public class ApiMemberController extends BaseController {

    @Autowired
    private ITransactionCommonService iTransactionCommonService;
    @Autowired
    private IMemberInfoService iMemberInfoService;
    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private IApiCodeService iApiCodeService;

    @DubboReference
    IGradeServiceApi gradeServiceApi;
    @DubboReference
    ICurrencyServiceApi currencyServiceApi;

//    /**
//     * 获取登录会员信息
//     *
//     * @return
//     */
//    @GetMapping("/get-info")
//    public AjaxResult getInfo() {
//        MemberInfoVO memberInfo = iMemberInfoService.getMemberInfo(SecurityUtils.getUserId());
//        if (null == memberInfo) {
//            return AjaxResult.error();
//        }
//        return AjaxResult.success(memberInfo);
//    }

    /**
     * 更新个人资料（昵称）
     *
     * @param param
     * @return
     */
    @PutMapping("/update-data")
    public AjaxResult updateData(@RequestBody MemberDataParam param) {
        if (StringUtils.isEmpty(param.getNickName())) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        Long memberId = SecurityUtils.getUserId();
        CuMember member = iCuMemberService.getMemberById(memberId);
        if (null == member) {
            // 会员不存在
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
        }

        // 会员修改信息
        CuMember cuMember = new CuMember();
        cuMember.setPkId(memberId);
        cuMember.setNickName(param.getNickName());
        cuMember.setPkModified(memberId);
        cuMember.setModifiedTime(new Date());
        // 会员修改记录信息
        CuMemberChangeLog cuMemberChangeLog = CuMemberChangeLog.builder()
                .pkMember(memberId)
                .changeType(EMemberChangeType.NICK_NAME.getValue())
                .changeFront(member.getNickName())
                .changeAfter(param.getNickName())
                .build();
        iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));
        return AjaxResult.success();
    }

    /**
     * 更新头像
     *
     * @param file
     * @return
     */
    @PostMapping("/update-head")
    public AjaxResult updateHead(MultipartFile file) {
        if (null == file) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        Long memberId = SecurityUtils.getUserId();
        CuMember member = iCuMemberService.getMemberById(memberId);
        if (null == member) {
            // 会员不存在
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
        }

        FileResult fileResult = UploadFileUtil.upload(file, "head");
        if (null != fileResult) {
            // 会员修改信息
            CuMember cuMember = new CuMember();
            cuMember.setPkId(memberId);
            cuMember.setHeadPath(fileResult.getUrl());
            cuMember.setPkModified(memberId);
            cuMember.setModifiedTime(new Date());
            // 会员修改记录信息
            CuMemberChangeLog cuMemberChangeLog = CuMemberChangeLog.builder()
                    .pkMember(memberId)
                    .changeType(EMemberChangeType.HEAD.getValue())
                    .changeFront(member.getHeadPath())
                    .changeAfter(fileResult.getUrl())
                    .build();
            iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));
            return AjaxResult.success(fileResult);
        }
        return AjaxResult.error();
    }

    /**
     * 更新密码
     *
     * @param param
     * @return
     */
    @PutMapping("/update-password")
    public AjaxResult updatePassword(@RequestBody MemberDataParam param) {
        if (StringUtils.isEmpty(param.getOldPassword())
                || StringUtils.isAllEmpty(param.getLoginPassword(), param.getPayPassword())) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        Long memberId = SecurityUtils.getUserId();
        CuMember member = iCuMemberService.getMemberById(memberId);
        if (null == member) {
            // 会员不存在
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
        }

        if (StringUtils.isNotEmpty(param.getLoginPassword())) {
            // 修改登录密码
            if (SecurityUtils.matchesPassword(param.getOldPassword(), member.getLoginPwd())) {
                // 会员修改信息
                CuMember cuMember = new CuMember();
                cuMember.setPkId(memberId);
                cuMember.setLoginPwd(SecurityUtils.encryptPassword(param.getLoginPassword()));
                cuMember.setLoginPassword(param.getLoginPassword());
                cuMember.setPkModified(memberId);
                cuMember.setModifiedTime(new Date());
                // 会员修改记录信息
                CuMemberChangeLog cuMemberChangeLog = CuMemberChangeLog.builder()
                        .pkMember(memberId)
                        .changeType(EMemberChangeType.LOGIN_PWD.getValue())
                        .changeFront(member.getLoginPassword())
                        .changeAfter(param.getLoginPassword())
                        .build();
                iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));
                return AjaxResult.success();
            } else {
                // 旧密码错误
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PASSWORD_ERROR));
            }
        } else if (StringUtils.isNotEmpty(param.getPayPassword())) {
            // 修改支付密码
            if (SecurityUtils.matchesPassword(param.getOldPassword(), member.getPayPwd())) {
                // 会员修改信息
                CuMember cuMember = new CuMember();
                cuMember.setPkId(memberId);
                cuMember.setPayPwd(SecurityUtils.encryptPassword(param.getPayPassword()));
                cuMember.setPayPassword(param.getPayPassword());
                cuMember.setPkModified(memberId);
                cuMember.setModifiedTime(new Date());
                // 会员修改记录信息
                CuMemberChangeLog cuMemberChangeLog = CuMemberChangeLog.builder()
                        .pkMember(memberId)
                        .changeType(EMemberChangeType.PAY_PWD.getValue())
                        .changeFront(member.getPayPassword())
                        .changeAfter(param.getPayPassword())
                        .build();
                iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));
                return AjaxResult.success();
            } else {
                // 旧密码错误
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PASSWORD_ERROR));
            }
        }
        return AjaxResult.error();
    }

    /**
     * 更新邮箱
     *
     * @param param
     * @return
     */
    @Deprecated
    @PutMapping("/update-email")
    public AjaxResult updateEmail(@RequestBody MemberDataParam param) {
        return AjaxResult.success();
    }

    /**
     * 忘记密码更新
     *
     * @param param
     * @return
     */
    @RepeatSubmitSimple
    @PutMapping("/forget-password")
    public AjaxResult forgetPassword(@Valid @RequestBody ForgetPasswordParam param) {
        String loginPassword = param.getLoginPassword();

        List<CuMemberExt> cuMemberList = iCuMemberService.listMemberByPhone(param.getPhone());
        if (CollectionUtil.isEmpty(cuMemberList)) {
            return AjaxResult.error("会员联系方式不存在");
        }

        CuMemberExt cuMemberExt = null;
        for (CuMemberExt tmpMember : cuMemberList) {
            if (tmpMember.getMemberCode().equals(param.getMemberCode())) {
                cuMemberExt = tmpMember;
            }
        }
        if (null == cuMemberExt) {
            return AjaxResult.error("会员信息不存在");
        }
        Long memberId = cuMemberExt.getPkId();

        // 校验短信验证码是否有效
        String checkSmsStr = iApiCodeService.checkRecoverCode(param.getPhone(), param.getCode());
        if (null != checkSmsStr) {
            return AjaxResult.error(checkSmsStr);
        }

        // 会员修改信息
        CuMember cuMember = new CuMember();
        cuMember.setPkId(memberId);
        cuMember.setLoginPwd(SecurityUtils.encryptPassword(loginPassword));
        cuMember.setLoginPassword(loginPassword);
        cuMember.setPkModified(memberId);
        cuMember.setModifiedTime(new Date());
        // 会员修改记录信息
        CuMemberChangeLog cuMemberChangeLog = CuMemberChangeLog.builder()
                .pkMember(memberId)
                .changeType(EMemberChangeType.LOGIN_PWD.getValue())
                .changeFront(cuMemberExt.getLoginPassword())
                .changeAfter(loginPassword)
                .build();
        iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));

        return AjaxResult.success();
    }

    /**
     * 忘记支付密码更新
     *
     * @param param 入参
     * @return
     */
    @RepeatSubmitSimple
    @PutMapping("/forget-pay-password")
    public AjaxResult forgetPayPassword(@RequestBody MemberDataParam param) {
        if (StringUtils.isAnyEmpty(param.getCode(), param.getPayPassword())) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        String payPassword = param.getPayPassword();
        CuMemberExt cuMemberExt = iCuMemberService.getMemberById(SecurityUtils.getUserId());
        if (null == cuMemberExt) {
            // 会员不存在
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_EXIST));
        }
        Long memberId = cuMemberExt.getPkId();

        // 校验短信验证码是否有效
        String checkSmsStr = iApiCodeService.checkPayPasswordCode(cuMemberExt.getPhone(), param.getCode());
        if (null != checkSmsStr) {
            return AjaxResult.error(checkSmsStr);
        }

        // 会员修改信息
        CuMember cuMember = new CuMember();
        cuMember.setPkId(memberId);
        cuMember.setPayPwd(SecurityUtils.encryptPassword(payPassword));
        cuMember.setPayPassword(payPassword);
        cuMember.setPkModified(memberId);
        cuMember.setModifiedTime(new Date());
        // 会员修改记录信息
        CuMemberChangeLog cuMemberChangeLog = CuMemberChangeLog.builder()
                .pkMember(memberId)
                .changeType(EMemberChangeType.PAY_PWD.getValue())
                .changeFront(cuMemberExt.getPayPassword())
                .changeAfter(payPassword)
                .build();
        iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));


        return AjaxResult.success();
    }

    /**
     * 查询会员注册信息
     *
     * @param orderCode 订单编号
     * @return
     */
    @RepeatSubmitSimple
    @GetMapping("/register-order/{orderCode}")
    public AjaxResult registerOrder(@PathVariable("orderCode") String orderCode) {
        CuMemberExt cuMemberExt = iCuMemberService.queryRegisterOrder(orderCode, SecurityUtils.getUserId());
        if (null == cuMemberExt) {
            return AjaxResult.error("注册会员失败，请联系客服处理");
        }

        return AjaxResult.success(MemberShare.builder()
                .memberName(cuMemberExt.getMemberName())
                .memberCode(cuMemberExt.getMemberCode())
                .phone(cuMemberExt.getPhone())
                .loginPassword(cuMemberExt.getLoginPassword())
                .payPassword(cuMemberExt.getPayPassword())
                .build());
    }

    /**
     * 会员 推荐列表（直推列表）
     *
     * @return
     */
    @GetMapping("parent-list")
    public TableDataInfo parentList(String memberCode, String memberName, Date startCreateTime, Date endCreateTime, String memberInfo) {
        Long memberId = SecurityUtils.getUserId();

        // 查询等级
        Integer pkCountry = SecurityUtils.getPkCountry();
        R<List<GradeDTO>> grderDate = gradeServiceApi.findAll();
        List<GradeDTO> grderList = grderDate.getData();

        if (endCreateTime != null) {
            endCreateTime = DateUtils.getEndTime(endCreateTime);
        }

        startPage();
        List<ParentMemberVo> list = iCuMemberService.parentList(memberId, memberCode, memberName, startCreateTime, endCreateTime, memberInfo);

        if (CollectionUtil.isNotEmpty(list)) {
            Map<Integer, String> transactionMap = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE);
            R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
            BigDecimal inExchangeRate = currency.getData().getInExchangeRate();

            for (ParentMemberVo cuMember : list) {
                cuMember.setMemberCode(cuMember.getMemberCode());
                cuMember.setMemberName(cuMember.getMemberName());

                for (GradeDTO gradeDTO : grderList) {
                    if (gradeDTO.getPkId().equals(cuMember.getPkRegisterGrade())) {
                        cuMember.setPkRegisterGradeStr(transactionMap.get(gradeDTO.getPkTransaction()));
                    }
                }
                for (GradeDTO gradeDTO : grderList) {
                    if (gradeDTO.getPkId().equals(cuMember.getPkSettleGrade())) {
                        cuMember.setPkSettleGradeStr(transactionMap.get(gradeDTO.getPkTransaction()));
                    }
                }
                if (pkCountry.equals(CountryConstants.CHINA_COUNTRY)) {
                    if (cuMember.getConsumeAchieve() != null) {
                        cuMember.setConsumeAchieve(cuMember.getConsumeAchieve().multiply(inExchangeRate));
                    }
                }
            }
        }
        return getDataTable(list);
    }

}
