package com.fs.app.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fs.app.annotation.Login;
import com.fs.app.param.CompanyUserChangeApplyParam;
import com.fs.app.param.CompanyUserParam;
import com.fs.app.param.CompanyUserUpdateParam;
import com.fs.app.vo.CompanySubUserVO;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.constant.UserConstants;
import com.fs.common.core.domain.R;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.bean.BeanUtils;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyDept;
import com.fs.company.domain.CompanyUser;
import com.fs.company.domain.CompanyUserChangeApply;
import com.fs.company.service.ICompanyDeptService;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserChangeApplyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.vo.CompanyUserChangeApplyVO;
import com.fs.core.security.SecurityUtils;
import com.fs.course.service.IFsCourseRedPacketLogService;
import com.fs.course.service.IFsCourseWatchLogService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "企业用户接口")
@RestController
@RequestMapping("/app/companyUser")
@AllArgsConstructor
public class CompanyUserController extends AppBaseController {

    private final ICompanyUserService companyUserService;
    private final ICompanyService companyService;
    private final ICompanyDeptService companyDeptService;
    private final IFsCourseWatchLogService courseWatchLogService;
    private final IFsCourseRedPacketLogService courseRedPacketLogService;
    private final ICompanyUserChangeApplyService companyUserChangeApplyService;

    @Login
    @ApiOperation("下级用户列表")
    @GetMapping("/getCompanyUserList")
    public R getCompanyUserList(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        log.debug("下级用户列表 pageNum: {}, pageSize: {}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<CompanyUser> companyUsers = companyUserService.selectCompanySubUserList(Long.parseLong(getUserId()));
        PageInfo<CompanyUser> page = new PageInfo<>(companyUsers);

        // 转换对象
        List<CompanySubUserVO> users = page.getList().stream().map(u -> {
            CompanySubUserVO vo = new CompanySubUserVO();
            BeanUtils.copyProperties(u, vo);

            Map<String, Object> params = new HashMap<>();
            params.put("date", LocalDate.now());
            params.put("companyUserId", u.getUserId());
            params.put("logTypes", Arrays.asList(1,2,4));

            // 今日观看人数
            int count = courseWatchLogService.countByMap(params);
            vo.setTodayWatchCount(count);

            // 今日完播人数
            params.put("logTypes", Collections.singletonList(2));
            int finishCount = courseWatchLogService.countByMap(params);
            vo.setTodayFinishCount(finishCount);

            // 今日完播率
            BigDecimal rate = count > 0 ? BigDecimal.valueOf(finishCount)
                    .divide(BigDecimal.valueOf(count), 2, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100)) : BigDecimal.ZERO;
            vo.setTodayFinishRate(rate);

            // 今日红包金额
            BigDecimal amount = courseRedPacketLogService.getSumByCompanyUserIdId(u.getUserId());
            vo.setTodayRedPacketAmount(amount);

            // 是否存在会员转移申请
            Wrapper<CompanyUserChangeApply> applyWrapper = Wrappers.<CompanyUserChangeApply>lambdaQuery()
                    .eq(CompanyUserChangeApply::getFrom, u.getUserId())
                    .orderByDesc(CompanyUserChangeApply::getApplyTime)
                    .last("limit 1");
            CompanyUserChangeApply apply = companyUserChangeApplyService.getOne(applyWrapper);
            int applyStatus = 3; // 不存在
            if (Objects.nonNull(apply)) {
                applyStatus = apply.getStatus();
            }
            vo.setApplyStatus(applyStatus);

            return vo;
        }).collect(Collectors.toList());

        PageInfo<CompanySubUserVO> pageInfo = new PageInfo<>();
        BeanUtils.copyProperties(page, pageInfo);
        pageInfo.setList(users);

        return R.ok().put("data", pageInfo);
    }

    @Login
    @ApiOperation("获取销售信息")
    @GetMapping("/getCompanyUserInfo")
    public R getCompanyUserInfo(@ApiParam(name = "companyUserId", value = "销售用户ID", required = true)
                                @RequestParam Long companyUserId) {
        return R.ok().put("data", companyUserService.selectCompanyUserById(companyUserId));
    }

    @Login
    @ApiOperation("修改用户信息")
    @PostMapping("/updateUserInfo")
    public R updateUserInfo(@Valid @RequestBody CompanyUserUpdateParam param) {
        CompanyUser companyUser = companyUserService.selectCompanyUserById(param.getUserId());
        if (Objects.isNull(companyUser)) {
            throw new ServiceException("用户不存在");
        }

        companyUser.setUserId(param.getUserId());
        companyUser.setNickName(param.getNickName());
        companyUser.setPhonenumber(param.getPhoneNumber());
        companyUser.setRemark(param.getRemark());
        companyUserService.updateCompanyUser(companyUser);
        return R.ok();
    }

