package com.ruoyi.member.service.impl;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.base.service.IBaseCityService;
import com.ruoyi.common.core.domain.DlBaseEntity;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.member.domain.MemberUser;
import com.ruoyi.member.service.IMemberUserService;
import com.ruoyi.member.vo.MemberApplyVO;
import com.ruoyi.system.service.ISysUserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.member.mapper.MemberApplyMapper;
import com.ruoyi.member.domain.MemberApply;
import com.ruoyi.member.service.IMemberApplyService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 通告主认证申请Service业务层处理
 *
 * @author pqz
 * @date 2025-03-17
 */
@Service
public class MemberApplyServiceImpl extends ServiceImpl<MemberApplyMapper, MemberApply> implements IMemberApplyService {
    @Autowired
    private MemberApplyMapper memberApplyMapper;
    @Resource
    private IMemberUserService memberUserService;
    @Resource
    private IBaseCityService cityService;
    @Autowired
    private ISysUserService userService;


    /**
     * 通告主认证申请列表查询
     *
     * @param memberApply {@link MemberApplyVO}
     * @param page        分页参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.ruoyi.member.domain.MemberApply>
     * @author PQZ
     * @date 9:53 2025/3/18
     **/
    @Override
    public IPage<MemberApplyVO> queryListPage(MemberApplyVO memberApply, Page<MemberApply> page) {
        return memberApplyMapper.queryListPage(memberApply, page);
    }

    /**
     * 审核通告主
     *
     * @param memberApply {@link MemberApplyVO}
     * @author PQZ
     * @date 11:50 2025/3/18
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkMemberApply(MemberApplyVO memberApply) {
        //获取当前登录用户id
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        //当前时间
        Date nowDate = new Date();
        memberApply.setApprovalUserId(userId);
        memberApply.setApprovalTime(nowDate);
        memberApply.setApprovalUserName(sysUser.getNickName());
        updateById(memberApply);
        //通过userId更新会员表身份类型
        LambdaUpdateWrapper<MemberUser> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(MemberUser::getUserId, memberApply.getUserId())
                .eq(DlBaseEntity::getDelFlag, 0)
                .eq(MemberUser::getUserType, "01")
                .set(MemberUser::getIdentityType, memberApply.getIdentityType());
        memberUserService.update(lambdaUpdateWrapper);
    }

    /**
     * 通告主申请
     *
     * @param memberApply {@link MemberApply}
     * @author PQZ
     * @date 15:25 2025/4/10
     **/
    @Override
    @SneakyThrows
    public void toApply(MemberApply memberApply) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = userService.selectUserById(loginUser.getUserId());
        checkApply(loginUser.getUserId());
        JSONObject jsonObject = JSONObject.parseObject(memberApply.getApplyJson());
        //地址名称转换
        Long corpCityCode = jsonObject.getLong("corpCityCode");
        //地址名称转换
        Long personCityCode = jsonObject.getLong("personCityCode");
        jsonObject.put("corpCityName",cityService.getCityName(corpCityCode));
        jsonObject.put("personCityName",cityService.getCityName(personCityCode));
        String jsonString = jsonObject.toJSONString();

        memberApply.setUserId(loginUser.getUserId());
        memberApply.setNickname(sysUser.getNickName());
        memberApply.setApplyJson(jsonString);
        save(memberApply);
    }

    private void checkApply(Long userId) throws Exception {
        LambdaQueryWrapper<MemberApply> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MemberApply::getUserId,userId).eq(DlBaseEntity::getDelFlag,0)
                .eq(MemberApply::getApprovalStatus,'0');
        List<MemberApply> list = list(lambdaQueryWrapper);
        if (!list.isEmpty()) {
            throw new Exception("您有未审批通过的认证单，请耐心等待");
        }
    }


}
