package com.qs.mp.web.controller.api.channel;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qs.mp.admin.domain.vo.TicketCntVO;
import com.qs.mp.admin.service.ITicketService;
import com.qs.mp.channel.domain.Channel;
import com.qs.mp.channel.domain.ChannelCommission;
import com.qs.mp.channel.domain.ChannelOrderDetail;
import com.qs.mp.channel.domain.ChannelUserRel;
import com.qs.mp.channel.domain.param.ChannelParam;
import com.qs.mp.channel.domain.param.SiteQueryParam;
import com.qs.mp.channel.domain.param.VerifyParam;
import com.qs.mp.channel.domain.vo.ChannelOperDataVO;
import com.qs.mp.channel.domain.vo.ChannelVO;
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.constant.UserConstants;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.enums.ChannelCertifyStatusEnum;
import com.qs.mp.common.enums.ChannelRoleEnum;
import com.qs.mp.common.enums.ChannelStatusEnum;
import com.qs.mp.common.enums.ChannelVerifyStatusEnum;
import com.qs.mp.common.enums.ErrorCodeEnum;
import com.qs.mp.common.exception.ServiceException;
import com.qs.mp.common.exception.base.BaseException;
import com.qs.mp.common.utils.DateUtils;
import com.qs.mp.system.service.ISysUserService;
import com.qs.mp.user.domain.UserAddr;
import com.qs.mp.user.domain.UserTicketOrder;
import com.qs.mp.user.service.IUserAddrService;
import com.qs.mp.user.service.IUserTicketOrderService;
import com.qs.mp.utils.SecurityUtils;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @auther zhongcp
 * @create 2022-02-28 16:17:48
 * @describe 渠道管理前端控制器
 */
@Api("渠道管理API")
@RestController
@RequestMapping("/api/v1/mp/channel/*")
@Component
public class ChannelController extends BaseApiController {

	@Autowired
	private IChannelService channelService;

	@Autowired
	private IChannelCommissionService channelCommissionService;

	@Autowired
	private IChannelUserRelService channelUserRelService;

    @Autowired
    private ISysUserService userService;

	@Autowired
	private IUserTicketOrderService userTicketOrderService;

	@Autowired
	private ITicketService ticketService;

	@Autowired
	private MapperFacade mapperFacade;

	@Autowired
	private IUserAddrService userAddrService;

	/**
	 * 获取我的下级渠道列表信息，支持翻页
	 *
	 * @return
	 */
	@PostMapping("subchannel/list")
	public TableDataInfo listChannel(@RequestBody Channel channel) {
		Long channelId = SecurityUtils.getLoginUser().getChannelId();
		List<ChannelVO> list = new ArrayList<ChannelVO>();
		if(null != channelId) {
			channel.setParentId(channelId);
			startPage();
			QueryWrapper<Channel> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("t1.parent_id", channel.getParentId());
			queryWrapper.gt("t1.level", 0);
			queryWrapper.orderByAsc("t1.channel_id");
			list = channelService.selectChannelVoList(queryWrapper);
			if(null != list && list.size() > 0) {
				for(ChannelVO channelVO : list) {
					if(null != channelVO && StringUtils.isNotBlank(channelVO.getChannelNo())) {
						int siteCnt = channelService.getChannelSiteCnt(channelVO.getChannelNo());
						int userCnt = channelUserRelService.getChannelTotalUserCnt(channelVO.getChannelNo());
						channelVO.setSiteCnt(siteCnt);
						channelVO.setUserCnt(userCnt);
					}
				}
			}
		}
		return getDataTable(list);
	}

	/**
	 * 获取我的下级渠道详情信息
	 *
	 * @param
	 * @return
	 */
	@PostMapping(value = "subchannel/detail")
	public AjaxResult getChannelDetail(@RequestBody Channel channel) {
		if (null == channel || null == channel.getChannelId()) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		Long parentlId = SecurityUtils.getLoginUser().getChannelId();
		ChannelVO channelVO = new ChannelVO();
		Channel queryChannel = channelService.getById(channel.getChannelId());
		if(null == queryChannel || null == queryChannel.getChannelId()) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		if(!parentlId.equals(queryChannel.getParentId())) {
			return AjaxResult.error("非当前用户的下级,查询失败");
		}
	    BeanUtils.copyProperties(queryChannel, channelVO);
	    // 查询今日的销售额、佣金收入、新增用户数
	    ChannelOperDataVO channelOperDataVO = channelService.getChannelOperData(channelVO.getChannelNo(), 1);
	    channelVO.setOperData(channelOperDataVO);
		return AjaxResult.success(channelVO);
	}

