package com.ads.business.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ads.business.dao.DocTypeConversationRelDao;
import com.ads.business.dao.DocTypeDao;
import com.ads.business.dao.TypeRoleDao;
import com.ads.business.entity.DocType;
import com.ads.business.entity.DocTypeConversationRel;
import com.ads.business.entity.TypeRole;
import com.ads.business.service.ConversationService;
import com.ads.business.service.DocTypeConversationRelService;
import com.ads.business.service.DocTypeService;
import com.ads.business.service.TypeRoleService;
import com.ads.business.service.model.request.DocTypeDetailRequest;
import com.ads.business.service.model.request.DocTypeEditRequest;
import com.ads.business.service.model.request.DocTypeListRequest;
import com.ads.business.service.model.response.DocTypeDetailResponse;
import com.ads.business.service.model.response.DocTypeListResponse;
import com.ads.common.data.JsonResult;
import com.ads.common.exception.BusinessException;
import com.ads.common.util.OnlineUserUtils;
import com.ads.common.util.PageUtils;
import com.ads.common.util.UtilMessage;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hou
 * @since 2021-10-21
 */
@Service
@Slf4j
public class DocTypeServiceImpl extends ServiceImpl<DocTypeDao, DocType> implements DocTypeService {


    @Value("${docType.linkUrl}")
    private String linkUrl;

    @Resource
    private TypeRoleService typeRoleService;

    @Resource
    private DocTypeConversationRelService docTypeConversationRelService;

    @Resource
    private DocTypeConversationRelDao docTypeConversationRelDao;

    @Resource
    private ConversationService conversationService;

    @Resource
    private TypeRoleDao typeRoleDao;

