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

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.core.model.auth.AuthUser;
import com.casic.missiles.core.shiro.ShiroKit;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.system.SignAddRequest;
import com.casic.missiles.dto.system.SignDetailResponse;
import com.casic.missiles.dto.system.SignListRequest;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.PrefixCodeEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.system.SystemSignMapper;
import com.casic.missiles.mapper.system.SystemSignUserRelationMapper;
import com.casic.missiles.model.system.SystemSign;
import com.casic.missiles.model.system.SystemSignUserRelation;
import com.casic.missiles.modular.system.dao.UserMapper;
import com.casic.missiles.modular.system.model.User;
import com.casic.missiles.service.system.ISystemSignService;
import com.casic.missiles.service.system.ISystemSignUserRelationService;
import com.casic.missiles.utils.ConvertUtils;
import com.casic.missiles.utils.NumberGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 系统管理-常用工具-签章/签名管理表 服务实现类
 * </p>
 *
 * @author wangpeng
 * @since 2022-12-01
 */
@Service
public class SystemSignServiceImpl extends ServiceImpl<SystemSignMapper, SystemSign> implements ISystemSignService {
    @Autowired
    private SystemSignMapper signMapper;
    @Autowired
    private ISystemSignUserRelationService userRelationService;
    @Autowired
    private SystemSignUserRelationMapper userRelationMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Page<SystemSign> listPage(Page<SystemSign> page, SignListRequest request) {
        Page<SystemSign> signPage = signMapper.selectSignListPage(page, request);
//        QueryWrapper<SystemSign> wrapper = getWrapper(request);
//        Page<SystemSign> signPage = signMapper.selectPage(page, wrapper);
        return signPage;
    }

    @Override
    public List<SystemSign> list(SignListRequest request) {
//        QueryWrapper<SystemSign> wrapper = getWrapper(request);
        List<SystemSign> signList = signMapper.selectSignList(request);
        return signList;
    }

    @Override
    public ReturnDTO<SignDetailResponse> signDetail(Long id) {
        SignDetailResponse signDetailResponse = signMapper.selectSignDetailById(id);
        if(!Objects.isNull(signDetailResponse.getSignUserId())){
            User user = userMapper.selectById(signDetailResponse.getSignUserId());
            signDetailResponse.setSignUserName(user.getName());
        }
        return ReturnUtil.success(signDetailResponse);
    }

    @Override
    @Transactional
    public ReturnDTO addSign(SignAddRequest request) {
        //生成编号
        Long maxNo = signMapper.selectMaxSignNo();
        String signNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.SIGN_PREFIX, maxNo); //签名签章编号一起
        SystemSign systemSign = ConvertUtils.sourceToTarget(request, SystemSign.class);
        systemSign.setSignNo(signNo);
        int insertFlag = signMapper.insert(systemSign);
        //关联表
        //签名/签章可使用人
        List<Long> userIdList = request.getUserIdList();
        userIdList.add(request.getSignUserId()); //添加签名本人
        List<SystemSignUserRelation> userRelationList = getUserRelations(userIdList, systemSign.getId());
        boolean saveBatch = userRelationService.saveBatch(userRelationList);
        if(insertFlag > 0 && saveBatch){
            return ReturnUtil.success();
        }
        return ReturnUtil.failed("新建失败");
    }

    @Override
    @Transactional
    public ReturnDTO updateSign(SystemSign systemSign) {
        int updateFlag = signMapper.updateById(systemSign);
        //关联表
        //签名/签章可使用人
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("sign_id", systemSign.getId());
        int deleteFlag = userRelationMapper.deleteByMap(columnMap);
        List<Long> userIdList = systemSign.getUserIdList();
        userIdList.add(systemSign.getSignUserId());
        List<SystemSignUserRelation> userRelationList = getUserRelations(systemSign.getUserIdList(), systemSign.getId());
        boolean saveBatch = userRelationService.saveBatch(userRelationList);

        if(updateFlag > 0 && deleteFlag > 0 && saveBatch){
            return ReturnUtil.success();
        }
        return ReturnUtil.failed("更新失败");
    }

    @Override
    public ReturnDTO deleteSign(Long id) {
        if(signMapper.deleteById(id) > 0){
            return ReturnUtil.success();
        }
        return ReturnUtil.failed("刪除失败");
    }

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

    @Override
    public List<SystemSign> usableSign() {
        AuthUser user = ShiroKit.getUser();
        Assert.isFalse(Objects.isNull(user), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        return signMapper.selectUsableSignList(user.getId());
    }

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

//    private QueryWrapper<SystemSign> getWrapper(SignListRequest request) {
//        QueryWrapper<SystemSign> wrapper = new QueryWrapper<>();
//        wrapper.eq("sign_type", request.getSignType());
//        wrapper.like(StringUtils.isNotBlank(request.getSignNo()), "sign_no", request.getSignNo());
//        wrapper.like(StringUtils.isNotBlank(request.getSignName()), "sign_name", request.getSignName());
//        wrapper.like(StringUtils.isNotBlank(request.getSignDirector()), "sign_director", request.getSignDirector());
//        wrapper.eq(!Objects.isNull(request.getSignUserId()), "sign_user_id", request.getSignUserId());
//        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;
//    }
}
