package com.ruoyi.hezhi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.hezhi.domain.TbExamCourse;
import com.ruoyi.hezhi.domain.TbRegion;
import com.ruoyi.hezhi.domain.TbStudyCenter;
import com.ruoyi.hezhi.domain.TbStudyCenterTeacher;
import com.ruoyi.hezhi.domain.dto.StudyCenterDTO;
import com.ruoyi.hezhi.domain.vo.StudyCenterVO;
import com.ruoyi.hezhi.mapper.*;
import com.ruoyi.hezhi.service.ITbStudyCenterService;
import lombok.Getter;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学习中心Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-21
 */
@Service
public class TbStudyCenterServiceImpl implements ITbStudyCenterService
{
    @Autowired
    private TbStudyCenterMapper tbStudyCenterMapper;
    @Autowired
    private TbStudyCenterFileMapper tbStudyCenterFileMapper;
    @Autowired
    private TbRegionMapper tbRegionMapper;
    @Autowired
    private TbExamCourseMapper tbExamCourseMapper;
    @Resource
    private TbStudyCenterTeacherMapper tbStudyCenterTeacherMapper;

    /**
     * 查询学习中心
     *
     * @param studyCenterId 学习中心主键
     * @return 学习中心
     */
    @Override
    public TbStudyCenter selectTbStudyCenterByStudyCenterId(Long studyCenterId)
    {
        TbStudyCenter tbStudyCenter = tbStudyCenterMapper.selectTbStudyCenterByStudyCenterId(studyCenterId);
        if (ObjectUtils.isNotEmpty(tbStudyCenter)){
            List<TbExamCourse> examCourseList = tbExamCourseMapper.getExamCourseList(tbStudyCenter.getStudyCenterId(), null, null, null);
            tbStudyCenter.setExamCourseList(examCourseList);

            List<TbStudyCenterTeacher> studyCenterTeacherList = tbStudyCenterTeacherMapper.getByStudyCenterId(tbStudyCenter.getStudyCenterId());
            tbStudyCenter.setStudyCenterTeacherList(studyCenterTeacherList);
        }

        return tbStudyCenter;
    }

    /**
     * 查询学习中心列表
     *
     * @param tbStudyCenter 学习中心
     * @return 学习中心
     */
    @Override
    public List<TbStudyCenter> selectTbStudyCenterList(TbStudyCenter tbStudyCenter)
    {
        // 机构ID
        if (SecurityUtils.hasRole("localLearningCenter")){
            tbStudyCenter.setStudyCenterId(SecurityUtils.getStudyCenterId());
        }
        return tbStudyCenterMapper.selectTbStudyCenterList(tbStudyCenter);
    }

    /**
     * 查询学习中心列表
     *
     * @return 学习中心
     */
    @Override
    public List<StudyCenterVO> getAllStudyCenterList()
    {
        return tbStudyCenterMapper.getAllStudyCenterList();
    }

    /**
     * 新增学习中心
     *
     * @param tbStudyCenter 学习中心
     * @return 结果
     */
    @Transactional
    @Override
    public int insertTbStudyCenter(TbStudyCenter tbStudyCenter)
    {
        //学习中心名称必须非空唯一
        if (tbStudyCenter.getStudyCenterName() == null){
            throw new ServiceException("学习中心名称不能为空");
        }
        TbStudyCenter studyCenter = tbStudyCenterMapper.selectTbStudyCenterByStudyCenterName(tbStudyCenter.getStudyCenterName());
        if (studyCenter != null){
            throw new ServiceException("学习中心名称已存在");
        }
        if (tbStudyCenter.getProvinceId() != null) {
            TbRegion province = tbRegionMapper.selectTbRegionById(tbStudyCenter.getProvinceId());
            if (province != null) {
                tbStudyCenter.setProvinceName(province.getName());
            }
        }
        if (tbStudyCenter.getCityId() != null) {
            TbRegion city = tbRegionMapper.selectTbRegionById(tbStudyCenter.getCityId());
            if (city != null) {
                tbStudyCenter.setCityName(city.getName());
            }
        }
        if (tbStudyCenter.getAreaId() != null) {
            TbRegion area = tbRegionMapper.selectTbRegionById(tbStudyCenter.getAreaId());
            if (area != null) {
                tbStudyCenter.setAreaName(area.getName());
            }
        }
        tbStudyCenter.setCreateTime(DateUtils.getNowDate());
        int result = tbStudyCenterMapper.insertTbStudyCenter(tbStudyCenter);
        // 新增考试课程
        List<TbExamCourse> examCourseList = tbStudyCenter.getExamCourseList();
        if (!examCourseList.isEmpty()){
            for (TbExamCourse tbExamCourse : examCourseList) {
                tbExamCourse.setStudyCenterId(tbStudyCenter.getStudyCenterId());
                tbExamCourseMapper.insertTbExamCourse(tbExamCourse);
            }
        }
        // 新增教师
        List<TbStudyCenterTeacher> studyCenterTeacherList = tbStudyCenter.getStudyCenterTeacherList();
        if (!studyCenterTeacherList.isEmpty()){
            int i = 0;
            for (TbStudyCenterTeacher studyCenterTeacher : studyCenterTeacherList) {
                if (StringUtils.isBlank(studyCenterTeacher.getTeacherName()) || StringUtils.isBlank(studyCenterTeacher.getTeacherPhone())){
                    throw new ServiceException("请完善老师信息");
                }
                studyCenterTeacher.setStudyCenterId(tbStudyCenter.getStudyCenterId());
                studyCenterTeacher.setSort(i++);
                studyCenterTeacher.setDelFlag(0);
                tbStudyCenterTeacherMapper.insertTbStudyCenterTeacher(studyCenterTeacher);
            }
        }

        return result;
    }

