package com.qs.mp.channel.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qs.mp.admin.domain.vo.IndexVO;
import com.qs.mp.channel.domain.Channel;
import com.qs.mp.channel.domain.vo.ChannelOperDataVO;
import com.qs.mp.channel.domain.vo.ChannelVO;
import com.qs.mp.channel.mapper.ChannelMapper;
import com.qs.mp.channel.service.IChannelCommissionService;
import com.qs.mp.channel.service.IChannelService;
import com.qs.mp.channel.service.IChannelUserRelService;
import com.qs.mp.common.enums.ChannelCertifyStatusEnum;
import com.qs.mp.common.enums.ChannelRoleEnum;
import com.qs.mp.common.enums.ChannelVerifyStatusEnum;
import com.qs.mp.common.enums.RoleTypeEnum;
import com.qs.mp.common.exception.ServiceException;
import com.qs.mp.common.jsms.JSMSUtils;
import com.qs.mp.system.domain.SysRole;
import com.qs.mp.system.domain.SysUser;
import com.qs.mp.system.service.ISysRoleService;
import com.qs.mp.system.service.ISysUserService;
import com.qs.mp.user.domain.UserAddr;
import com.qs.mp.user.service.IUserAddrService;
import com.qs.mp.utils.SecurityUtils;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 渠道经销商 服务实现类
 * </p>
 *
 * @author quanshu
 * @since 2022-03-02
 */