	/**
	 * 新增子渠道信息
	 * @param
	 * @return
	 */
	@ApiOperation(value = "新增子渠道信息", notes = "渠道端新增子渠道")
	@PostMapping("subchannel/create")
	public AjaxResult channelCreate(@Validated @RequestBody ChannelParam channelParam) {
		if (channelParam.getChannelId() != null && channelParam.getChannelId() != 0) {
			return AjaxResult.error("该代理已存在");
		}
		Long channelId = SecurityUtils.getLoginUser().getChannelId();
		Channel existChannel = channelService.getById(channelId);
		if (existChannel.getStatus() == ChannelStatusEnum.OFF) {
			return AjaxResult.error("账号异常");
		}
		Channel channel = mapperFacade.map(channelParam, Channel.class);
		channel.setParentId(channelId);
		// 1、校验名称是否重复、手机号是否存在（渠道表）
		LambdaQueryWrapper<Channel> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Channel::getName, channel.getName());
		queryWrapper.gt(Channel::getLevel, 0);
		int nameCount = channelService.count(queryWrapper);
		if(nameCount > 0) {
			return AjaxResult.error("代理名称" + channel.getName() + "已存在！");
		}
		int mobileCount = channelService.count(
		        new LambdaQueryWrapper<Channel>().eq(Channel::getMobile, channel.getMobile()));
		if(mobileCount > 0) {
			 return AjaxResult.error("手机号码" + channel.getMobile() + "已注册！");
		}
		// 2.校验佣金比例，不能高于其父渠道的佣金比例
		Channel parentChannel = channelService.getById(channel.getParentId());
		if(null != parentChannel && null != parentChannel.getCommRate()) {
			 if(channel.getCommRate().compareTo(parentChannel.getCommRate()) > 0) {
				 return AjaxResult.error("佣金比例不能高于上级代理的佣金比例");
			 }
		}
		channel.setLevel(parentChannel.getLevel()+1);
		// 3.插入数据
		channel.setChannelNo(parentChannel.getChannelNo()+".");
		try {
			channelService.saveChannel(channel, ChannelRoleEnum.CHANNEL);
		} catch (Exception e) {
			return AjaxResult.error("代理'" + channel.getName() + "'新增失败" + e.getMessage());
		}

