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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.result.TemplatePrintInfoResult;
import com.qmth.distributed.print.business.entity.BasicTemplate;
import com.qmth.distributed.print.business.mapper.BasicTemplateMapper;
import com.qmth.distributed.print.business.service.BasicTemplateService;
import com.qmth.distributed.print.business.service.ExamCardDetailService;
import com.qmth.distributed.print.business.service.ExamCardService;
import com.qmth.distributed.print.business.util.PdfFillUtils;
import com.qmth.teachcloud.common.config.DictionaryConfig;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicAttachment;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ClassifyEnum;
import com.qmth.teachcloud.common.enums.EnumResult;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.UploadFileEnum;
import com.qmth.teachcloud.common.service.BasicAttachmentService;
import com.qmth.teachcloud.common.service.TeachcloudCommonService;
import com.qmth.teachcloud.common.util.FileStoreUtil;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.stream.Collectors;

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

    @Autowired
    private BasicAttachmentService basicAttachmentService;

    @Autowired
    private ExamCardService examCardService;

    @Autowired
    private ExamCardDetailService examCardDetailService;

    @Resource
    TeachcloudCommonService teachcloudCommonService;

    @Resource
    BasicTemplateMapper basicTemplateMapper;

    @Resource
    DictionaryConfig dictionaryConfig;

    @Resource
    FileStoreUtil fileStoreUtil;

    @Override
    public IPage<TemplateDto> list(Boolean enable, String type, String name, Long startTime, Long endTime, Integer pageNumber, Integer pageSize) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        return this.baseMapper.listPage(new Page<>(pageNumber, pageSize), schoolId, enable, type, SystemConstant.translateSpecificSign(name), startTime, endTime);
    }

    @Transactional
    @Override
    public boolean saveTemplate(String data) throws Exception {
        BasicTemplate template = JSON.parseObject(data, BasicTemplate.class);
        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("模板名称已存在");
            }
            if (StringUtils.isNotBlank((basicTemplate.getPreviewPath()))) {
                JSONObject jsonObject = JSONObject.parseObject(basicTemplate.getPreviewPath());
                String type = jsonObject.getString(SystemConstant.TYPE);
                if (Objects.nonNull(type) && type.equalsIgnoreCase(SystemConstant.LOCAL)) {
                    FileUtils.forceDelete(new File(jsonObject.getString(SystemConstant.PATH)));
                }
            }

            template.setPreviewPath("");
            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")) {
            return teachcloudCommonService.readFileContent(attachment.getPath());
        }
        return null;
    }

    /**
     * 查找模版(机构同级及以下)
     *
     * @param ids
     * @return
     */
    @Override
    public List<TemplatePrintInfoResult> findTemplateInfoByOrgIds(List<Long> ids) {
        return basicTemplateMapper.findTemplateInfoByOrgIds(ids);
    }

    @Override
    public String preview(Long id) {
        BasicTemplate basicTemplate = basicTemplateMapper.selectById(id);
        String classifyStr = basicTemplate.getClassify().name();
        List<String> stringList = ClassifyEnum.listTypes().stream().map(EnumResult::getName).collect(Collectors.toList());
        if (!stringList.contains(classifyStr)) {
            throw ExceptionResultEnum.ERROR.exception("模板类型有误");
        }
        ClassifyEnum classifyEnum = ClassifyEnum.valueOf(classifyStr);

        LocalDateTime nowTime = LocalDateTime.now();
        StringJoiner pdfStringJoiner = new StringJoiner("");
        pdfStringJoiner.add(UploadFileEnum.PDF.getTitle()).add(File.separator);
        pdfStringJoiner.add(String.valueOf(nowTime.getYear())).add(File.separator)
                .add(String.format("%02d", nowTime.getMonthValue())).add(File.separator)
                .add(String.format("%02d", nowTime.getDayOfMonth()));
        pdfStringJoiner.add(File.separator).add(SystemConstant.getUuid()).add(SystemConstant.PDF_PREFIX);

        String pdfDirName = pdfStringJoiner.toString();
        String destUrl = dictionaryConfig.fssLocalPdfDomain().getConfig() + File.separator + pdfDirName;

        // 签到表
        if (ClassifyEnum.SIGN.equals(classifyEnum)) {
            if (StringUtils.isBlank(basicTemplate.getPreviewPath())) {
                JSONObject json = PdfFillUtils.parseSignTempData(basicTemplate.getDisplayRange(), destUrl);
                basicTemplate.setPreviewPath(JSON.toJSONString(json));
                basicTemplateMapper.updateById(basicTemplate);
            }
            return basicTemplate.getPreviewPath() == null ? null : teachcloudCommonService.filePreview(basicTemplate.getPreviewPath());
        } else if (ClassifyEnum.PACKAGE.equals(classifyEnum)) {
            if (StringUtils.isBlank(basicTemplate.getPreviewPath())) {
                JSONObject json = PdfFillUtils.packageTempData(basicTemplate.getDisplayRange(), destUrl);
                basicTemplate.setPreviewPath(JSON.toJSONString(json));
                basicTemplateMapper.updateById(basicTemplate);
            }
            return basicTemplate.getPreviewPath() == null ? null : teachcloudCommonService.filePreview(basicTemplate.getPreviewPath());
        } else if (ClassifyEnum.CHECK_IN.equals(classifyEnum)) {
            BasicAttachment attachment = basicAttachmentService.getById(basicTemplate.getAttachmentId());
            return attachment == null ? null : teachcloudCommonService.filePreview(attachment.getPath());
        } else {
            throw ExceptionResultEnum.ERROR.exception("不支持当前模板预览");
        }
    }
}
