package com.qmth.distributed.print.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.distributed.print.business.bean.dto.TemplateDto;
import com.qmth.distributed.print.business.bean.params.ExamCardParams;
import com.qmth.distributed.print.business.entity.*;
import com.qmth.distributed.print.business.enums.CardStatusEnum;
import com.qmth.distributed.print.business.enums.CardTypeEnum;
import com.qmth.distributed.print.business.enums.MakeMethodEnum;
import com.qmth.distributed.print.business.enums.TemplateTypeEnum;
import com.qmth.distributed.print.business.mapper.BasicTemplateMapper;
import com.qmth.distributed.print.business.service.*;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicAttachment;
import com.qmth.teachcloud.common.entity.SysOrg;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.service.BasicAttachmentService;
import com.qmth.teachcloud.common.service.TeachcloudCommonService;
import com.qmth.teachcloud.common.util.ConvertUtil;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 通用模板 服务实现类
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Service
public class BasicTemplateServiceImpl extends ServiceImpl<BasicTemplateMapper, BasicTemplate> implements BasicTemplateService {

    @Autowired
    private BasicTemplateOrgService basicTemplateOrgService;

    @Autowired
    private BasicAttachmentService basicAttachmentService;

    @Autowired
    private ExamCardService examCardService;

    @Autowired
    private ExamCardDetailService examCardDetailService;

    @Resource
    TeachcloudCommonService teachcloudCommonService;

    @Override
    public IPage<TemplateDto> list(Boolean enable, String type, String name, Long startTime, Long endTime, Integer pageNumber, Integer pageSize) {
        Page<TemplateDto> page = new Page<>(pageNumber, pageSize);
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        IPage<TemplateDto> templateDtoIPage = this.baseMapper.listPage(page, schoolId, enable, type, SystemConstant.translateSpecificSign(name), startTime, endTime);
        if (templateDtoIPage.getRecords().size() > 0) {
            templateDtoIPage.getRecords().forEach(m -> {
                //查询适用学院
                List<SysOrg> sysOrgs = basicTemplateOrgService.listByTypeAndTemplateId(type, Long.valueOf(m.getId()));
                m.setOrgs(sysOrgs);

                /*if (type.equals(TemplateTypeEnum.GENERIC.name())) {
                    QueryWrapper<ExamCard> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(ExamCard::getTemplateId, m.getId());
                    List<ExamCard> examCards = examCardService.list(queryWrapper);
                    if (!CollectionUtils.isEmpty(examCards)) {
                        m.setCardId(examCards.get(0).getId().toString());
                    }
                }*/
            });
        }
        return templateDtoIPage;
    }

    @Transactional
    @Override
    public boolean saveTemplate(BasicTemplate template) throws Exception {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        template.setSchoolId(schoolId);
        template.setOrgId(sysUser.getOrgId());
        QueryWrapper<BasicTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicTemplate::getSchoolId, template.getSchoolId()).eq(BasicTemplate::getName, template.getName());
        BasicTemplate basicTemplate = this.getOne(queryWrapper);
        boolean isSuccess;
        // 新增
        if (Objects.isNull(template.getId())) {
            if (basicTemplate != null) {
                throw ExceptionResultEnum.ERROR.exception("模板名称已存在");
            }
            template.insertInfo(sysUser.getId());
            isSuccess = this.save(template);
        }
        // 修改
        else {
            if (basicTemplate != null && basicTemplate.getId().longValue() != template.getId().longValue()) {
                throw ExceptionResultEnum.ERROR.exception("模板名称已存在");
            }

            template.updateInfo(sysUser.getId());
            //删除权限
            basicTemplateOrgService.removeByRuleId(template.getId());
            isSuccess = this.updateById(template);
        }

        // 新增权限
        basicTemplateOrgService.saveBatch(schoolId, template.getType(), template.getId(), template.getOrgIds(), template.getCreateId());

        if (TemplateTypeEnum.GENERIC.name().equals(template.getType().name())) {
            // 通用题卡，同步更新exam_card
            BasicAttachment attachment = basicAttachmentService.getById(template.getAttachmentId());

            ExamCard examCard1 = examCardService.getOneByTemplateId(template.getId());
            if (examCard1 == null) {
                ExamCard examCard = examCardService.getOneByTemplateId(template.getId());
                ExamCardParams examCardParams = new ExamCardParams();
                examCardParams.setId(examCard == null ? null : examCard.getId());
                examCardParams.setOrgId(sysUser.getOrgId());
                examCardParams.setTitle(template.getName());
                examCardParams.setMakeMethod(MakeMethodEnum.SELECT);// 默认SELECT
                examCardParams.setType(CardTypeEnum.GENERIC); // 默认GENERIC
                examCardParams.setTemplateId(template.getId());
                examCardParams.setStatus(CardStatusEnum.SUBMIT); // 默认SUBMIT
                examCardParams.setHtmlContent(teachcloudCommonService.readFileContent(attachment.getPath()));
                examCardService.saveExamCard(examCardParams);
            } else {
                examCard1.setTitle(template.getName());
                examCardService.updateById(examCard1);

                ExamCardDetail examCardDetail = examCardDetailService.getByCardId(examCard1.getId());
                examCardDetail.setHtmlContent(teachcloudCommonService.readFileContent(attachment.getPath()));
                examCardDetailService.updateById(examCardDetail);
            }
        }
        return isSuccess;
    }

    @Override
    public boolean enable(BasicTemplate template) {
        // 校验模板是否已有绑定命题任务
//        boolean used = examCardService.usedCardByTemplateId(template.getId());
//        if (used && !template.getEnable()) {
//            throw ExceptionResultEnum.ERROR.exception("通用题卡模板已绑定任务，不能禁用");
//        }
        UpdateWrapper<BasicTemplate> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(BasicTemplate::getEnable, template.getEnable()).eq(BasicTemplate::getId, template.getId());
        return this.update(updateWrapper);
    }

    @Override
    public BasicTemplate getOne(Long id) {
        BasicTemplate basicTemplate = this.getById(id);
        if (basicTemplate.getAttachmentId() != null) {
            BasicAttachment basicAttachment = basicAttachmentService.getById(basicTemplate.getAttachmentId());
            if (basicAttachment == null) {
                throw ExceptionResultEnum.ERROR.exception("附件数据异常");
            }
            String url = teachcloudCommonService.filePreview(basicAttachment.getPath());
            basicTemplate.setUrl(url);
        }
        return basicTemplate;
    }

    @Override
    public Object readContent(Long attachmentId) {
        BasicAttachment attachment = basicAttachmentService.getById(attachmentId);
        if (attachment.getType().equals(".ftl") || attachment.getType().equals(".html")) {
            String content = teachcloudCommonService.readFileContent(attachment.getPath());
            return content;
        }
        return null;
    }

}
