package com.younike.member;

import com.younike.common.annotation.Log;
import com.younike.common.constant.Constants;
import com.younike.common.core.controller.BaseController;
import com.younike.common.core.domain.AjaxResult;
import com.younike.common.core.page.TableDataInfo;
import com.younike.common.core.redis.RedisCache;
import com.younike.common.enums.BusinessType;
import com.younike.common.utils.StringUtils;
import com.younike.common.utils.bean.BeanUtils;
import com.younike.common.utils.poi.ExcelUtil;
import com.younike.framework.config.AnonymousAccess;
import com.younike.framework.config.MemberAccess;
import com.younike.framework.web.service.JwtService;
import com.younike.system.domain.Member;
import com.younike.system.domain.MemberAddress;
import com.younike.system.domain.vo.MemberVo;
import com.younike.system.mapper.MemberMapper;
import com.younike.system.param.UserLoginParam;
import com.younike.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 会员Controller
 *
 * @author zulu.chen
 * @date 2022-01-04
 */
@Api("member用户接口")
@RestController
@RequestMapping("/member/member")
public class MemberController extends BaseController {
    @Autowired
    private IMemberService memberService;

    @Autowired
    private CoinService coinService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 外部接口获得业主收货地址
     */
    @Autowired
    private AddressService addressService;

    @Autowired
    private IMemberAddressService memberAddressService;

    @Autowired
    private JwtService jwtService;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private ISysConfigService sysConfigService;

    private static final Pattern MOBILE_PATTERN = Pattern.compile("^[1]\\d{10}$");

    private static final String DEFAULT_PHONE_CODE = "666666";

    /**
     * 会员手机号登录
     *
     * @param param
     * @return
     */
    @ApiOperation("会员手机号登录")
    @AnonymousAccess
//    @Log(title = "会员手机号登录", businessType = BusinessType.INSERT)
    @PostMapping("/login")
    public AjaxResult login(@RequestBody UserLoginParam param) {
        if (param == null || StringUtils.isEmpty(param.getPhone())) {
            return AjaxResult.error("参数错误");
        }
        // 查询会员信息
        Member member = memberMapper.selectMemberByPhone(param.getPhone());
        if (member != null) {
            Member updateMember = new Member();
            updateMember.setMemberId(member.getMemberId());
            updateMember.setLoginDate(LocalDateTime.now());
            this.memberService.updateMember(updateMember);
            //判断用户是否是锁定状态
            if("1".equals(member.getStatus())){
                // 查询平台客服电话
                String hotline = sysConfigService.selectConfigByKey("home.complaint.hotline");
                String errorMsg = "此账号已被关闭，如有疑问，请联系平台客服";
                if (StringUtils.isNotBlank(hotline)) {
                    errorMsg = errorMsg + "热线" + hotline;
                }
                return AjaxResult.error(errorMsg);
            }
        } else {
            member = new Member();
            if (StringUtils.isEmpty(param.getNickname())) {
                member.setNikeName("UXX" + new Random().nextInt(1000000000));
            } else {
                member.setNikeName(param.getNickname());
            }
            if (StringUtils.isNotEmpty(param.getAvatar())) {
                member.setAvatar(param.getAvatar());
            }
            member.setPhone(param.getPhone());
            member.setLoginDate(LocalDateTime.now());
            member.setCloseTime(LocalDateTime.now());
            int insert = this.memberService.insertMember(member);
            if (insert <= 0) {
                return AjaxResult.error("登录失败");
            }

            //根据手机号调用外部接口，查询业主收货地址（房产信息，存储到用户收货地址）
            //查询到房产信息为空的不添加收货地址
            List<MemberAddress> addressList = addressService.address(param.getPhone());
            if(addressList.size()>0){
                for (MemberAddress address :addressList ) {
                    address.setMemberId(member.getMemberId());
                    address.setName(param.getPhone());
                    if(memberAddressService.insertMemberAddress(address)<1){
                        return AjaxResult.error("登录失败,添加用户收货地址失败");
                    }
                }
            }
        }
        MemberVo memberVo = new MemberVo();
        BeanUtils.copyProperties(member, memberVo);
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, memberVo.getMemberId());
        memberVo.setToken(jwtService.createToken(claims));
        return AjaxResult.success(memberVo);
//        return memberService.login(param);
    }

    /**
     * 会员手机号验证码登录
     *
     * @param param
     * @return
     */
    @ApiOperation("会员手机号验证码登录")
    @AnonymousAccess
