package com.casic.missiles.service.Impl.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.system.TemplateAddRequest;
import com.casic.missiles.dto.system.TemplateDetailResponse;
import com.casic.missiles.dto.system.TemplateListRequest;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.PrefixCodeEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.system.SystemTemplateMapper;
import com.casic.missiles.mapper.system.SystemTemplateUserRelationMapper;
import com.casic.missiles.model.system.SystemTemplate;
import com.casic.missiles.model.system.SystemTemplateUserRelation;
import com.casic.missiles.service.system.ISystemTemplateService;
import com.casic.missiles.service.system.ISystemTemplateUserRelationService;
import com.casic.missiles.utils.ConvertUtils;
import com.casic.missiles.utils.NumberGeneratorUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * <p>
 * 系统管理-常用工具-原始记录模板/证书报告模板表 服务实现类
 * </p>
 *
 * @author wangpeng
 * @since 2022-12-01
 */
@Service
public class SystemTemplateServiceImpl extends ServiceImpl<SystemTemplateMapper, SystemTemplate> implements ISystemTemplateService {
    @Autowired
    private SystemTemplateMapper templateMapper;
    @Autowired
    private ISystemTemplateUserRelationService userRelationService;
    @Autowired
    private SystemTemplateUserRelationMapper userRelationMapper;

    @Override
    public Page<SystemTemplate> listPage(Page<SystemTemplate> page, TemplateListRequest request) {
        QueryWrapper<SystemTemplate> wrapper = getWrapper(request);
        Page<SystemTemplate> templatePage = templateMapper.selectPage(page, wrapper);
        return templatePage;
    }

    @Override
    public List<SystemTemplate> list(TemplateListRequest request) {
        QueryWrapper<SystemTemplate> wrapper = getWrapper(request);
        return templateMapper.selectList(wrapper);
    }

    @Override
    public ReturnDTO<TemplateDetailResponse> templateDetail(Long id) {
        TemplateDetailResponse templateDetailResponse = templateMapper.selectTemplateDetailById(id);
        return ReturnUtil.success(templateDetailResponse);
    }

    @Override
    public ReturnDTO addTemplate(TemplateAddRequest request) {
        //生成编号
        Long maxNo = templateMapper.selectMaxTemplateNo();
        String templateNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.TEMPLATE_PREFIX, maxNo); //原始记录模板证书报告模板编号一起
        SystemTemplate systemTemplate = ConvertUtils.sourceToTarget(request, SystemTemplate.class);
        systemTemplate.setTemplateNo(templateNo);
        int insertFlag = templateMapper.insert(systemTemplate);
        //关联表
        //0208原始记录模板和证书报告模板需求更新为都不需要可使用人
        boolean saveBatch = true;
        if(!CollectionUtils.isEmpty(request.getUserIdList())){
            List<SystemTemplateUserRelation> userRelationList = getUserRelations(request.getUserIdList(), systemTemplate.getId());
            saveBatch = userRelationService.saveBatch(userRelationList);
        }
        if(insertFlag > 0 && saveBatch){
            return ReturnUtil.success();
        }
        return ReturnUtil.failed("新建失败");

    }

    @Override
    public ReturnDTO updateTemplate(SystemTemplate systemTemplate) {
        int updateFlag = templateMapper.updateById(systemTemplate);
        //关联表
        int deleteFlag = 1;
        boolean saveBatch = true;
        if(!CollectionUtils.isEmpty(systemTemplate.getUserIdList())){
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("template_id", systemTemplate.getId());
            deleteFlag = userRelationMapper.deleteByMap(columnMap);
            List<SystemTemplateUserRelation> userRelationList = getUserRelations(systemTemplate.getUserIdList(), systemTemplate.getId());
            saveBatch = userRelationService.saveBatch(userRelationList);
        }
        if(updateFlag > 0 && deleteFlag > 0 && saveBatch){
            return ReturnUtil.success();
        }
        return ReturnUtil.failed("更新失败");
    }

    @Override
    public ReturnDTO deleteTemplate(Long id) {
        if(templateMapper.deleteById(id) > 0){
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public ReturnDTO deleteBatchTemplate(List<Long> ids) {
        if(templateMapper.deleteBatchIds(ids) > 0){
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    private List<SystemTemplateUserRelation> getUserRelations(List<Long> userIdList, Long templateId) {
        List<SystemTemplateUserRelation> bsRelations = new ArrayList<>();
        userIdList.forEach(id -> {
            SystemTemplateUserRelation userRelation = new SystemTemplateUserRelation();
            userRelation.setTemplateId(templateId);
            userRelation.setUserId(id);
            bsRelations.add(userRelation);
        });
        return bsRelations;
    }

    private QueryWrapper<SystemTemplate> getWrapper(TemplateListRequest request) {
        QueryWrapper<SystemTemplate> wrapper = new QueryWrapper<>();
        wrapper.eq("template_type", request.getTemplateType());
        wrapper.like(StringUtils.isNotBlank(request.getTemplateNo()), "template_no", request.getTemplateNo());
        wrapper.like(StringUtils.isNotBlank(request.getTemplateName()), "template_name", request.getTemplateName());
        wrapper.like(StringUtils.isNotBlank(request.getTemplateCreator()), "template_creator", request.getTemplateCreator());
        wrapper.apply(StringUtils.isNotBlank(request.getCreateStartTime()),
                "{0} <= DATE_FORMAT(create_time,'%Y-%m-%d')", request.getCreateStartTime().split(" ")[0]);
        wrapper.apply(StringUtils.isNotBlank(request.getCreateEndTime()),
                "{0} >= DATE_FORMAT(create_time,'%Y-%m-%d')", request.getCreateEndTime().split(" ")[0]);
        wrapper.eq("is_del", 0);
        wrapper.orderByDesc("create_time");
        return wrapper;
    }
}