    @Override
    public JsonResult selectList(DocTypeListRequest request) {
        log.info("文件分类列表 request:{}", JSON.toJSONString(request));
        Long currPage = request.getPage() == null ? 1 : request.getPage().longValue();
        Long pageSize = request.getPageSize() == null ? 10 : request.getPageSize().longValue();
        Page<DocTypeListResponse> page = new Page<>(currPage, pageSize);
        QueryWrapper<DocTypeListResponse> wrapper = new QueryWrapper();
        if (!ObjectUtil.isEmpty(request.getStatus())) {
            wrapper.eq("hdt.status", request.getStatus());
        }
        if (StringUtils.isNotBlank(request.getName())) {
            wrapper.like("hdt.name", request.getName());
        }
        wrapper.orderByDesc("hdt.create_time");
        return JsonResult.success(new PageUtils(this.baseMapper.findPage(page, wrapper)), UtilMessage.GET_MESSAGE_SUCCESS);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult add(DocTypeEditRequest request) {
        log.info("新增文件分类 request:{}", JSON.toJSONString(request));
        List<DocType> list = this.list(Wrappers.lambdaQuery(DocType.class).eq(DocType::getName, request.getName()));
        if (CollectionUtil.isNotEmpty(list)) {
            throw new BusinessException("分类名称已存在");
        }
        List<String> collect = request.getRole().stream().distinct().collect(Collectors.toList());
        if (request.getRole().size() != collect.size()) {
            throw new BusinessException("请勿输入相同手机号");
        }
        DocType docType = new DocType();
        docType.setName(request.getName());
        docType.setLinkUrl(request.getLinkUrl());
        docType.setStatus(request.getStatus());
        docType.setCreateUser(Long.valueOf(OnlineUserUtils.get().getUserId()));
        docType.setCreateTime(new Date());
        docType.setUpdateUser(Long.valueOf(OnlineUserUtils.get().getUserId()));
        docType.setUpdateTime(new Date());
        this.save(docType);

        DocType type = new DocType();
        type.setTypeId(docType.getTypeId());
        type.setLinkUrl(linkUrl + docType.getTypeId() + "&showmenu=false");
        this.updateById(type);
        if (CollectionUtil.isNotEmpty(request.getRole())){
            ArrayList<TypeRole> typeRoles = new ArrayList<>();
            request.getRole().stream().distinct().forEach(e -> {
                TypeRole typeRole = new TypeRole();
                typeRole.setTypeId(docType.getTypeId());
                typeRole.setMobile(e);
                typeRoles.add(typeRole);
            });
            typeRoleDao.insertBatch(typeRoles);
        }

        //新增文件会话关系
        if(CollectionUtil.isNotEmpty(request.getConversationList())){
            //新增
            List<DocTypeConversationRel> relList = new ArrayList<>();
            request.getConversationList().stream().forEach(conversationRequest -> {
                DocTypeConversationRel docTypeConversationRel = new DocTypeConversationRel();
                docTypeConversationRel.setTypeId(docType.getTypeId());
                docTypeConversationRel.setChatId(conversationRequest.getChatId());
                docTypeConversationRel.setOpenConversationId(conversationRequest.getOpenConversationId());
                relList.add(docTypeConversationRel);
            });
            docTypeConversationRelService.saveBatch(relList);
        }
        return JsonResult.success(null, UtilMessage.SAVE_MESSAGE_SUCCESS);
    }

    @Override
    public JsonResult<DocTypeDetailResponse> detail(DocTypeDetailRequest request) {
        log.info("文件分类详情 request:{}", JSON.toJSONString(request));
        DocType docType = this.getById(request.getTypeId());
        if (Objects.isNull(docType)) {
            throw new BusinessException("文件分类不存在");
        }
        DocTypeDetailResponse response = new DocTypeDetailResponse();
        response.setTypeId(docType.getTypeId().toString());
        response.setName(docType.getName());
        response.setStatus(docType.getStatus());
        response.setLinkUrl(docType.getLinkUrl());
        List<TypeRole> list = typeRoleService.list(Wrappers.lambdaQuery(TypeRole.class).eq(TypeRole::getTypeId, docType.getTypeId()));
        if (CollectionUtil.isNotEmpty(list)) {
            List<String> roles = list.stream().map(TypeRole::getMobile).collect(Collectors.toList());
            response.setRole(roles);
        }
        List<DocTypeConversationRel> docTypeRels =docTypeConversationRelDao.getList(request.getTypeId());
        if(CollectionUtil.isNotEmpty(docTypeRels)){
            response.setConversationList(docTypeRels);
        }
        return JsonResult.success(response);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult updateType(DocTypeEditRequest request) {
        log.info("修改文件分类 request:{}", JSON.toJSONString(request));
        DocType docType = this.getById(request.getTypeId());
        if (Objects.isNull(docType)) {
            throw new BusinessException("文件分类不存在");
        }
        List<DocType> list = this.list(Wrappers.lambdaQuery(DocType.class)
                .eq(DocType::getName, request.getName())
                .ne(DocType::getTypeId, request.getTypeId()));
        if (CollectionUtil.isNotEmpty(list)) {
            throw new BusinessException("分类名称已存在");
        }
        List<String> collect = request.getRole().stream().distinct().collect(Collectors.toList());
        if (request.getRole().size() != collect.size()) {
            throw new BusinessException("请勿输入相同手机号");
        }
        docType.setName(request.getName());
        docType.setStatus(request.getStatus());
        docType.setUpdateTime(new Date());
        docType.setUpdateUser(Long.valueOf(OnlineUserUtils.get().getUserId()));
        this.updateById(docType);
        typeRoleService.remove(Wrappers.lambdaQuery(TypeRole.class).eq(TypeRole::getTypeId, docType.getTypeId()));
        if (CollectionUtil.isNotEmpty(request.getRole())){
            ArrayList<TypeRole> typeRoles = new ArrayList<>();
            request.getRole().stream().distinct().forEach(e -> {
                TypeRole typeRole = new TypeRole();
                typeRole.setTypeId(docType.getTypeId());
                typeRole.setMobile(e);
                typeRoles.add(typeRole);
            });
            typeRoleDao.insertBatch(typeRoles);
        }

        //根据文件ID删除
        docTypeConversationRelService.remove(new LambdaQueryWrapper<DocTypeConversationRel>()
                .eq(DocTypeConversationRel::getTypeId,request.getTypeId()));
        //新增文件会话关系
        if(CollectionUtil.isNotEmpty(request.getConversationList())){
            //新增
            List<DocTypeConversationRel> relList = new ArrayList<>();
            request.getConversationList().stream().forEach(conversationRequest -> {
                DocTypeConversationRel docTypeConversationRel = new DocTypeConversationRel();
                docTypeConversationRel.setTypeId(docType.getTypeId());
                docTypeConversationRel.setChatId(conversationRequest.getChatId());
                docTypeConversationRel.setOpenConversationId(conversationRequest.getOpenConversationId());
                relList.add(docTypeConversationRel);
            });
            docTypeConversationRelService.saveBatch(relList);
        }
        return JsonResult.success(null, UtilMessage.SAVE_MESSAGE_SUCCESS);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult updateSwitch(Long id, Integer status) {
        DocType docTypeDb = this.getById(id);
        if (ObjectUtil.isEmpty(docTypeDb)) {
            throw new BusinessException(UtilMessage.USER_EMPTY);
        }
        if (docTypeDb.getStatus().equals(status) && status == 1) {
            throw new BusinessException("文件分类已启用，请勿重复操作！");
        }
        if (docTypeDb.getStatus().equals(status) && status == 0) {
            throw new BusinessException("文件分类已禁用，请勿重复操作！");
        }
        DocType docType = new DocType();
        docType.setTypeId(id);
        docType.setStatus(status);
        this.updateById(docType);

        String msg;
        if (status == 1) {
            msg = UtilMessage.ENABLE_MESSAGE_SUCCESS;
        } else {
            msg = UtilMessage.DISABLE_MESSAGE_SUCCESS;
        }
        return JsonResult.success(null, msg);

    }

    /**
     * 下拉列表
     *
     * @return JsonResult
     */
    @Override
    public JsonResult dropList() {
        return JsonResult.success(baseMapper.getDropList(1));
    }



    /**
     * 下拉列表
     *
     * @return JsonResult
     */
    @Override
    public JsonResult dropListAll() {
        return JsonResult.success(baseMapper.getDropList(2));
    }
}