    /**
     * 修改学习中心
     *
     * @param tbStudyCenter 学习中心
     * @return 结果
     */
    @Transactional
    @Override
    public int updateTbStudyCenter(TbStudyCenter tbStudyCenter)
    {
        //学习中心名称必须非空唯一
        if (tbStudyCenter.getStudyCenterName() == null){
            throw new ServiceException("学习中心名称不能为空");
        }
        TbStudyCenter studyCenter = tbStudyCenterMapper.selectTbStudyCenterByStudyCenterId(tbStudyCenter.getStudyCenterId());
        if (studyCenter != null){
            //判断学习中心名称变动了没有
            if (!studyCenter.getStudyCenterName().equals(tbStudyCenter.getStudyCenterName())){
                //如果变动了，要查重
                TbStudyCenter studyCenter1 = tbStudyCenterMapper.selectTbStudyCenterByStudyCenterName(tbStudyCenter.getStudyCenterName());
                if (studyCenter1 != null){
                    throw new ServiceException("学习中心名称已存在");
                }
            }
        }
        if (tbStudyCenter.getProvinceId() != null) {
            TbRegion province = tbRegionMapper.selectTbRegionById(tbStudyCenter.getProvinceId());
            if (province != null) {
                tbStudyCenter.setProvinceName(province.getName());
            }
        }
        if (tbStudyCenter.getCityId() != null) {
            TbRegion city = tbRegionMapper.selectTbRegionById(tbStudyCenter.getCityId());
            if (city != null) {
                tbStudyCenter.setCityName(city.getName());
            }
        }
        if (tbStudyCenter.getAreaId() != null) {
            TbRegion area = tbRegionMapper.selectTbRegionById(tbStudyCenter.getAreaId());
            if (area != null) {
                tbStudyCenter.setAreaName(area.getName());
            }
        }
        // 新增考试课程
        List<TbExamCourse> examCourseList = tbStudyCenter.getExamCourseList();
        if (!examCourseList.isEmpty()){
            tbExamCourseMapper.deleteTbExamCourse(tbStudyCenter.getStudyCenterId(), null, null, null);
            for (TbExamCourse tbExamCourse : examCourseList) {
                tbExamCourse.setStudyCenterId(tbStudyCenter.getStudyCenterId());
                tbExamCourseMapper.insertTbExamCourse(tbExamCourse);
            }
        }
        // 新增教师
        List<TbStudyCenterTeacher> studyCenterTeacherList = tbStudyCenter.getStudyCenterTeacherList();
        if (!studyCenterTeacherList.isEmpty()){
            tbStudyCenterTeacherMapper.deleteByStudyCenterId(tbStudyCenter.getStudyCenterId());
            int i = 0;
            for (TbStudyCenterTeacher studyCenterTeacher : studyCenterTeacherList) {
                if (StringUtils.isBlank(studyCenterTeacher.getTeacherName()) || StringUtils.isBlank(studyCenterTeacher.getTeacherPhone())){
                    throw new ServiceException("请完善老师信息");
                }
                studyCenterTeacher.setStudyCenterId(tbStudyCenter.getStudyCenterId());
                studyCenterTeacher.setSort(i++);
                studyCenterTeacher.setDelFlag(0);
                tbStudyCenterTeacherMapper.insertTbStudyCenterTeacher(studyCenterTeacher);
            }
        }

        tbStudyCenter.setUpdateTime(DateUtils.getNowDate());
        return tbStudyCenterMapper.updateTbStudyCenter(tbStudyCenter);
    }