//    @Log(title = "会员手机号验证码登录", businessType = BusinessType.INSERT)
    @PostMapping("/codeLogin")
    public AjaxResult codeLogin(@RequestBody UserLoginParam param) {
        if (param == null || StringUtils.isEmpty(param.getPhone()) || StringUtils.isBlank(param.getCode())) {
            return AjaxResult.error("手机号或验证码不能为空!");
        }
        // 校验验证码
        if (!Objects.equals(DEFAULT_PHONE_CODE, param.getCode())) {
            Object pop = redisCache.getCacheObject(Constants.SMS_LOGIN_CODE + param.getPhone());
            if (pop == null || !pop.equals(param.getCode())) {
                return AjaxResult.error("验证码错误!");
            }
        }
        // 查询会员信息
        Member member = memberMapper.selectMemberByPhone(param.getPhone());
        if (member != null) {
            Member updateMember = new Member();
            updateMember.setMemberId(member.getMemberId());
            updateMember.setLoginDate(LocalDateTime.now());
            this.memberService.updateMember(updateMember);

            //判断用户是否是锁定状态
            if("1".equals(member.getStatus())){
                return AjaxResult.error("此账号已被关闭，如有疑问，请联系客服：电话号码。");
            }
        } else {
            member = new Member();
            member.setNikeName("UXX" + new Random().nextInt(1000000000));
            member.setPhone(param.getPhone());
            member.setLoginDate(LocalDateTime.now());
            member.setCloseTime(LocalDateTime.now());
            int insert = this.memberService.insertMember(member);
            if (insert <= 0) {
                return AjaxResult.error("登录失败");
            }
            // 根据手机号调用外部接口，查询业主收货地址（房产信息，存储到用户收货地址）
            // 查询到房产信息为空的不添加收货地址
            List<MemberAddress> addressList = addressService.address(param.getPhone());
            if (CollectionUtils.isNotEmpty(addressList)) {
                for (MemberAddress address : addressList) {
                    address.setMemberId(member.getMemberId());
                    address.setName(param.getPhone());
                    if (memberAddressService.insertMemberAddress(address) <= 0) {
                        return AjaxResult.error("登录失败,添加用户收货地址失败!");
                    }
                }
            }
        }
        MemberVo memberVo = new MemberVo();
        BeanUtils.copyProperties(member, memberVo);
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, memberVo.getMemberId());
        memberVo.setToken(jwtService.createToken(claims));
        return AjaxResult.success(memberVo);
    }

    @ApiOperation("会员一键登陆")
    @AnonymousAccess
    @Log(title = "会员一键登陆", businessType = BusinessType.OTHER)
    @PostMapping("tokenLogin")
    public AjaxResult tokenLogin(@RequestBody UserLoginParam param) {
        return memberService.tokenLogin(param);
    }


    @ApiOperation("会员发送验证码")
    @AnonymousAccess
    @GetMapping("sendCode/{param}")
    public AjaxResult sendCode(@PathVariable("param") String param) {
        if(ObjectUtils.isEmpty(param)){
            return AjaxResult.error("参数错误");
        }
        if (!MOBILE_PATTERN.matcher(param).matches()) {
            return AjaxResult.error("参数错误(手机号格式不正确)");
        }

        return memberService.sendCode(param);
    }


    /**
     * 查询会员列表
     */
    @PreAuthorize("@ss.hasPermi('member:member:list')")
    @GetMapping("/list")
    public TableDataInfo list(Member member) {
        startPage();
        List<Member> list = memberService.selectMemberList(member);
        return getDataTable(list);
    }

    /**
     * 导出会员列表
     */
    @PreAuthorize("@ss.hasPermi('member:member:export')")
    @Log(title = "会员", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Member member) {
        List<Member> list = memberService.selectMemberList(member);
        ExcelUtil<Member> util = new ExcelUtil<Member>(Member.class);
        return util.exportExcel(list, "会员数据");
    }

    /**
     * 获取会员详细信息
     */
//    @PreAuthorize("@ss.hasPermi('member:member:query')")
    @ApiOperation("获取会员详细信息")
    @MemberAccess
    @GetMapping(value = "/{memberId}")
    public AjaxResult getInfo(@PathVariable("memberId") Long memberId) {
        //参数验证
        if(memberId==null){
            return AjaxResult.error("参数错误");
        }
        return AjaxResult.success(memberService.selectMemberByMemberId(memberId));
    }

    /**
     * 新增会员
     */
    @PreAuthorize("@ss.hasPermi('member:member:add')")
    @Log(title = "会员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Member member) {
        return toAjax(memberService.insertMember(member));
    }

    /**
     * 修改会员
     */
//    @PreAuthorize("@ss.hasPermi('member:member:edit')")
//    @Log(title = "会员", businessType = BusinessType.UPDATE)
    @PutMapping
    @MemberAccess
    @ApiOperation("编辑会员信息")
    public AjaxResult edit(@RequestBody Member member) {


        //参数验证
        if(ObjectUtils.isEmpty(member)){
            return AjaxResult.error("参数错误");
        }
        //验证会员d是否为空
        if(!StringUtils.isNotNull(member.getMemberId())){
            return AjaxResult.error("参数错误(会员id不能为空)");
        }
        return toAjax(memberService.updateMember(member));
    }

    /**
     * 删除会员
     */
    @PreAuthorize("@ss.hasPermi('member:member:remove')")
    @Log(title = "会员", businessType = BusinessType.DELETE)
	@DeleteMapping("/{memberIds}")
    public AjaxResult remove(@PathVariable Long[] memberIds) {
        return toAjax(memberService.deleteMemberByMemberIds(memberIds));
    }

    /**
     * 获取用户优金豆数量
     */
    @ApiOperation("获取会员详细信息")
    @MemberAccess
    @GetMapping(value = "getCoin/{phone}")
    public AjaxResult getCoin(@PathVariable("phone") String phone) {
        //参数验证
        if(StringUtils.isEmpty(phone)){
            return AjaxResult.error("参数错误");
        }
        //根据用户手机号查询优金豆数量
       String coin = coinService.getCoin(phone);


        return AjaxResult.success("查询成功",coin);
    }
}
