package com.yonge.cooleshow.biz.dal.service.impl;

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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.auth.api.enums.SysUserType;
import com.yonge.cooleshow.biz.dal.dto.EmployeeDto;
import com.yonge.cooleshow.biz.dal.dto.search.EmployeeSearch;
import com.yonge.cooleshow.biz.dal.vo.EmployeeVo;
import com.yonge.cooleshow.common.entity.HttpResponseResult;

import com.yonge.toolset.mybatis.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonge.cooleshow.auth.api.entity.SysRole;
import com.yonge.cooleshow.biz.dal.dao.EmployeeDao;
import com.yonge.cooleshow.biz.dal.entity.Employee;
import com.yonge.cooleshow.biz.dal.service.EmployeeService;
import com.yonge.toolset.mybatis.dal.BaseDAO;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Long, Employee> implements EmployeeService {

    @Autowired
    private EmployeeDao employeeDao;

    @Override
    public BaseDAO<Long, Employee> getDAO() {
        return employeeDao;
    }

    @Override
    public EmployeeVo detail(Long id) {
        EmployeeVo detail = employeeDao.detail(id);
        //用户角色
        List<Long> longs = employeeDao.queryUserRole(id);
        detail.setRoleIds(longs);
        return detail;
    }

    @Override
    public IPage<EmployeeVo> selectPage(IPage<EmployeeVo> page, EmployeeSearch employeeSearch) {
        return page.setRecords(employeeDao.selectPage(page, employeeSearch));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult<EmployeeDto> addEmployee(EmployeeDto param) throws Exception {
        SysUser sysUser = employeeDao.querySysUserByPhone(param.getPhone());
        if (sysUser == null) {
            sysUser = new SysUser();
            BeanUtils.copyProperties(param, sysUser);
            sysUser.setUserType(SysUserType.SYSTEM.getCode());
            //初始密码，手机号后6位
            String password = param.getPhone().substring(param.getPhone().length() - 6);
            sysUser.setPassword(new BCryptPasswordEncoder().encode(password));
            sysUser.setGender(param.getGender().getCode());
            sysUser.setCreateTime(new Date());
            sysUser.setUpdateTime(new Date());
            employeeDao.insertSysUser(sysUser);
        } else {
            Employee employee = employeeDao.get(sysUser.getId());
            if (null != employee || sysUser.getUserType().indexOf(SysUserType.SYSTEM.getCode()) > 0) {
                return HttpResponseResult.failed("该手机号对应用户已经是员工");
            }
            sysUser.setUserType(SysUserType.SYSTEM.getCode() + "," + sysUser.getUserType());
            if(StringUtils.isNotBlank(param.getUsername())){
            	sysUser.setUsername(param.getUsername());
            }
            sysUser.setUpdateTime(new Date());
            employeeDao.updateSysUser(sysUser);
        }
        List<Long> roles = employeeDao.queryUserRole(sysUser.getId());
        param.getRoleIds().removeAll(roles);
        //新增角色
        employeeDao.batchAddEmployeeRole(sysUser.getId(), param.getRoleIds());
        //新增员工表
        param.setUserId(sysUser.getId());
        employeeDao.insert(param);
        return HttpResponseResult.succeed(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult<EmployeeDto> updateEmployee(EmployeeDto param) throws Exception {
        SysUser sysUser = employeeDao.querySysUserById(param.getUserId());
        Employee employee = employeeDao.get(sysUser.getId());
        if (null == sysUser || null == employee) {
            return HttpResponseResult.failed("未找到用户");
        }
        SysUser oldPhoneUser = employeeDao.querySysUserByPhone(param.getPhone());
        if (null != oldPhoneUser && !oldPhoneUser.getId().equals(sysUser.getId())) {
            return HttpResponseResult.failed("手机号已经有用户使用");
        }
        BeanUtils.copyProperties(param, sysUser, "gender");
        sysUser.setGender(param.getGender().getCode());
        employeeDao.updateSysUser(sysUser);

        employeeDao.delEmployeeRole(employee.getUserId());
        employeeDao.batchAddEmployeeRole(employee.getUserId(), param.getRoleIds());

        employeeDao.update(param);
        return HttpResponseResult.succeed(param);
    }

    @Override
    public SysUser queryUserByMobile(String phone) {
        return employeeDao.querySysUserByPhone(phone);
    }


    @Override
    public List<Long> queryUserRole(Long sysUserId) {
        return employeeDao.queryUserRole(sysUserId);
    }

    /**
     * 批量添加角色和菜单关系
     *
     * @param roleId  角色id
     * @param menuIds 菜单集合
     */
    @Override
    public int batchInsertRoleMenu(Long roleId, List<Integer> menuIds) {
        return employeeDao.batchInsertRoleMenu(roleId, menuIds);
    }

    /**
     * 添加角色信息
     *
     * @param sysRole
     */
    @Override
    public int insertSysRole(SysRole sysRole) {
        return employeeDao.insertSysRole(sysRole);
    }

}