@Service
public class ChannelServiceImpl extends ServiceImpl<ChannelMapper, Channel> implements
    IChannelService {

  @Autowired
  private IChannelService channelService;

  @Autowired
  private IChannelUserRelService channelUserRelService;

  @Autowired
  private IChannelCommissionService channelCommissionService;

  @Autowired
  private ISysUserService userService;

  @Autowired
  private ISysRoleService roleService;

  @Autowired
  private IUserAddrService userAddrService;

  @Override
  @Transactional
  public void saveChannel(Channel channel, ChannelRoleEnum channelRole) {
    boolean res = channelService.save(channel);
    if (res && null != channel.getChannelId()) {
      channel.setChannelNo(channel.getChannelNo() + channel.getChannelId());
			SysUser sysUser = userService.selectUserByUserName(channel.getMobile());
			if (null == sysUser) {
				// 生成用户
				sysUser = new SysUser();
				sysUser.setUserName(channel.getMobile());
				sysUser.setPhonenumber(channel.getMobile());
				sysUser.setNickName(channel.getMobile());
//		    sysUser.setDeptId(SecurityUtils.getDeptId());
//			sysUser.setCreateBy(SecurityUtils.getUsername());
				// 获取默认的角色
				SysRole sysRole = roleService.selectDefaultRoleByType(
						channelRole == ChannelRoleEnum.CHANNEL ? RoleTypeEnum.CHANNEL_ROLE.getValue()
								: RoleTypeEnum.SALESITE_ROLE.getValue());
				if (null == sysRole || null == sysRole.getRoleId()) {
					throw new ServiceException(
							"未设置默认角色，请联系管理员");
				}
				Long[] roleIds = new Long[1];
				roleIds[0] = sysRole.getRoleId();
				sysUser.setRoleIds(roleIds);
				int userNum = userService.insertUser(sysUser);
				if (userNum == 0 || null == sysUser.getUserId()) {
					throw new ServiceException("账号创建失败，请联系管理员");
				}
			}
      channel.setUserId(sysUser.getUserId());
      boolean ures = channelService.updateById(channel);
      if (!ures) {
        throw new ServiceException("请联系管理员");
      }
      // 4.发送账号创建成功短信
      JSMSUtils.sendChannelActNotify(channel.getMobile());
    } else {
      throw new ServiceException("请联系管理员");
    }
  }


  @Override
  @Transactional
  public void updateChannel(Channel channel, boolean mobileChange) {
    // 4.更新入库
    boolean editRes = channelService.updateById(channel);
    if (editRes && mobileChange
        && null != channel.getUserId()) {
      SysUser sysUser = new SysUser();
      sysUser.setUserId(channel.getUserId());
      sysUser.setUserName(channel.getMobile());
      sysUser.setPhonenumber(channel.getMobile());
      sysUser.setNickName(channel.getName());
      sysUser.setDeptId(SecurityUtils.getDeptId());
      int userNum = userService.updateUser(sysUser);
      if (userNum == 0 || null == sysUser.getUserId()) {
        throw new ServiceException("更新失败，请联系管理员");
      }
      // 发送账号更新成功短信
    }
  }

  @Override
  public List<ChannelVO> selectChannelVoList(Wrapper<Channel> queryWrapper) {
    return getBaseMapper().selectChannelVoList(queryWrapper);
  }

  @Override
  public List<ChannelVO> selectChannelList(Wrapper<Channel> queryWrapper) {
    return getBaseMapper().selectChannelList(queryWrapper);
  }

  @Override
  public List<ChannelVO> selectSaleSiteList(Wrapper<Channel> queryWrapper) {
    return getBaseMapper().selectSaleSiteList(queryWrapper);
  }

  @Override
  public Channel getChannelByUserId(Long userId) {
    return getBaseMapper().selectOne(
        new LambdaQueryWrapper<Channel>().eq(Channel::getUserId, userId));
  }

  @Override
  public int getChannelSiteCnt(String channelNo) {
    return getBaseMapper().getChannelSiteCnt(channelNo);
  }

  @Override
  public ChannelVO getChannelVoById(Long channelId) {
    List<ChannelVO> channelVOList = getBaseMapper().selectChannelVoList(new QueryWrapper<Channel>().eq("t1.channel_id", channelId));
    if (CollectionUtils.isEmpty(channelVOList)) {
      return null;
    }
    return channelVOList.get(0);
  }

  @Override
  public ChannelOperDataVO getChannelOperData(String channelNo, int days) {
    ChannelOperDataVO channelOperData = new ChannelOperDataVO();
    // 查询销售金额
    channelOperData.setSaleAmt(channelCommissionService.getChannelSaleAmtCnt(channelNo, days));
    // 查询佣金金额
    channelOperData.setCommAmt(channelCommissionService.getChannelCommAmtCnt(channelNo, days));
    // 查询新增用户数
    int newUserCnt = channelUserRelService.getChannelNewUserCnt(channelNo, days);
    channelOperData.setNewUserCnt(newUserCnt);
    return channelOperData;
  }


  @Override
  public ChannelOperDataVO getChannelTotalOperData(String channelNo) {
    ChannelOperDataVO channelOperData = new ChannelOperDataVO();
    // 查询销售金额
    channelOperData.setSaleAmt(channelCommissionService.getChannelTotalSaleAmtCnt(channelNo));
    // 查询佣金金额
    channelOperData.setCommAmt(channelCommissionService.getChannelTotalCommAmtCnt(channelNo));
    // 查询新增用户数
    // int newUserCnt = channelUserRelService.getChannelNewUserCnt(channelNo, days);
    // channelOperData.setNewUserCnt(newUserCnt);
    return channelOperData;
  }


  @Override
  public List<IndexVO> selectIndexSiteIncreaseList(Wrapper<Channel> wrapper) {
	 return getBaseMapper().selectIndexSiteIncreaseList(wrapper);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean siteVerify(Channel channel) {

    if(channel.getVerifyStatus() == ChannelVerifyStatusEnum.ACCEPT) {
      channel.setCertifyStatus(ChannelCertifyStatusEnum.CERTIFIED);

      // 获取经销商信息
      Channel param = this.getById(channel.getChannelId());
      // 设置保存地址信息
      UserAddr userAddr = new UserAddr();
      userAddr.setUserId(param.getUserId());
      userAddr.setReceiver(param.getContact());
      userAddr.setProvince(param.getProvince());
      userAddr.setProvinceId(param.getProvinceId());
      userAddr.setCity(param.getCity());
      userAddr.setCityId(param.getCityId());
      userAddr.setArea(param.getArea());
      userAddr.setAreaId(param.getAreaId());
      userAddr.setAddr(param.getAddress());
      userAddr.setMobile(param.getMobile());
      userAddr.setStatus(1);
      int count = userAddrService.count(new LambdaQueryWrapper<UserAddr>().eq(UserAddr::getUserId, channel.getUserId()));
      if (count == 0) {
        userAddr.setCommonAddr(1);
      }
      userAddrService.save(userAddr);

    }else {
      channel.setCertifyStatus(ChannelCertifyStatusEnum.NOT_CERTIFIED);
    }
    // 更新经销商信息
    channelService.updateById(channel);

    return true;
  }
}
