package com.sdut.labex.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sdut.labex.entity.User;
import com.sdut.labex.mapper.UserMapper;
import com.sdut.labex.service.UserService;
import com.sdut.labex.utils.ExcelUtils;
import com.sdut.labex.utils.JWTUtil;
import com.sdut.labex.utils.ResVo;
import com.sdut.labex.utils.SFFileUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * File: UserServiceImpl
 * Created: 2023/6/11
 * Author: springforest
 * Description:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public ResVo login(String id, String password) {
        User user = userMapper.selectById(id);
        if (user == null) {
            return ResVo.error("用户不存在");
        }

        if (password.equals(user.getPassword()) || DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
            Map<String, String> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("role", user.getRole());
            map.put("username", user.getUsername());
            map.put("className", user.getClassName());
            map.put("department", user.getDepartment());
            String token = JWTUtil.getTokenByMap(map);
            map.put("token", token);
            return ResVo.ok(map);
        } else {
            return ResVo.error("密码错误");
        }
    }

    @Override
    public ResVo changePassword(String id, String oldPassword, String newPassword) {
        User user = userMapper.selectById(id);
        if (user == null) {
            return ResVo.error("用户不存在");
        }

        if (oldPassword.equals(user.getPassword()) || DigestUtils.md5DigestAsHex(oldPassword.getBytes()).equals(user.getPassword())) {
            user.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
            userMapper.updateById(user);
        } else {
            return ResVo.error("密码错误");
        }
        return ResVo.ok();
    }

    @Override
    public ResVo add(User user) {
        try {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            userMapper.insert(user);
        } catch (Exception e) {
            return ResVo.error("添加失败");
        }
        return ResVo.ok("添加成功");
    }

    @Override
    public ResVo delete(String id) {
        try {
            userMapper.deleteById(id);
        } catch (Exception e) {
            return ResVo.error("删除失败");
        }
        return ResVo.ok("删除成功");
    }

    @Override
    public ResVo update(User user) {
        try {
            userMapper.updateById(user);
        } catch (Exception e) {
            return ResVo.error("更新失败");
        }
        return ResVo.ok("更新成功");
    }

    @Override
    public ResVo addBatch(MultipartFile file) {
        SFFileUtils sfFile;
        try {
            sfFile = new SFFileUtils(file);
        } catch (Exception e) {
            e.printStackTrace();
            return ResVo.error("文件读取失败");
        }
        ExcelUtils excel;
        try {
            excel = new ExcelUtils(sfFile.getFile(), sfFile.getEndName());
            if (excel.isEmpty) {
                return ResVo.error("Excel文件为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResVo.error("解析Excel出错");
        }

        int startRow = 1;
        int endRow = excel.totalRows;
        List<User> list = new ArrayList<>();
        for (int i = startRow; i < endRow; i++) {
            User user = new User();

            //学号
            try {
                if (excel.readCell(i, 0) == null) {
                    break;
                }
                user.setId(excel.readCell(i, 0));

            } catch (Exception e) {
                e.printStackTrace();
                return ResVo.error("Excel格式错误：第" + (i + 1) + "行第1列");
            }
            //姓名
            try {
                if (excel.readCell(i, 1) == null) {
                    return ResVo.error("Excel格式错误：第" + (i + 1) + "行第2列");
                }
                user.setUsername(excel.readCell(i, 1));
            } catch (Exception e) {
                e.printStackTrace();
                return ResVo.error("Excel格式错误：第" + (i + 1) + "行第2列");
            }
            //默认密码为123456
            user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            //班级
            try {
                if (excel.readCell(i, 2) == null) {
                    return ResVo.error("Excel格式错误：第" + (i + 1) + "行第3列");
                }
                user.setClassName(excel.readCell(i, 2));
            } catch (Exception e) {
                e.printStackTrace();
                return ResVo.error("Excel格式错误：第" + (i + 1) + "行第3列");
            }
            //学院
            try {
                if (excel.readCell(i, 3) == null) {
                    return ResVo.error("Excel格式错误：第" + (i + 1) + "行第4列");
                }
                user.setDepartment(excel.readCell(i, 3));
            } catch (Exception e) {
                e.printStackTrace();
                return ResVo.error("Excel格式错误：第" + (i + 1) + "行第4列");
            }
            //身份
            try {
                if (excel.readCell(i, 4) == null) {
                    return ResVo.error("Excel格式错误：第" + (i + 1) + "行第5列");
                }
                user.setRole(excel.readCell(i, 4));
            } catch (Exception e) {
                e.printStackTrace();
                return ResVo.error("Excel格式错误：第" + (i + 1) + "行第5列");
            }
            list.add(user);
        }

        userMapper.deleteBatchIds(list.stream().map(User::getId).collect(Collectors.toList()));
        try {
            userMapper.insertBatch(list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResVo.error("批量添加失败");
        }
        return ResVo.ok("批量添加成功" + list.size() + "条数据");
    }

    @Override
    public ResVo getUser(int pageNum, int pageSize, User user) {
        Page<User> page = new Page<>(pageNum, pageSize);
        userMapper.getUser(page, user);
        Map<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        map.put("list", page.getRecords());
        return ResVo.ok(map);
    }

}