		return AjaxResult.success("代理'" + channel.getName() + "'新增成功");
	}

	/**
	 * 编辑子渠道信息
	 * @param
	 * @return
	 */
	@ApiOperation(value = "编辑子渠道信息", notes = "渠道端编辑子渠道")
	@PostMapping("subchannel/update")
	public AjaxResult channelUpdate(@Validated @RequestBody ChannelParam channelParam) {

		if (null == channelParam || null == channelParam.getChannelId()) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}

		Channel channel = mapperFacade.map(channelParam, Channel.class);
		// 1、校验修改子渠道是否为当前用户的子渠道
		Channel oldChannel = channelService.getById(channel.getChannelId());
		if(null == oldChannel || null == oldChannel.getChannelId()) {
			return AjaxResult.error("代理'" + oldChannel.getName() + "'编辑失败");
		}
		Long channelId = SecurityUtils.getLoginUser().getChannelId();
		Channel existChannel = channelService.getById(channelId);
		if (existChannel.getStatus() == ChannelStatusEnum.OFF) {
			return AjaxResult.error("账号异常");
		}
		if(!oldChannel.getParentId().equals(channelId)) {
			return AjaxResult.error("代理'" + oldChannel.getName() + "'编辑失败");
		}
		// 2.校验名称是否重复、手机号是否存在（渠道表）；
		if(!channel.getName().equals(oldChannel.getName())) {
			LambdaQueryWrapper<Channel> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(Channel::getName, channel.getName());
			queryWrapper.gt(Channel::getLevel, 0);
			int nameCount = channelService.count(queryWrapper);
			if(nameCount > 0) {
				return AjaxResult.error("代理名称" + channel.getName() + "已存在！");
			}
		}
		boolean mobileChange = false;  // 手机号码是否有变更
		if(!channel.getMobile().equals(oldChannel.getMobile())) {
			int mobileCount = channelService.count(
			        new LambdaQueryWrapper<Channel>().eq(Channel::getMobile, channel.getMobile()));
			if(mobileCount > 0) {
				return AjaxResult.error("手机号码" + channel.getMobile() + "已注册！");
			}
			if(UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(channel.getMobile()))) {
				return AjaxResult.error("手机号码" + channel.getMobile() + "已注册！");
			}
			mobileChange = true;
		}
		// 3.校验佣金比例，不能高于其父渠道的佣金比例，不能低于其子渠道的最大佣金比例
		Channel parentChannel = channelService.getById(oldChannel.getParentId());
		if(null != parentChannel && null != parentChannel.getCommRate()) {
			 if(channel.getCommRate().compareTo(parentChannel.getCommRate()) > 0) {
				 return AjaxResult.error("佣金比例不能高于上级代理的佣金比例");
			 }
		}
		// 查询子渠道的最大佣金比例
		QueryWrapper<Channel> queryWrapper = new QueryWrapper<Channel>();
		queryWrapper.select("IFNULL(max(comm_rate),0) as commRate");
		queryWrapper.lambda().eq(Channel::getParentId, channel.getChannelId());
		Map<String, Object> map = channelService.getMap(queryWrapper);
		if(null != map && map.containsKey("commRate")) {
			BigDecimal commRate = new BigDecimal(map.get("commRate").toString());
			if(!commRate.equals(BigDecimal.ZERO) && channel.getCommRate().compareTo(commRate) < 0) {
				return AjaxResult.error("不能低于其下级的最大佣金比例");
			}
		}
		try {
			channel.setUserId(oldChannel.getUserId());
			channelService.updateChannel(channel, mobileChange);
		} catch (Exception e) {
			return AjaxResult.error(e.getMessage());
		}
		return AjaxResult.success("代理'" + channel.getName() + "'编辑成功");
	}


	/**
	 *获取当前用户渠道或者某个子渠道的经营数据
	 *
	 * @param
	 * @return
	 */
	@PostMapping(value = "subchannel/operdata/query")
	public AjaxResult getOperData(@RequestBody JSONObject jsonObject) {
		if (null == jsonObject) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		Long channelId = SecurityUtils.getLoginUser().getChannelId();
		int days = jsonObject.getIntValue("days");;
		if(StringUtils.isNotBlank(jsonObject.getString("channelId"))) {
			Long _channelId = jsonObject.getLong("channelId");
			Channel queryChannel = channelService.getById(_channelId);
			if(null == queryChannel || null == queryChannel.getChannelId()) {
				return error(ErrorCodeEnum.ERROR_CODE_1001);
			}
			if(!channelId.equals(queryChannel.getParentId())) {
				return AjaxResult.error("非当前用户的下级,查询失败");
			}
			channelId = _channelId;
		}
		days = days > 0?days:1;
		Channel channel = channelService.getById(channelId);
		// 查询今日的销售额、佣金收入、新增用户数
		ChannelOperDataVO channelOperDataVO = channelService.getChannelOperData(channel.getChannelNo(), days);
		return AjaxResult.success(channelOperDataVO);
	}

	/**
	 * 获取子渠道的经营数据列表
	 *
	 * @param
	 * @return
	 */
	@PostMapping(value = "subchannel/operdata/list")
	public TableDataInfo getOperDataList(@RequestBody JSONObject jsonObject) {
		Long channelId = SecurityUtils.getLoginUser().getChannelId();
		int days = jsonObject.getIntValue("days");;
		if(StringUtils.isNotBlank(jsonObject.getString("channelId"))) {
			channelId = jsonObject.getLong("channelId");
		}
		days = days > 0?days:1;
		startPage();
		List<Channel> list = channelService.list(
		        new LambdaQueryWrapper<Channel>().eq(Channel::getParentId, channelId).gt(Channel::getLevel, 0)
		            .orderByDesc(Channel::getChannelId));

		List<ChannelOperDataVO> dataList = new ArrayList<ChannelOperDataVO>();
		if(null != list && list.size() > 0) {
			for(Channel channel : list) {
				if(null != channel && null != channel.getChannelNo()) {
				    // 查询今日的销售额、佣金收入、新增用户数
				    ChannelOperDataVO channelOperDataVO = channelService.getChannelOperData(channel.getChannelNo(), days);
				    if(null != channelOperDataVO) {
				    	channelOperDataVO.setName(channel.getName());
							channelOperDataVO.setMobile(channel.getMobile());
				    	dataList.add(channelOperDataVO);
				    }
				}
			}
		}
		TableDataInfo resData = getDataTable(list);
		resData.setRows(dataList);
		return resData;
	}


	/**
	 * 获取我的经销商列表信息，支持翻页
	 *
	 * @return
	 */
	@PostMapping("site/list")
	public TableDataInfo listSite(@RequestBody SiteQueryParam siteParam) {
		Long channelId = SecurityUtils.getLoginUser().getChannelId();
		List<ChannelVO> list = new ArrayList<ChannelVO>();
		if(null != channelId) {
			startPage();
			QueryWrapper<Channel> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("t1.parent_id", channelId);
			queryWrapper.eq("t1.level", 0);
			if(!CollectionUtils.isEmpty(siteParam.getVerifyStatus())) {
				queryWrapper.in("t1.verify_status", siteParam.getVerifyStatus());
			}
			if(StringUtils.isNotBlank(siteParam.getCertifyStatus())) {
				queryWrapper.eq("t1.certify_status", siteParam.getCertifyStatus());
			}
			list = channelService.selectChannelVoList(queryWrapper);

			List<Long> channelIds = new ArrayList<Long>();
			if(null != list && list.size() > 0) {
				for(ChannelVO channelVO : list) {
					if(null != channelVO && null != channelVO.getChannelId()
							&& StringUtils.isNotBlank(channelVO.getChannelNo())) {
						channelIds.add(channelVO.getChannelId());
	 				}
				}
			}
			List<TicketCntVO>  qtyCntList = new ArrayList<TicketCntVO>();
			List<TicketCntVO>  saleCntList = new ArrayList<TicketCntVO>();
			if(null != channelIds && channelIds.size() > 0) {
				QueryWrapper<ChannelOrderDetail> ticketQtyCntQueryWrapper = new QueryWrapper<ChannelOrderDetail>();
				ticketQtyCntQueryWrapper.in("t1.channel_id", channelIds);
				qtyCntList = ticketService.listTicketQtyCnt(ticketQtyCntQueryWrapper);

		    	QueryWrapper<UserTicketOrder> ticketSaleCntQueryWrapper = new QueryWrapper<UserTicketOrder>();
		    	ticketSaleCntQueryWrapper.in("t1.channel_id", channelIds);
		    	ticketSaleCntQueryWrapper.eq("t1.`status`", 1);
		    	saleCntList = userTicketOrderService.listTicketSaleCnt(ticketSaleCntQueryWrapper);
			}

			if(null != list && list.size() > 0) {
				for(ChannelVO channelVO : list) {
					if(null != channelVO && null != channelVO.getChannelId()
							&& StringUtils.isNotBlank(channelVO.getChannelNo())) {
						// int siteCnt = channelService.getChannelSiteCnt(channelVO.getChannelNo());
						LambdaQueryWrapper<ChannelUserRel> userCntQueryWrapper = new LambdaQueryWrapper<ChannelUserRel>();
						userCntQueryWrapper.eq(ChannelUserRel::getChannelId, channelVO.getChannelId());
						int userCnt = channelUserRelService.count(userCntQueryWrapper);
						channelVO.setUserCnt(userCnt);
						// 统计盲票库存， 销量
						if(null != qtyCntList && qtyCntList.size() > 0) {
							List<TicketCntVO> voList =  qtyCntList.stream().filter(item  -> item.getChannelId().equals(channelVO.getChannelId()))
					                .collect(Collectors.toList());
							if(null != voList && voList.size() > 0) {
								TicketCntVO ticketQtyCnt =  voList.get(0);
								channelVO.setOffLineQtyCnt(null != ticketQtyCnt?ticketQtyCnt.getOffLineQtyCnt():0);
							}
						}
						if(null != saleCntList && saleCntList.size() > 0) {
							List<TicketCntVO> voList =  saleCntList.stream().filter(item  -> item.getChannelId().equals(channelVO.getChannelId()))
					                .collect(Collectors.toList());
							if(null != voList && voList.size() > 0) {
								TicketCntVO ticketSaleCnt =  voList.get(0);
								channelVO.setOffLineSaleCnt(null != ticketSaleCnt?ticketSaleCnt.getOffLineSaleCnt():0);
								channelVO.setOnLineSaleCnt(null != ticketSaleCnt?ticketSaleCnt.getOnLineSaleCnt():0);
							}
						}
	 				}
				}
			}

		}
		return getDataTable(list);
	}

	/**
	 * 获取我的下级渠道详情信息
	 *
	 * @param
	 * @return
	 */
	@PostMapping(value = "site/detail")
	public AjaxResult getSiteDetail(@RequestBody Channel channel) {
		if (null == channel || null == channel.getChannelId()) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		Long parentlId = SecurityUtils.getLoginUser().getChannelId();
		ChannelVO channelVO = new ChannelVO();
		Channel queryChannel = channelService.getById(channel.getChannelId());
		if(null == queryChannel || null == queryChannel.getChannelId()) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		if(!parentlId.equals(queryChannel.getParentId())) {
			return AjaxResult.error("非当前用户的门店,查询失败");
		}
	    BeanUtils.copyProperties(queryChannel, channelVO);
	    // 查询今日的销售额、佣金收入、新增用户数
	    ChannelOperDataVO channelOperDataVO = channelService.getChannelOperData(channelVO.getChannelNo(), 1);
	    channelVO.setOperData(channelOperDataVO);
	    if(null != channelVO && null != channelVO.getChannelId()) {

	    	LambdaQueryWrapper<ChannelUserRel> userCntQueryWrapper = new LambdaQueryWrapper<ChannelUserRel>();
			userCntQueryWrapper.eq(ChannelUserRel::getChannelId, channelVO.getChannelId());
			int userCnt = channelUserRelService.count(userCntQueryWrapper);
			channelVO.setUserCnt(userCnt);

	    	int ticketQtyCnt = ticketService.getTicketQtyCnt(channelVO.getChannelId());
	    	channelVO.setOffLineQtyCnt(ticketQtyCnt);

	    	TicketCntVO ticketSaleCnt = userTicketOrderService.getTicketSaleCnt(channelVO.getChannelId());
			channelVO.setOffLineSaleCnt(null != ticketSaleCnt?ticketSaleCnt.getOffLineSaleCnt():0);
			channelVO.setOnLineSaleCnt(null != ticketSaleCnt?ticketSaleCnt.getOnLineSaleCnt():0);
	    }

		return AjaxResult.success(channelVO);
	}

	/**
	 * 新增经销商信息
	 * @param
	 * @return
	 */
	@ApiOperation(value = "渠道端新增经销商", notes = "渠道端新增经销商")
	@PostMapping("site/create")
	public AjaxResult siteCreate(@Validated @RequestBody ChannelParam channelParam) {
		if (channelParam.getChannelId() != null && channelParam.getChannelId() != 0) {
			return AjaxResult.error("该门店已存在");
		}
		Long channelId = SecurityUtils.getLoginUser().getChannelId();
		Channel existChannel = channelService.getById(channelId);
		if (existChannel.getStatus() == ChannelStatusEnum.OFF) {
			return AjaxResult.error("账号异常");
		}

		Channel channel = mapperFacade.map(channelParam, Channel.class);
		channel.setParentId(channelId);
		// 1、校验名称是否重复、手机号是否存在（渠道表）
		LambdaQueryWrapper<Channel> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Channel::getName, channel.getName());
		queryWrapper.eq(Channel::getLevel, 0);
		int nameCount = channelService.count(queryWrapper);
		if(nameCount > 0) {
			return AjaxResult.error("门店名称" + channel.getName() + "已存在！");
		}
		int mobileCount = channelService.count(
		        new LambdaQueryWrapper<Channel>().eq(Channel::getMobile, channel.getMobile()));
		if(mobileCount > 0) {
			 return AjaxResult.error("手机号码" + channel.getMobile() + "已注册！");
		}
		// 2.校验佣金比例，不能高于其父渠道的佣金比例
		Channel parentChannel = channelService.getById(channel.getParentId());
		if(null != parentChannel && null != parentChannel.getCommRate()) {
			 if(channel.getCommRate().compareTo(parentChannel.getCommRate()) > 0) {
				 return AjaxResult.error("佣金比例不能高于上级代理的佣金比例");
			 }
		}
		channel.setLevel(0);
		// 3.插入数据
		channel.setChannelNo(parentChannel.getChannelNo()+".");
		try {
			channelService.saveChannel(channel,ChannelRoleEnum.SALESITE);
		} catch (Exception e) {
			return AjaxResult.error("门店'" + channel.getName() + "'新增失败"+e.getMessage());
		}
		return AjaxResult.success("门店'" + channel.getName() + "'新增成功");
	}

	/**
	 * 编辑经销商信息
	 * @param
	 * @return
	 */
	@ApiOperation(value = "编辑经销商信息", notes = "渠道端编辑经销商")
	@PostMapping("site/update")
	public AjaxResult siteUpdate(@Validated @RequestBody ChannelParam channelParam) {

		if (null == channelParam || null == channelParam.getChannelId()) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		Channel channel = mapperFacade.map(channelParam, Channel.class);

		// 1、校验修改子渠道是否为当前用户的子渠道
		Channel oldChannel = channelService.getById(channel.getChannelId());
		if(null == oldChannel || null == oldChannel.getChannelId()) {
			return AjaxResult.error("门店'" + oldChannel.getName() + "'编辑失败");
		}
		Long channelId = SecurityUtils.getLoginUser().getChannelId();
		Channel existChannel = channelService.getById(channelId);
		if (existChannel.getStatus() == ChannelStatusEnum.OFF) {
			return AjaxResult.error("账号异常");
		}
		if(!oldChannel.getParentId().equals(channelId)) {
			return AjaxResult.error("门店'" + oldChannel.getName() + "'编辑失败");
		}
		// 2.校验名称是否重复、手机号是否存在（渠道表）；
		if(!channel.getName().equals(oldChannel.getName())) {

			LambdaQueryWrapper<Channel> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(Channel::getName, channel.getName());
			queryWrapper.eq(Channel::getLevel, 0);
			int nameCount = channelService.count(queryWrapper);
			if(nameCount > 0) {
				return AjaxResult.error("门店名称" + channel.getName() + "已存在！");
			}
		}
		boolean mobileChange = false;  // 手机号码是否有变更
		if(!channel.getMobile().equals(oldChannel.getMobile())) {
			int mobileCount = channelService.count(
			        new LambdaQueryWrapper<Channel>().eq(Channel::getMobile, channel.getMobile()));
			if(mobileCount > 0) {
				return AjaxResult.error("手机号码" + channel.getMobile() + "已注册！");
			}
			if(UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(channel.getMobile()))) {
				return AjaxResult.error("手机号码" + channel.getMobile() + "已注册！");
			}
			mobileChange = true;
		}
		// 3.校验佣金比例，不能高于其父渠道的佣金比例，不能低于其子渠道的最大佣金比例
		Channel parentChannel = channelService.getById(oldChannel.getParentId());
		if(null != parentChannel && null != parentChannel.getCommRate()) {
			 if(channel.getCommRate().compareTo(parentChannel.getCommRate()) > 0) {
				 return AjaxResult.error("佣金比例不能高于上级代理的佣金比例");
			 }
		}
		try {
			channel.setUserId(oldChannel.getUserId());
			channelService.updateChannel(channel, mobileChange);
		} catch (Exception e) {
			return AjaxResult.error("门店'" + channel.getName() + "'编辑失败");
		}
		return AjaxResult.success("门店'" + channel.getName() + "'编辑成功");
	}


	/**
	 * 经销商认证审核
	 * @param
	 * @return
	 */
	@ApiOperation(value = "经销商认证审核", notes = "经销商认证审核")
	@PostMapping("site/verify")
	public AjaxResult siteVerify(@RequestBody Channel channel) {

		if (null == channel || null == channel.getChannelId() || null == channel.getVerifyStatus()) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}

		Long parentlId = SecurityUtils.getLoginUser().getChannelId();
		Channel existChannel = channelService.getById(parentlId);
		if (existChannel.getStatus() == ChannelStatusEnum.OFF) {
			return AjaxResult.error("账号异常");
		}
		Channel queryChannel = channelService.getById(channel.getChannelId());
		if(null == queryChannel || null == queryChannel.getChannelId()) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		if(!parentlId.equals(queryChannel.getParentId())) {
			return AjaxResult.error(queryChannel.getName() + "非当前用户的门店, 认证审核失败");
		}
		try {
			channelService.siteVerify(channel);
		} catch (Exception e) {
			return AjaxResult.error("门店'" + channel.getName() + "'认证审核失败");
		}
		return AjaxResult.success("门店'" + channel.getName() + "'认证审核成功");
	}

	/**
	 * 经销商认证页面点提交
	 * @param
	 * @return
	 */
	@ApiOperation(value = "经销商认证信息提交", notes = "经销商认证页面点提交")
	@PostMapping("site/verify/submit")
	public AjaxResult siteVerifySubmit(@Validated @RequestBody VerifyParam verifyParam) {

		if (null == verifyParam || null == verifyParam.getChannelId()) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		Channel channel = mapperFacade.map(verifyParam, Channel.class);
		try {
			channel.setVerifyStatus(ChannelVerifyStatusEnum.WAIT);
			channelService.updateById(channel);
		} catch (Exception e) {
			return AjaxResult.error("门店'" + channel.getName() + "'提交认证信息失败");
		}
		return AjaxResult.success("门店'" + channel.getName() + "'提交认证信息成功");
	}


	/**
	 * 我的（经销商）
	 *
	 * @param
	 * @return
	 */
	@PostMapping(value = "/site/mine/detail")
	@ApiOperation(value = "经销商查看我的信息", notes = "经销商端点击我的")
	public AjaxResult getSiteMineDetail() {
		Long channelId = SecurityUtils.getLoginUser().getChannelId();
		if (null == channelId) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		ChannelVO channelVO = new ChannelVO();
		Channel queryChannel = channelService.getById(channelId);
	    BeanUtils.copyProperties(queryChannel, channelVO);
	    // 查询今日的销售额、佣金收入、新增用户数
	    Channel parentChannel = channelService.getById(queryChannel.getParentId());
	    channelVO.setParentName(parentChannel.getName());
		return AjaxResult.success(channelVO);
	}

	/**
	 * 我的（渠道）
	 *
	 * @param
	 * @return
	 */
	@PostMapping(value = "/mine/detail")
	@ApiOperation(value = "渠道端查看我的信息", notes = "渠道端点击我的")
	public AjaxResult getChannelMineDetail() {
		Long channelId = SecurityUtils.getLoginUser().getChannelId();
		if (null == channelId) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		ChannelVO channelVO = new ChannelVO();
		Channel queryChannel = channelService.getById(channelId);
		BeanUtils.copyProperties(queryChannel, channelVO);
		// 查询今日的销售额、佣金收入、新增用户数
		Channel parentChannel = channelService.getById(queryChannel.getParentId());
		if (null != parentChannel) {
			channelVO.setParentName(parentChannel.getName());
		}
		// 统计今天的分润金额
		Date zero = DateUtils.getToday(); // 获取当天零点零分时间
		QueryWrapper<ChannelCommission> queryWrapper = new QueryWrapper<ChannelCommission>();
		queryWrapper.select("IFNULL(sum(comm_amt) ,0) as commAmt");
		queryWrapper.lambda().eq(ChannelCommission::getChannelId, channelId);
		queryWrapper.lambda().gt(ChannelCommission::getCreatedTime, zero);
		Map<String, Object> map = channelCommissionService.getMap(queryWrapper);
		if(null != map && map.containsKey("commAmt")) {
			BigDecimal commAmt = new BigDecimal(map.get("commAmt").toString());
			ChannelOperDataVO channelOperDataVO = new ChannelOperDataVO();
			channelOperDataVO.setCommAmt(commAmt.longValue());
			channelVO.setOperData(channelOperDataVO);
		}
		return AjaxResult.success(channelVO);
	}


	/**
	 * 场景是这里要显示待审核数量
	 *
	 * @param
	 * @return
	 */
	@PostMapping(value = "subchannel/index")
	public AjaxResult getChannelIndex() {
		int waitVerifyNum = 0;
		Long channelId = SecurityUtils.getLoginUser().getChannelId();
		if(null != channelId && 0 != channelId) {
			LambdaQueryWrapper<Channel> queryWrapper = new LambdaQueryWrapper<Channel>();
			queryWrapper.eq(Channel::getParentId, channelId);
			queryWrapper.eq(Channel::getVerifyStatus, ChannelVerifyStatusEnum.WAIT);
			queryWrapper.eq(Channel::getLevel, 0);
			waitVerifyNum = channelService.count(queryWrapper);
		}
	    Map<String,Object> map = new HashMap<String,Object>();
	    map.put("waitVerifyNum", waitVerifyNum);
		return AjaxResult.success(map);
	}
}