    @ApiOperation("注册")
    @PostMapping("/resisterCompanyUser")
    public R resisterCompanyUser(@Valid @RequestBody CompanyUserParam param) {
        Company company = companyService.selectCompanyById(param.getCompanyId());
        if (Objects.isNull(company)) {
            return R.error("公司不存在");
        }

        // 判断用户数量是否已达到上线
        Integer count = companyUserService.selectCompanyUserCountByCompanyId(param.getCompanyId());
        if(count > company.getLimitUserCount()) {
            return R.error("用户数量已达到上限");
        }

        if (UserConstants.NOT_UNIQUE.equals(String.valueOf(companyUserService.checkUserName(param.getPhoneNumber())))) {
            return R.error("注册用户'" + param.getPhoneNumber() + "'失败，登录账号已存在");
        }

        // 组装参数
        CompanyUser companyUser = new CompanyUser();
        BeanUtils.copyProperties(param, companyUser);

        companyUser.setUserName(param.getPhoneNumber());
        companyUser.setPhonenumber(param.getPhoneNumber());
        companyUser.setPassword(SecurityUtils.encryptPassword(companyUser.getPassword()));
        companyUser.setCreateTime(new Date());

        // 部门
        CompanyDept dept = companyDeptService.getDefaultCompanyDeptByCompanyId(param.getCompanyId());
        if (Objects.nonNull(dept)) {
            companyUser.setDeptId(dept.getDeptId());
        }

        companyUserService.insertUser(companyUser);
        return R.ok();
    }

    @Login
    @ApiOperation("接收群管列表")
    @GetMapping("/companyUserListByCompanyId")
    public R CompanyUserListByCompanyId(){
        // 查询公司下销售
        CompanyUser companyUser = new CompanyUser();
        companyUser.setCompanyId(getCompanyId());
        List<CompanyUser> companyUsers = companyUserService.selectCompanyUserList(companyUser);
        return R.ok().put("data",companyUsers);
    }

    @Login
    @RepeatSubmit
    @ApiOperation("更换会员归属申请")
    @PostMapping("/changeUserParentApply")
    public R changeVipUser(@Valid @RequestBody CompanyUserChangeApplyParam param) {
        // 参数校验
        CompanyUser fromUser = companyUserService.selectCompanyUserById(param.getFrom());
        if (Objects.isNull(fromUser)) {
            return R.error("原归属销售不存在");
        }

        CompanyUser toUser = companyUserService.selectCompanyUserById(param.getTo());
        if (Objects.isNull(toUser)) {
            throw new ServiceException("申请更换归属销售不存在");
        }

        if (param.getType() != 0 && param.getType() != 1) {
            throw new ServiceException("类型不正确");
        }

        if (param.getType() == 1 && (Objects.isNull(param.getIds()) || param.getIds().isEmpty())) {
            throw new ServiceException("请先选择会员");
        }

        // 存在待审核的申请不能再次申请
        Wrapper<CompanyUserChangeApply> applyWrapper = Wrappers.<CompanyUserChangeApply>lambdaQuery()
                .eq(CompanyUserChangeApply::getFrom, fromUser.getUserId())
                .eq(CompanyUserChangeApply::getStatus, 0);
        if (companyUserChangeApplyService.count(applyWrapper) > 0) {
            throw new ServiceException("存在待审核申请");
        }

        CompanyUser companyUser = companyUserService.selectCompanyUserById(Long.parseLong(getUserId()));

        // 添加申请
        companyUserChangeApplyService.apply(param.getFrom(), param.getTo(), param.getType(), param.getIds(), companyUser.getCompanyId(), companyUser.getUserName());
        return R.ok();
    }

    @Login
    @ApiOperation("申请列表")
    @GetMapping("/applyList")
    public R applyList(@RequestParam(required = false) Integer status,
                       @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                       @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        log.debug("申请列表 status: {}, pageNum: {}, pageSize: {}", status, pageNum, pageSize);

        Map<String, Object> map = new HashMap<>();
        map.put("status", status);
        map.put("companyId", getCompanyId());

        PageHelper.startPage(pageNum, pageSize);
        List<CompanyUserChangeApplyVO> list = companyUserChangeApplyService.selectApplyListByMap(map);
        PageInfo<CompanyUserChangeApplyVO> page = new PageInfo<>(list);
        return R.ok().put("data", page);
    }

}
