package com.ruoyi.cai.manager;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.cai.domain.*;
import com.ruoyi.cai.dto.app.query.AccountAliBankCardRes;
import com.ruoyi.cai.dto.app.query.AnchorUpdateReq;
import com.ruoyi.cai.dto.app.query.UserUpdateReq;
import com.ruoyi.cai.dto.app.vo.AnchorVo;
import com.ruoyi.cai.dto.app.vo.CurrentUserInfoVo;
import com.ruoyi.cai.dto.app.vo.user.UserAccountVo;
import com.ruoyi.cai.dto.app.vo.user.UserAlbumDTO;
import com.ruoyi.cai.dto.app.vo.user.UserCountVo;
import com.ruoyi.cai.service.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.BeanConvertUtil;
import com.ruoyi.yunxin.client.ImUserRefClient;
import com.ruoyi.yunxin.req.UpdateUinfoReq;
import com.ruoyi.yunxin.resp.YxCommonR;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@Slf4j
public class CurrentUserManager {
    @Autowired
    private UserService userService;
    @Autowired
    private AnchorService anchorService;
    @Autowired
    private UserCountService userCountService;
    @Autowired
    private UserAlbumService userAlbumService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private AccountBankcardService accountBankcardService;
    @Resource
    private ImUserRefClient userClient;
    @Autowired
    private CitysService citysService;

    public CurrentUserInfoVo currentInfo() {
        Long userId = LoginHelper.getUserId();
        User user = userService.getById(userId);
        CurrentUserInfoVo res = BeanConvertUtil.convertTo(user, CurrentUserInfoVo::new);
        Anchor anchor = anchorService.getByUserId(userId);
        res.setOpenVideoStatus(anchor.getOpenVideoStatus());
        UserCount userCount = userCountService.getByUserId(userId);
        res.setUserCount(BeanConvertUtil.convertTo(userCount, UserCountVo::new));
        Account account = accountService.getByUserId(userId);
        res.setUserAccount(BeanConvertUtil.convertTo(account, UserAccountVo::new));
        List<UserAlbum> userAlbums = userAlbumService.listByUserId(userId);
        res.setUserAlbumList(BeanConvertUtil.convertListTo(userAlbums, UserAlbumDTO::new));
        return res;
    }

    public UserAccountVo currentAccount(){
        Long userId = LoginHelper.getUserId();
        Account account = accountService.getByUserId(userId);
        return BeanConvertUtil.convertTo(account,UserAccountVo::new);
    }

    public AnchorVo anchorInfo() {
        Long userId = LoginHelper.getUserId();
        Anchor anchor = anchorService.getByUserId(userId);
        return BeanConvertUtil.convertTo(anchor,AnchorVo::new);
    }

    public boolean anchorUpdate(AnchorUpdateReq anchorUpdate) {
        anchorUpdate.setUserId(LoginHelper.getUserId());
        boolean updateFlag = false;
        LambdaUpdateWrapper<Anchor> update =
                Wrappers.lambdaUpdate(Anchor.class).eq(Anchor::getUserId, anchorUpdate.getUserId());
        if(anchorUpdate.getPrice() != null){
            update.set(Anchor::getPrice,anchorUpdate.getPrice());
            updateFlag=true;
        }
        if(anchorUpdate.getOrderSwitch() != null){
            update.set(Anchor::getOrderSwitch,anchorUpdate.getOrderSwitch());
            updateFlag=true;
        }
        if(anchorUpdate.getOpenVideoStatus() != null){
            update.set(Anchor::getOpenVideoStatus,anchorUpdate.getOpenVideoStatus());
            updateFlag=true;
        }
        if(updateFlag){
            return anchorService.update(update);
        }
        return true;
    }

    public boolean userUpdate(UserUpdateReq res) {
        res.setUserId(LoginHelper.getUserId());
        boolean updateFlag = false;
        boolean updateYunxin = false;
        UpdateUinfoReq uinfoReq = new UpdateUinfoReq();
        uinfoReq.setAccid(res.getUserId()+"");
        LambdaUpdateWrapper<User> update =
                Wrappers.lambdaUpdate(User.class).eq(User::getId, res.getUserId());
        if(StringUtils.isNotEmpty(res.getNickname())){
            update.set(User::getNickname,res.getNickname());
            uinfoReq.setName(res.getNickname());
            updateFlag=true;
            updateYunxin=true;
        }
        if(res.getBirthday() != null){
            update.set(User::getBirthday,res.getBirthday());
            uinfoReq.setBirth(res.getBirthday().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            updateFlag=true;
            updateYunxin=true;
        }
        if(res.getGender() != null){
            User user = userService.getById(res.getUserId());
            if(user.getGender() != 0 && !user.getGender().equals(res.getGender())){
                throw new ServiceException("性别不可以修改");
            }
        }
        if(res.getCityId() != null){
            update.set(User::getCityId,res.getCityId());
            update.set(User::getCity,citysService.getByCityId(res.getCityId()));
            updateFlag=true;
        }
        if(StringUtils.isNotEmpty(res.getAvatar())){
            update.set(User::getAvatar,res.getAvatar());
            update.set(User::getAvatarState,1);
//            uinfoReq.setIcon(res.getAvatar());
//            updateYunxin=true;
            updateFlag=true;
        }
        if(updateFlag){
            boolean flag = userService.update(update);
            if(flag){
                userService.checkFinishStatus(res.getUserId());
                if(updateYunxin){
                    YxCommonR r = userClient.updateUinfo(uinfoReq);
                    if(!r.isSuccess()){
                        log.error("云信更新失败，需要检查！{}", JSON.toJSONString(r));
                    }
                }
            }
        }
        return true;
    }

    public AccountBankcard aliInfo() {
        return accountBankcardService.getOne(Wrappers.lambdaQuery(AccountBankcard.class)
                .eq(AccountBankcard::getUserId, LoginHelper.getUserId())
                .last("limit 1"));
    }

    public void saveOrUpdateAliInfo(AccountAliBankCardRes res) {
        AccountBankcard bankcard = new AccountBankcard();
        bankcard.setId(res.getId());
        if(bankcard.getId() == null){
            bankcard.setType(1);
            bankcard.setBankCode("alipay");
            bankcard.setBank("支付宝");
        }
        bankcard.setCardName(res.getCardName());
        bankcard.setCardAccount(res.getCardAccount());
        accountBankcardService.saveOrUpdate(bankcard);
    }
}
