package com.ruoyi.bar.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.bar.mapper.WyBarUserRoleMapper;
import com.ruoyi.common.core.domain.entity.WyBarUser;
import com.ruoyi.common.core.domain.entity.WyBarUserRole;
import com.ruoyi.common.core.domain.model.BarUserRegisterVO;
import com.ruoyi.common.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.ruoyi.bar.mapper.WyBarMapper;
import com.ruoyi.bar.domain.WyBar;
import com.ruoyi.bar.service.IWyBarService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 酒吧Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-02
 */
@Slf4j
@Service
public class WyBarServiceImpl implements IWyBarService
{
    @Resource
    private WyBarMapper wyBarMapper;

    @Resource
    private WyBarUserServiceImpl wyBarUserService;

    @Resource
    private WyBarUserRoleMapper userRoleMapper;

    /**
     * 查询酒吧
     *
     * @param id 酒吧主键
     * @return 酒吧
     */
    @Override
    public WyBar selectWyBarById(Long id)
    {
        final WyBar wyBar = wyBarMapper.selectWyBarById(id);
        if(wyBar!=null && wyBar.getAuthState() == 1){
            if(wyBar.getLastAuthTime() == null){
                wyBar.setLastAuthTime(wyBar.getCreateTime());
                wyBarMapper.updateWyBar(wyBar);
            }
            wyBar.setAuthEndTime(DateUtils.addYears(wyBar.getLastAuthTime(), 1));
        }
        return wyBar;
    }