    /**
     * 批量删除学习中心
     *
     * @param studyCenterIds 需要删除的学习中心主键
     * @return 结果
     */
    @Override
    public int deleteTbStudyCenterByStudyCenterIds(Long[] studyCenterIds)
    {
        return tbStudyCenterMapper.deleteTbStudyCenterByStudyCenterIds(studyCenterIds);
    }

    /**
     * 删除学习中心信息
     *
     * @param studyCenterId 学习中心主键
     * @return 结果
     */
    @Override
    public int deleteTbStudyCenterByStudyCenterId(Long studyCenterId)
    {
        return tbStudyCenterMapper.deleteTbStudyCenterByStudyCenterId(studyCenterId);
    }

    /**
     * 学习中心入驻
     *
     * @param studyCenterDTO
     * @return ok
     */
    @Override
    public AjaxResult joinInStudyCenter(StudyCenterDTO studyCenterDTO) {
        TbStudyCenter enterpriseName = tbStudyCenterMapper.selectTbStudyCenterBy(studyCenterDTO.getEnterpriseName(), null);
        if (enterpriseName != null) {
            return AjaxResult.error("企业名称：" + studyCenterDTO.getEnterpriseName() + "已入驻");
        }
        TbStudyCenter tbStudyCenter1 = tbStudyCenterMapper.selectTbStudyCenterByStudyCenterName(studyCenterDTO.getStudyCenterName());
        if (tbStudyCenter1 != null) {
            return AjaxResult.error("学习中心名称：" + studyCenterDTO.getStudyCenterName() + "已存在");
        }
        TbStudyCenter businessLicenseCreditCode = tbStudyCenterMapper.selectTbStudyCenterBy(null, studyCenterDTO.getBusinessLicenseCreditCode());
        if (businessLicenseCreditCode != null) {
            return AjaxResult.error("营业执照信用代码：" + studyCenterDTO.getBusinessLicenseCreditCode() + "已入驻");
        }
        TbStudyCenter tbStudyCenter = new TbStudyCenter();
        tbStudyCenter.setProvinceId(studyCenterDTO.getProvinceId());
        tbStudyCenter.setCityId(studyCenterDTO.getCityId());
        tbStudyCenter.setAreaId(studyCenterDTO.getAreaId());
        tbStudyCenter.setSuperintendent(studyCenterDTO.getSuperintendent());
        tbStudyCenter.setPhone(studyCenterDTO.getPhone());
        tbStudyCenter.setEnterpriseName(studyCenterDTO.getEnterpriseName());
        tbStudyCenter.setBusinessLicenseCreditCode(studyCenterDTO.getBusinessLicenseCreditCode());
        tbStudyCenter.setBusinessLicenseImg(studyCenterDTO.getBusinessLicenseImg());
        tbStudyCenter.setStudyCenterName(studyCenterDTO.getStudyCenterName());
        tbStudyCenter.setStudyCenterNumber(IdUtils.fastSimpleUUID());
        tbStudyCenter.setCreateTime(DateUtils.getNowDate());
        tbStudyCenter.setExamineStatus(0);
        tbStudyCenter.setFrozenStatus(0);
        tbStudyCenterMapper.insertTbStudyCenter(tbStudyCenter);
        return AjaxResult.success();
    }

    /**
     * 学习中心列表
     *
     * @param params 参数
     * @return 学习中心列表
     */
    @Override
    public List<Map<String, Object>> getStudyCenterList(Map<String, Object> params) {
        return tbStudyCenterMapper.getStudyCenterList(params);
    }

    /**
     * 学习中心详情
     *
     * @param params 参数
     * @return 学习中心详情
     */
    @Override
    public Map<String, Object> getStudyCenterInfo(Map<String, Object> params) {
        Map<String, Object> studyCenterInfo = tbStudyCenterMapper.getStudyCenterInfo(params);
        if (studyCenterInfo != null) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("studyCenterId", studyCenterInfo.get("studyCenterId").toString());
            studyCenterInfo.put("studyCenterFileList", tbStudyCenterFileMapper.getStudyCenterFileList(map));
        }
        return studyCenterInfo;
    }

    @Override
    public List<Map<String, Object>> getStudyCenterEvaluateAgencyList(Long studyCenterId){
        return tbExamCourseMapper.getEvaluateAgencyList(studyCenterId);
    }

    @Override
    public PageInfo<Map<String, Object>> getStudyCenterCourseList(Integer pageNum, Integer pageSize, Long studyCenterId, Long evaluateAgencyId){
        PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> studyCenterCourseList = tbExamCourseMapper.getStudyCenterCourseList(studyCenterId, evaluateAgencyId);
        return new PageInfo<>(studyCenterCourseList);
    }
}
