package com.keao.edu.user.service.impl;

import com.keao.edu.auth.api.entity.SysUser;
import com.keao.edu.common.dal.BaseDAO;
import com.keao.edu.common.exception.BizException;
import com.keao.edu.common.page.PageInfo;
import com.keao.edu.common.page.QueryInfo;
import com.keao.edu.common.service.impl.BaseServiceImpl;
import com.keao.edu.im.api.client.ImFeignService;
import com.keao.edu.im.api.entity.ImResult;
import com.keao.edu.im.api.entity.ImUserModel;
import com.keao.edu.user.api.entity.Student;
import com.keao.edu.user.dao.EmployeeDao;
import com.keao.edu.user.dao.StudentDao;
import com.keao.edu.user.dao.StudentExamResultDao;
import com.keao.edu.user.dao.SysUserDao;
import com.keao.edu.user.dto.StudentExamPaymentDto;
import com.keao.edu.user.entity.Employee;
import com.keao.edu.user.page.StudentApplyQueryInfo;
import com.keao.edu.user.service.StudentService;
import com.keao.edu.util.collection.MapUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Joburgess
 * @Date 2020.06.18
 */
@Service
public class StudentServiceImpl extends BaseServiceImpl<Integer, Student> implements StudentService {

    @Autowired
    private StudentDao studentDao;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private StudentExamResultDao studentExamResultDao;
    @Autowired
    private ImFeignService imFeignService;

    @Override
    public BaseDAO<Integer, Student> getDAO() {
        return studentDao;
    }

    @Override
    @Transactional(rollbackFor = Exception.class,isolation = Isolation.SERIALIZABLE)
    public void addStudent(Student student) {
        SysUser sysUser = student.getSysUser();
        if (sysUser == null || StringUtils.isEmpty(sysUser.getPhone())) {
            throw new BizException("参数校验失败");
        }
        SysUser user = sysUserDao.queryByPhone(sysUser.getPhone());
        if (user != null && user.getId() != null) {
            Employee employee = employeeDao.get(user.getId());
            if(employee != null && employee.getDelFlag() == false && employee.getEmployeeType().equals("ORGAN")){
                throw new BizException("手机号被占用");
            }
            Student stu = studentDao.get(user.getId());
            if (stu == null) {
                student.setUserId(user.getId());
//                student.setTenantId(user.getTenantId());
                studentDao.insert(student);
                sysUser.setId(user.getId());
                sysUser.setUserType(user.getUserType() + ",STUDENT");
                sysUserDao.update(sysUser);
            } else {
                throw new BizException("用户已存在");
            }
            return;
        }
        sysUser.setUserType("STUDENT");
        sysUserDao.insert(sysUser);
        ImResult imResult = imFeignService.register(new ImUserModel(sysUser.getId().toString(), sysUser.getRealName(), null));
        sysUser.setImToken(imResult.getToken());
        sysUserDao.update(sysUser);
        student.setUserId(sysUser.getId());
        studentDao.insert(student);
    }

    @Override
    public void updateStudent(Student student) {
        Integer userId = student.getUserId();
        SysUser sysUser = student.getSysUser();
        if (userId == null || StringUtils.isEmpty(sysUser.getPhone())) {
            throw new BizException("参数校验失败");
        }
        SysUser sysUser1 = sysUserDao.queryByPhone(sysUser.getPhone());
        if (sysUser1 != null && !userId.equals(sysUser1.getId())) {
            throw new BizException("手机号已被占用");
        }
        sysUserDao.update(sysUser);
        studentDao.update(student);
    }

    @Override
    public PageInfo<Student> queryStudentPage(QueryInfo queryInfo) {
        PageInfo<Student> studentPageInfo = queryPage(queryInfo);
        List<Student> rows = studentPageInfo.getRows();
        if (rows != null && rows.size() > 0) {
            List<Integer> studentIds = rows.stream().map(e -> e.getUserId()).collect(Collectors.toList());
            //获取考试次数
            Map<Integer, Integer> examNumMap = MapUtil.convertMybatisMap(studentExamResultDao.countExamNum(studentIds, queryInfo.getTenantId()),Integer.class,Integer.class);
            rows.forEach(e -> {
                e.setExamNum(examNumMap.get(e.getUserId()));
            });
        }
        return studentPageInfo;
    }

    @Override
    public PageInfo<StudentExamPaymentDto> queryApplyList(StudentApplyQueryInfo queryInfo) {
        PageInfo<StudentExamPaymentDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);

        List<StudentExamPaymentDto> dataList = null;
        int count = studentDao.countApplyList(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentDao.queryApplyList(params);
            List<Long> basicIds = dataList.stream().map(e -> e.getExamRegistration().getExaminationBasicId()).collect(Collectors.toList());
            Map<Integer, String> basicNameMap = this.getMap("examination_basic", "id_", "name_", basicIds, Integer.class, String.class);
            Map<Integer, String> organNameMap = this.getMap("organization", "id_", "name_", basicIds, Integer.class, String.class);
            Map<Integer, String> subjectNameMap = this.getMap("subject", "id_", "name_", basicIds, Integer.class, String.class);
            dataList.forEach(e -> {
                e.setExamBaseName(basicNameMap.get(e.getExamRegistration().getExaminationBasicId()));
                e.setOrganName(organNameMap.get(e.getExamRegistration().getOrganId()));
                e.setOrganName(subjectNameMap.get(e.getExamRegistration().getSubjectId()));
            });
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public Student getStudent(Integer userId) {
        return studentDao.getStudent(userId);
    }

    @Override
    @Transactional
    public Student updateInfo(Student student) {
        student.setId(student.getUserId());
        if (sysUserDao.update(student) <= 0 || studentDao.update(student) <= 0) {
            throw new BizException("学生信息更新失败，请重试");
        }
        return student;
    }
}
