package com.foreverwin.mesnac.dispatch.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.service.UserService;
import com.foreverwin.mesnac.dispatch.dto.UserResourceDto;
import com.foreverwin.mesnac.dispatch.mapper.UserResourceMapper;
import com.foreverwin.mesnac.dispatch.model.UserResource;
import com.foreverwin.mesnac.dispatch.service.UserResourceService;
import com.foreverwin.mesnac.meapi.model.NwaUser;
import com.foreverwin.mesnac.meapi.service.NwaUserService;
import com.foreverwin.mesnac.meapi.service.ResrceService;
import com.foreverwin.modular.core.exception.BusinessException;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.FrontPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zjw
 * @since 2021-08-18
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserResourceServiceImpl extends ServiceImpl<UserResourceMapper, UserResource> implements UserResourceService {


    @Autowired
    private UserResourceMapper userResourceMapper;

    @Autowired
    private ResrceService resrceService;


    @Autowired
    private UserService userService;

    @Autowired
    private NwaUserService nwaUserService;

    @Override
    public IPage<UserResource> selectPage(FrontPage<UserResource> frontPage, UserResource userResource) {
        QueryWrapper<UserResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(userResource);
        return super.page(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<UserResource> selectList(UserResource userResource) {
        QueryWrapper<UserResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(userResource);
        return super.list(queryWrapper);
    }


    @Override
    public List<NwaUser> findEmployeeList(String site, String resourceType) {
        return userResourceMapper.findEmployeeList(site, resourceType);
    }

    @Override
    public List<UserResource> findEnableList(String site, String resource, String user) {
        return userResourceMapper.findEnableList(site, resource, user);
    }

    @Override
    public HashMap<String,Object> findAll(UserResourceDto userResourceDto) {
        String site = CommonMethods.getSite();
        String resource = userResourceDto.getResrce();
        String userId = userResourceDto.getUserId();
        HashMap<String, Object> hashMap = new HashMap<>();;


        List<NwaUser> nwaUserList = nwaUserService.selectList(null);

        List<UserResourceDto> userResourceList = userResourceMapper.findAll(site, resource, userId);
        for (int i = 0; i < userResourceList.size(); i++) {
            for (NwaUser nwaUser : nwaUserList) {
                if (nwaUser.getUserName().equals(userResourceList.get(i).getUserId())) {
                    userResourceList.get(i).setUserDescription(nwaUser.getFullName());
                }
            }
        }
        hashMap.put("users",nwaUserList);
        hashMap.put("userResources",userResourceList);
        return hashMap;

    }

    @Override
    public void saveAll(List<UserResourceDto> userResourceDtoList,List<UserResource> deleteTableList) {
        //保存到员工资源对应表里的list
        List<UserResource> userResourceList = new ArrayList<>();
        //保存到Z_NWA_USER表中的list
        ArrayList<NwaUser> nwaUserList = new ArrayList<>();
        String site = CommonMethods.getSite();
        //要删除的数据
        List<String> deleteList = new ArrayList<>();
        if(deleteTableList != null && deleteTableList.size() > 0){
            for (UserResource resource : deleteTableList) {
                deleteList.add(HandleEnum.USER_RESOURCE.getHandle(site,resource.getResrce(),resource.getUserId()));
            }
        }
        if(deleteList.size() > 0) {
            userResourceMapper.deleteBatchIds(deleteList);
        }

        for (int i = 0; i < userResourceDtoList.size(); i++) {
            UserResourceDto userResourceDto = userResourceDtoList.get(i);
            UserResource userResource = new UserResource();
            userResource.setSite(site);
            userResource.setResourceBo(HandleEnum.RESOURCE.getHandle(site, userResourceDto.getResrce()));
            userResource.setResrce(userResourceDto.getResrce());
            userResource.setResrceDescription(userResourceDto.getResrceDescription());
            if (resrceService.findByResrce(userResource.getResrce()) == null) {
                throw BusinessException.build("第" + (i + 1) + "行的资源不存在");
            }
            userResource.setUserId(userResourceDto.getUserId());
            userResource.setTemporaryUser(userResourceDto.getTemporaryUser());
            userResource.setUserDescription(userResourceDto.getUserDescription());
            userResource.setExistUser("false");

            NwaUser temporaryNwaUser = new NwaUser();
            temporaryNwaUser.setUserName(userResource.getUserId());
            List<NwaUser> userByUserName = nwaUserService.selectList(temporaryNwaUser);
            if ("false".equals(userResource.getTemporaryUser()) && userByUserName.size() <= 0) {
                throw BusinessException.build("第" + (i + 1) + "行的用户不存在，必须为临时用户");
            } else if (userByUserName.size() > 0) {
                if ("false".equals(userResource.getTemporaryUser()) && "Y".equals(userByUserName.get(0).getDelFlag())) {
                    throw BusinessException.build("第" + (i + 1) + "行的用户不存在，必须为临时用户");
                }
                if("Y".equals(userByUserName.get(0).getDelFlag())){
                    userResource.setExistUser("false");
                }else{
                    userResource.setExistUser("true");
                    userResource.setUserDescription(userByUserName.get(0).getFullName());
                }

            }

            /**
             * 把临时员工保存到Z_NWA_USER表中，然后把DEL_FLAG设为Y
             */
            if("true".equals(userResource.getTemporaryUser())){
                if((userByUserName.size() <= 0) ||
                    (userByUserName.size() > 0 && "Y".equals(userByUserName.get(0).getDelFlag()))){
                    NwaUser nwaUser = new NwaUser();
                    String uuid = UUID.randomUUID().toString();
                    nwaUser.setHandle(uuid);
                    nwaUser.setSite(site);
                    nwaUser.setUserName(userResourceDto.getUserId());
                    nwaUser.setFullName(userResourceDto.getUserDescription());
                    nwaUser.setDelFlag("Y");
                    if(userByUserName.size() <= 0){
                        nwaUser.setCreateTime(LocalDateTime.now());
                    }else{
                        nwaUser.setHandle(userByUserName.get(0).getHandle());
                    }
                    nwaUser.setUpdateTime(LocalDateTime.now());
                    nwaUserList.add(nwaUser);
                }
            }

                userResource.setStatus(userResourceDto.getStatus());
                userResource.setHandle("UserResourceBo:" + userResource.getSite() + "," +
                        userResource.getResrce() + "," + userResource.getUserId());
                if (userResourceMapper.selectById(userResource.getHandle()) == null) {
                    userResource.setCreatedUser(CommonMethods.getUser());
                    userResource.setCreatedDateTime(LocalDateTime.now());
                }
                userResource.setModifiedUser(CommonMethods.getUser());
                userResource.setModifiedDateTime(LocalDateTime.now());

                userResourceList.add(userResource);
            }
            if (userResourceList.size() > 0) {
                this.saveOrUpdateBatch(userResourceList);
            }
            if(nwaUserList.size() > 0) {
                nwaUserService.saveOrUpdateBatch(nwaUserList);
            }
        }





}