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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yonge.cooleshow.auth.api.entity.SysRole;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dao.EmployeeDao;
import com.yonge.cooleshow.biz.dal.dto.EmployeeDto;
import com.yonge.cooleshow.biz.dal.dto.search.EmployeeSearch;
import com.yonge.cooleshow.biz.dal.entity.Employee;
import com.yonge.cooleshow.biz.dal.entity.Student;
import com.yonge.cooleshow.biz.dal.entity.Teacher;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.service.EmployeeService;
import com.yonge.cooleshow.biz.dal.service.StudentService;
import com.yonge.cooleshow.biz.dal.service.SysConfigService;
import com.yonge.cooleshow.biz.dal.service.TeacherService;
import com.yonge.cooleshow.biz.dal.service.im.ImGroupCoreService;
import com.yonge.cooleshow.biz.dal.vo.EmployeeVo;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.SysUserType;
import com.yonge.cooleshow.common.enums.UserLockFlag;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.mybatis.dal.BaseDAO;
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 java.util.Date;
import java.util.List;
import java.util.Optional;

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

    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private ImGroupCoreService imGroupCoreService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentService studentService;

    @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 = "klx" + sysUser.getPhone().substring(sysUser.getPhone().length() - 4);
            sysUser.setPassword(new BCryptPasswordEncoder().encode(password));
            sysUser.setGender(param.getGender().getCode());

            String defaultHeard = sysConfigService.findConfigValue(SysConfigConstant.DEFAULT_HEARD);
            sysUser.setAvatar(defaultHeard);

            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);

        // 员工设置为客服时，同步IM账号到三方
        if (Optional.ofNullable(param.getCustomerService()).orElse(false)) {
            imGroupCoreService.register(String.valueOf(param.getUserId()), ClientEnum.SYSTEM.getCode(),
                param.getUsername(), sysUser.getAvatar());
        }

        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);

        // 员工设置为客服时，同步IM账号到三方
        if (Optional.ofNullable(param.getCustomerService()).orElse(false)) {
            imGroupCoreService.register(String.valueOf(param.getUserId()), ClientEnum.SYSTEM.getCode(),
                param.getUsername(), sysUser.getAvatar());
        } else {
            // 员工设置为非客服时，删除IM账号
            if (Optional.ofNullable(employee.getCustomerService()).orElse(false)
                || sysUser.getLockFlag().equals(YesOrNoEnum.YES.getCode())
                || employee.getLockFlag() == UserLockFlag.LOCKED) {

                // 清除客服绑定关系
                clearCustomerService(param.getUserId(), SysUserType.SYSTEM.getCode());
            }
        }
        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);
    }

    /**
     * 清除客服绑定关系
     *
     * @param userId      用户ID
     * @param sysUserType 用户类型
     * @return Boolean
     */
    @Override
    public Boolean clearCustomerService(Long userId, String sysUserType) {
        // 清除客服绑定关系
        String imCustomerServiceId = imGroupCoreService.getImUserId(String.valueOf(userId), sysUserType);

        // 更新老师表的客服ID
        teacherService.lambdaUpdate()
            .eq(Teacher::getImCustomerId, imCustomerServiceId)
            .set(Teacher::getCustomerId, null)
            .set(Teacher::getImCustomerId, "")
            .update();

        // 更新学生表的客服ID
        studentService.lambdaUpdate()
            .eq(Student::getImCustomerId, imCustomerServiceId)
            .set(Student::getCustomerId, null)
            .set(Student::getImCustomerId, "")
            .update();

        return true;
    }

}
