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.mapper.BasicPrintConfigMapper;
import com.qmth.distributed.print.business.service.BasicExamService;
import com.qmth.distributed.print.business.service.BasicPrintConfigService;
import com.qmth.teachcloud.common.bean.dto.DataPermissionRule;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicExam;
import com.qmth.teachcloud.common.entity.BasicPrintConfig;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ClassifyEnum;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.service.BasicRoleDataPermissionService;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 印品配置 服务实现类
 * </p>
 *
 * @author xf
 * @since 2022-02-10
 */
@Service
public class BasicPrintConfigServiceImpl extends ServiceImpl<BasicPrintConfigMapper, BasicPrintConfig> implements BasicPrintConfigService {

    @Resource
    private BasicExamService basicExamService;
    @Resource
    private BasicRoleDataPermissionService basicRoleDataPermissionService;

    @Override
    public IPage<BasicPrintConfig> listPage(Long examId, Boolean enable, Long createStartTime, Long createEndTime, Integer pageNumber, Integer pageSize) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(schoolId, requestUser.getId(), ServletUtil.getRequest().getServletPath());

        Page<BasicPrintConfig> page = new Page<>(pageNumber, pageSize);
        return this.baseMapper.listPage(page, schoolId, examId, enable, createStartTime, createEndTime, dpr);
    }

    @Override
    public boolean enable(Long id, Boolean enable) {
        UpdateWrapper<BasicPrintConfig> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(BasicPrintConfig::getEnable, enable).eq(BasicPrintConfig::getId, id);
        return this.update(updateWrapper);
    }

    @Transactional
    @Override
    public boolean savePrintConfig(BasicPrintConfig basicPrintConfig) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        basicPrintConfig.setSchoolId(schoolId);
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();

        if (basicPrintConfig.getReview()) {
            String auditContent = basicPrintConfig.getAuditContent();
            if (StringUtils.isNotBlank(auditContent) && JSON.parseArray(auditContent, String.class).size() == 0) {
                throw ExceptionResultEnum.ERROR.exception("强制审核内容至少选择一个");
            }
        }

        // 新增
        if (Objects.isNull(basicPrintConfig.getId())) {
            basicPrintConfig.setId(SystemConstant.getDbUuid());
            basicPrintConfig.setOrgId(sysUser.getOrgId());
            basicPrintConfig.setCreateId(sysUser.getId());
            basicPrintConfig.setCreateTime(System.currentTimeMillis());
        }
        // 修改
        else {
            basicPrintConfig.setUpdateId(sysUser.getId());
            basicPrintConfig.setUpdateTime(System.currentTimeMillis());
        }
        return this.saveOrUpdate(basicPrintConfig);
    }

    @Override
    public BasicPrintConfig getByExamId(Long examId) {
        BasicExam basicExam = basicExamService.getById(examId);
        BasicPrintConfig printConfig = this.baseMapper.getBySchoolIdAndExamId(basicExam.getSchoolId(), examId);
        if (printConfig == null) {
            throw ExceptionResultEnum.ERROR.exception("考试[" + basicExam.getName() + "]未配置印品");
        }
        if (!printConfig.getEnable()) {
            throw ExceptionResultEnum.ERROR.exception("考试[" + basicExam.getName() + "]印品配置已禁用");
        }
        return printConfig;
    }

    @Override
    public List<BasicPrintConfig> listBySchoolId(Long schoolId) {
        QueryWrapper<BasicPrintConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicPrintConfig::getSchoolId, schoolId);
        return this.list(queryWrapper);
    }

    @Override
    public void removeByExamId(Long examId) {
        UpdateWrapper<BasicPrintConfig> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(BasicPrintConfig::getExamId, examId);
        this.remove(updateWrapper);
    }

    @Override
    public void updateAttachmentIdByTemplateId(Long templateId, Long attachmentId) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        QueryWrapper<BasicPrintConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicPrintConfig::getSchoolId, schoolId);
        List<BasicPrintConfig> basicPrintConfigList = this.list(queryWrapper);
        for (BasicPrintConfig basicPrintConfig : basicPrintConfigList) {
            String ordinaryContent = basicPrintConfig.getOrdinaryContent();
            if (StringUtils.isNotBlank(ordinaryContent)) {
                List<JSONObject> jsonObjectList = JSON.parseArray(ordinaryContent, JSONObject.class);
                for (JSONObject jsonObject : jsonObjectList) {
                    if (ClassifyEnum.CHECK_IN.name().equals(jsonObject.getString("type")) && templateId.equals(jsonObject.getLong("templateId"))) {
                        jsonObject.put("attachmentId", String.valueOf(attachmentId));
                    }
                }
                basicPrintConfig.setOrdinaryContent(JSON.toJSONString(jsonObjectList));
            }
        }
        this.updateBatchById(basicPrintConfigList);
    }
}