    @Override
    public WyBar selectWyBarByNumber(String number)
    {
        final WyBar wyBar = new WyBar();
        wyBar.setBarNumber(number);
        final List<WyBar> wyBars = this.selectWyBarList(wyBar);
        if(wyBars.size() > 0){
            return wyBars.get(0);
        }else{
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WyBar register(BarUserRegisterVO registerVO)
    {
        log.debug("registerVo:======================================{}",registerVO);
        if(!PhoneNumberValidator.isValidPhoneNumber(registerVO.getBarContactPhone())){
            throw new RuntimeException("手机号格式不正确");
        }
        WyBar wyBar = new WyBar();
        wyBar.setBarContactPhone(registerVO.getBarContactPhone());
        final List<WyBar> wyBars = wyBarMapper.selectWyBarList(wyBar);
        log.debug("wyBars=======================================:{]",wyBars);
        if (wyBars.size() > 0) {
            throw new RuntimeException("该手机号已注册酒吧");
        }
        wyBar.setBarName(registerVO.getBarName());
        wyBar.setProvince(registerVO.getProvince());
        wyBar.setCity(registerVO.getCity());
        wyBar.setDistrict(registerVO.getDistrict());
        wyBar.setAddress(registerVO.getAddress());

//        wyBar.setBarLogo(registerVO.getBarLogo());
        wyBar.setBusinessLicense(registerVO.getBusinessLicense());
//        wyBar.setPosition(registerVO.getPosition());
//        wyBar.setNickName(registerVO.getNickName());
        wyBar.setStorefrontPhoto(registerVO.getStorefrontPhoto());
        //未认证
        wyBar.setAuthState(1);
        wyBar.setCreateTime(DateUtils.getNowDate());
        wyBar.setLatitude(registerVO.getLatitude());
        wyBar.setLongitude(registerVO.getLongitude());
        final String barNumber = generateBarNumber();
        log.debug("barNumber ======================{}", barNumber);
        wyBar.setBarNumber(barNumber);

        WyBarUser wyBarUserCheck = null;
        wyBarUserCheck = wyBarUserService.selectWyBarUserByUserName(registerVO.getBarContactPhone());
        if (wyBarUserCheck != null) {
            throw new RuntimeException("该手机号已注册");
        }
        wyBarUserCheck = wyBarUserService.selectWyBarUserByPhoneNumber(registerVO.getBarContactPhone());
        if (wyBarUserCheck != null) {
            throw new RuntimeException("该手机号已注册");
        }
        if (wyBar.getLatitude() == null) {
            throw new IllegalArgumentException("纬度不能为空");
        }
        if (wyBar.getLongitude() == null) {
            throw new IllegalArgumentException("经度不能为空");
        }
        try{
            final JSONObject addressComponent = TencentMapUtils.getLatAndLng(wyBar.getLatitude().toString(), wyBar.getLongitude().toString());
            if (addressComponent == null) { // 地址解析失败
                throw new IllegalArgumentException("地址解析失败");
            }
            wyBar.setProvince(addressComponent.getString("province"));
            wyBar.setCity(addressComponent.getString("city"));
            wyBar.setDistrict(addressComponent.getString("district"));
        }catch (Exception e){
            throw new RuntimeException("地址解析失败");
        }
        wyBarMapper.insertWyBar(wyBar);
        WyBarUser wyBarUser = new WyBarUser();
        wyBarUser.setPhonenumber(registerVO.getBarContactPhone());
//        wyBarUser.setNickName(registerVO.getNickName());
        wyBarUser.setBarId(wyBar.getId());
        wyBarUser.setUserName(registerVO.getBarContactPhone());
//        wyBarUser.setAvatar(registerVO.getBarLogo());
        //默认密码为手机号后八位
        wyBarUser.setPassword(getEncryptPassword(registerVO.getBarContactPhone()));
        if (StringUtils.isNotEmpty(registerVO.getOpenId())) {
            wyBarUser.setOpenId(registerVO.getOpenId());
        }
        wyBarUserService.insertWyBarUser(wyBarUser);

        insertUserRole(wyBarUser.getUserId(), new Long[]{1L});
        return wyBar;
    }

    @Override
    public String getEncryptPassword(String phone) {
        return SecurityUtils.encryptPassword(StringUtils.substring(phone, 3));
    }

    private String generateBarNumber() {
        final Integer integer = wyBarMapper.selectBarCount();
        final String barNumber = CodeGeneratorUtils.generateBarCode(integer);
        final WyBar wyBar1 = wyBarMapper.selectWyBarByNumber(barNumber);
        if (wyBar1 != null) {
            generateBarNumber();
        }
        return barNumber;
    }
    /**
     * 查询酒吧列表
     *
     * @param wyBar 酒吧
     * @return 酒吧
     */
    @Override
    public List<WyBar> selectWyBarList(WyBar wyBar)
    {
        return wyBarMapper.selectWyBarList(wyBar);
    }

    /**
     * 新增酒吧
     *
     * @param wyBar 酒吧
     * @return 结果
     */
    @Override
    public int insertWyBar(WyBar wyBar)
    {
        final String barNumber = generateBarNumber();
        wyBar.setBarNumber(barNumber);
        wyBar.setCreateTime(DateUtils.getNowDate());
        return wyBarMapper.insertWyBar(wyBar);
    }

    /**
     * 修改酒吧
     *
     * @param wyBar 酒吧
     * @return 结果
     */
    @Override
    public int updateWyBar(WyBar wyBar)
    {
        wyBar.setUpdateTime(DateUtils.getNowDate());
        return wyBarMapper.updateWyBar(wyBar);
    }

    @Override
    public int approvalWyBar(WyBar wyBar)
    {
        final WyBar bar = this.selectWyBarById(wyBar.getId());
        if (bar.getAuthState() == 1) {
            throw new RuntimeException("该酒吧已认证");
        }
        wyBar.setLastAuthTime(DateUtils.getNowDate());
        wyBar.setAuthState(1);
        wyBar.setEditTimes(2);
        wyBar.setUpdateTime(DateUtils.getNowDate());
        return wyBarMapper.updateWyBar(wyBar);
    }

    /**
     * 批量删除酒吧
     *
     * @param ids 需要删除的酒吧主键
     * @return 结果
     */
    @Override
    public int deleteWyBarByIds(Long[] ids)
    {
        return wyBarMapper.deleteWyBarByIds(ids);
    }

    /**
     * 删除酒吧信息
     *
     * @param id 酒吧主键
     * @return 结果
     */
    @Override
    public int deleteWyBarById(Long id)
    {
        return wyBarMapper.deleteWyBarById(id);
    }

    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<WyBarUserRole> list = new ArrayList<>(roleIds.length);
            for (Long roleId : roleIds)
            {
                WyBarUserRole ur = new WyBarUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }
}
