package com.mortals.xhx.module.workman.service.impl;

import com.mortals.framework.common.code.UserType;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.SecurityUtil;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.system.role.model.RoleUserQuery;
import com.mortals.xhx.base.system.role.service.RoleUserService;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.module.workman.dao.WorkmanDao;
import com.mortals.xhx.module.workman.model.WorkmanEntity;
import com.mortals.xhx.module.workman.service.WorkmanService;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * WorkmanService
 * 工作人员 service实现
 *
 * @author zxfei
 * @date 2022-01-12
 */
@Service("workmanService")
public class WorkmanServiceImpl extends AbstractCRUDServiceImpl<WorkmanDao, WorkmanEntity, Long> implements WorkmanService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleUserService roleUserService;

    @Override
    protected void findAfter(WorkmanEntity params, Context context, List<WorkmanEntity> list) throws AppException {
        buildList(list);
        super.findAfter(params, context, list);
    }

    @Override
    protected void findAfter(WorkmanEntity params, PageInfo pageInfo, Context context, List<WorkmanEntity> list) throws AppException {
        buildList(list);
        super.findAfter(params, pageInfo, context, list);
    }

    private void buildList(List<WorkmanEntity> list) {
        list.stream().peek(item -> {
            if (!ObjectUtils.isEmpty(item.getSystemUserId())) {
                UserEntity userEntity = userService.get(item.getSystemUserId());
                if (!ObjectUtils.isEmpty(userEntity)) {
                    item.setSystemUserName(userEntity.getRealName());
                }
            }
        }).count();
    }


    @Override
    protected void saveBefore(WorkmanEntity entity, Context context) throws AppException {
        IUser currUser = context.getUser();

        UserEntity user = new UserEntity();
        user.setLoginName(entity.getLoginName());
        user.setLoginPwd(entity.getLoginPwd());
        user.setRealName(entity.getName());
        user.setMobile(entity.getMobile());
        user.setUserType(1);
        user.setStatus(1);
        user.setCreateTime(new Date());
        if (currUser != null) {
            user.setCreateUser(currUser.getLoginName());
            user.setCreateUserName(currUser.getRealName());
            user.setCreateUserId(currUser.getId());
        }
        if (StringUtils.isNotNull(user.getLoginName())) {
            if (StringUtils.isNull(user.getLoginPwd())) {
                throw new AppException("密码不能为空！");
            }
            List<UserEntity> list = userService.find(new UserQuery().loginName(user.getLoginName()));
            if (CollectionUtils.isNotEmpty(list)) {
                throw new AppException("账号已存在！");
            }
            userService.save(user, context);
            if (ObjectUtils.isEmpty(entity.getRoleId())) {
                throw new AppException("未选择用户权限！");
            }
            //添加权限
            RoleUserQuery roleUserQuery = new RoleUserQuery();
            roleUserQuery.setUserId(user.getId());
            roleUserQuery.setRoleIdList(Arrays.asList(new Long[]{entity.getRoleId()}));
            roleUserService.doDistributionRole(roleUserQuery);
            entity.setSystemUserId(user.getId());

        }
        super.saveBefore(entity, context);
    }


    @Override
    protected void updateBefore(WorkmanEntity entity, Context context) throws AppException {

        if (!ObjectUtils.isEmpty(entity.getSystemUserId())) {
            RoleUserQuery roleUserQuery = new RoleUserQuery();
            roleUserQuery.setUserId(entity.getSystemUserId());
            roleUserQuery.setRoleIdList(Arrays.asList(new Long[]{entity.getRoleId()}));
            roleUserService.doDistributionRole(roleUserQuery);
        }

        super.updateBefore(entity, context);
    }

    @Override
    protected void saveAfter(WorkmanEntity entity, Context context) throws AppException {
        super.saveAfter(entity, context);

    }


    @Override
    protected void removeBefore(Long[] ids, Context context) throws AppException {
        Arrays.asList(ids).stream().peek(item -> {
            WorkmanEntity workmanEntity = this.get(item);
            if (!ObjectUtils.isEmpty(workmanEntity) && !ObjectUtils.isEmpty(workmanEntity.getSystemUserId())) {
                //删除用户及其关联信息
                userService.remove(workmanEntity.getSystemUserId(), context);
                RoleUserQuery roleUserQuery = new RoleUserQuery();
                roleUserQuery.setUserId(workmanEntity.getSystemUserId());
                Long[] roleUserIds = roleUserService.find(roleUserQuery).stream().map(m -> m.getId()).toArray(Long[]::new);
                roleUserService.remove(roleUserIds, context);
            }
        }).count();
        super.removeBefore(ids, context);
    }
}