/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yami.shop.bean.app.param.UserRegisterParam;
import com.yami.shop.bean.model.Channel;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.po.EnterpriseUserErrExcelInfo;
import com.yami.shop.bean.po.EnterpriseUserExcelInfo;
import com.yami.shop.bean.po.EnterpriseUserLogPo;
import com.yami.shop.bean.po.EnterpriseUserPo;
import com.yami.shop.bean.vo.EnterpriseUserVo;
import com.yami.shop.bean.vo.UserPointsVO;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.IPHelper;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.dao.ChannelMapper;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.service.UserExtensionService;
import com.yami.shop.service.UserService;
import com.yami.shop.utils.CullenUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author lgh on 2018/09/11.
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;
    private final ChannelMapper channelMapper;
    private final UserExtensionService userExtensionService;


    @Override
    public User getUserByUserId(String userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public void setUserLevelBylevelId(Integer level) {
        userMapper.setUserLevelBylevelId(level);
        userExtensionService.setUserLevelBylevelId(level);
    }

    @Override
    public void setUserLevelByGrowth(Integer level, Integer minNeedGrowth, Integer maxNeedGrowth) {
        userMapper.setMaxUserLevelBylevelId(level, minNeedGrowth, maxNeedGrowth);
        userExtensionService.setMaxUserLevelByLevelId(level, minNeedGrowth, maxNeedGrowth);
    }


    /**
     * 看看有没有校验验证码成功的标识
     *
     * @param userRegisterParam
     * @param checkRegisterSmsFlag
     */
    @Override
    public void validate(UserRegisterParam userRegisterParam, String checkRegisterSmsFlag) {
        if (StrUtil.isBlank(userRegisterParam.getCheckRegisterSmsFlag())) {
            throw new GlobalException("验证码已过期，请重新发送验证码校验");
        } else {
            String checkRegisterSmsFlagMobile = RedisUtil.get(checkRegisterSmsFlag);
            if (!Objects.equals(checkRegisterSmsFlagMobile, userRegisterParam.getMobile())) {
                throw new GlobalException("验证码已过期，请重新发送验证码校验");
            }
        }
    }

    @Override
    public IPage<User> getUserPage(PageParam<User> page, User user) {
        return userMapper.getUserPage(page, user);
    }

    @Override
    public IPage<UserPointsVO> statisticsList(PageParam<User> pageParam, User user) {
        return userMapper.statisticsList(pageParam, user);
    }

    @Override
    public IPage<EnterpriseUserVo> enterpriseUserList(PageParam<EnterpriseUserPo> page, EnterpriseUserPo po) {
        return userMapper.enterpriseUserList(page, po);
    }

    @Override
    public void downloadExcelGoods(HttpServletResponse response) {
        try {
            List<EnterpriseUserExcelInfo> list = Lists.newArrayList();
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("企业员工导入模板", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), EnterpriseUserExcelInfo.class)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet("列表").doWrite(list);
        } catch (IOException e) {
            throw new GlobalException("文件下载异常");
        }
    }

    @Override
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public void uploadExcelGoods(MultipartFile file,String username) {
        List<EnterpriseUserExcelInfo> goodsInfoList = Lists.newArrayList();
        String batchNo = String.valueOf(System.currentTimeMillis());
        EasyExcel.read(file.getInputStream(), EnterpriseUserExcelInfo.class, new PageReadListener<EnterpriseUserExcelInfo>(goodsInfoList::addAll)).sheet().doRead();
        CullenUtils.validateDataThrowException(goodsInfoList.isEmpty(), "请上传企业用户信息...");
        goodsInfoList.forEach(c -> {
            CullenUtils.validateDataThrowException(c.getChannel().contains("必填"), "请删除示例后重试...");
            CullenUtils.validateDataThrowException(c.getPhone()==null,"手机号不能为空...");
            CullenUtils.validateDataThrowException(c.getChannel()==null,"渠道不能为空...");
            CullenUtils.validateDataThrowException(c.getRealName()==null,"姓名不能为空...");
            String phone = c.getPhone().replaceAll("\\s+", "");
            if (phone.length()!=11||!CullenUtils.isNumeric(phone)) {
                userMapper.addUserLog(username,batchNo,"0",c.getChannel(),c.getRealName(),c.getPhone());
            }else {
                addUser(new EnterpriseUserPo(getChannel(c.getChannel()), c.getRealName(), c.getPhone()));
                userMapper.addUserLog(username,batchNo,"1",c.getChannel(),c.getRealName(),c.getPhone());
            }
        });
    }

    @Override
    public void addUser(EnterpriseUserPo po) {
        if (userMapper.selectCount(Wrappers.<User>lambdaQuery().eq(User::getUserMobile, po.getUserMobile())) == 0) {
            User user = new User();
            user.setUserName(po.getUserMobile());
            user.setNickName("企业用户");
            user.setRealName(po.getRealName());
            user.setUserMobile(po.getUserMobile());
            user.setModifyTime(new Date());
            user.setUserRegtime(new Date());
            user.setUserRegip(IPHelper.getIpAddr());
            user.setPic("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132");
            user.setStatus(1);
            user.setLevel(1);
            user.setLevelType(0);
            user.setPlatform(Integer.valueOf(po.getChannelId().toString()));
            user.setChannelId(po.getChannelId());
            user.setUserId(IdUtil.simpleUUID());
            save(user);
        }else {
            System.out.println("已存在...");
        }
    }

    @Override
    public void addUser2(EnterpriseUserPo po) {
        if (userMapper.selectCount(Wrappers.<User>lambdaQuery().eq(User::getUserMobile, po.getUserMobile())) == 0) {
            User user = new User();
            user.setUserName(po.getUserMobile());
            user.setNickName("企业用户");
            user.setRealName(po.getRealName());
            user.setUserMobile(po.getUserMobile());
            user.setModifyTime(new Date());
            user.setUserRegtime(new Date());
            user.setUserRegip(IPHelper.getIpAddr());
            user.setPic("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132");
            user.setStatus(1);
            user.setLevel(1);
            user.setLevelType(0);
            user.setPlatform(Integer.valueOf(po.getChannelId().toString()));
            user.setChannelId(po.getChannelId());
            user.setUserId(IdUtil.simpleUUID());
            save(user);
        }else {
            throw new GlobalException("系统已存在该员工，请勿重复添加...");
        }
    }


    @Override
    public IPage<EnterpriseUserLogPo> enterpriseUserLogList(PageParam<EnterpriseUserLogPo> page) {
        return userMapper.enterpriseUserLogList(page);
    }

    @Override
    public IPage<User> userList(PageParam<User> page, User user) {
        return userMapper.userList(page, user);
    }

    @Override
    public void downloadErrorExcel(HttpServletResponse response, String batchNo) {
        try {
            System.out.println(batchNo);
            List<EnterpriseUserLogPo> userLogErrList = userMapper.enterpriseUserLogErrList(batchNo);
            CullenUtils.validateDataThrowException(userLogErrList.isEmpty(),"该记录暂无错误日志...");
            List<EnterpriseUserErrExcelInfo> list = Lists.newArrayList();
            userLogErrList.forEach(c-> list.add(new EnterpriseUserErrExcelInfo("手机号格式错误",c.getChannel(),c.getRealName(),c.getPhone())));
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("企业员工", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), EnterpriseUserErrExcelInfo.class)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet("列表").doWrite(list);
        } catch (IOException e) {
            throw new GlobalException("文件下载异常");
        }
    }

    private Long getChannel(String channel) {
        List<Channel> channelList = channelMapper.selectList(new LambdaQueryWrapper<Channel>().like(Channel::getChannelName, channel));
        CullenUtils.validateDataThrowException(channelList.isEmpty(), "没有该渠道，请检查后重试...");
        CullenUtils.validateDataThrowException(channelList.size() > 1, "查询到多条渠道，请检查后重试...");
        return channelList.get(0).getId();
    }
}
