package cn.com.countrygarden.bi.main.service.wcx.impl;


import cn.com.countrygarden.bi.main.constant.wcx.WcxConstant;
import cn.com.countrygarden.bi.main.dao.wcx.WcxRoleMapper;
import cn.com.countrygarden.bi.main.dao.wcx.WcxUserMapper;
import cn.com.countrygarden.bi.main.dto.wcx.WcxUserDto;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.wcx.ErpEmp;
import cn.com.countrygarden.bi.main.model.wcx.WcxRole;
import cn.com.countrygarden.bi.main.model.wcx.WcxUserNew;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.wcx.WcxUserService;
import cn.com.countrygarden.bi.main.util.PageUtil;
import cn.com.countrygarden.bi.main.util.wcx.CommonUtil;
import com.github.pagehelper.PageRowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class WcxUserServiceImpl implements WcxUserService {

    @Resource
    public WcxUserMapper wcxUserMapper;
    @Resource
    public WcxRoleMapper wcxRoleMapper;
    @Autowired
    private AccessTokenService accessTokenService;

    @Override
    public PageData selectPageList(WcxUserDto dto) {
        int pageOffset = PageUtil.getPageOffset(dto.getPageIndex(), dto.getPageSize());
        dto.setPageOffset(pageOffset);
        String sugRoleId= wcxUserMapper.findRoleId();
        List<WcxUserDto> data= new ArrayList<>(0);
        Integer total;
        if (dto.getRoleId().equals(sugRoleId)){
                dto.setNickName("admin");
                data=wcxUserMapper.selectWcxUser(dto);
           String roleNameSug = wcxUserMapper.findRoleName(dto.getNickName());
            for (WcxUserDto wcxUserDto: data) {
                wcxUserDto.setRoleName(roleNameSug);
            }
            total = wcxUserMapper.selectWcxUserCount(dto);
        }else {
             data = wcxUserMapper.selectPageData(dto);
             total = wcxUserMapper.selectPageCount(dto);
        }
        boolean isFindEmpUnderRole = StringUtils.hasText(dto.getRoleId());
        // 设置前端判断是否勾选状态的标记 如果是人员选择则状态为不勾选, 反之勾选状态
        if (data != null) {
            Integer status = isFindEmpUnderRole ? 1 : 0;
            for (WcxUserDto datum : data) {
                datum.setStatus(status);
            }
        }


        PageRowBounds pageRowBounds = new PageRowBounds(dto.getPageIndex(), dto.getPageSize());
        pageRowBounds.setTotal(total.longValue());
        pageRowBounds.setCount(true);

        PageData pageData = new PageData(data, pageRowBounds);
        return pageData;
    }

    @Override
    public void updateEmpRole(String userId, String roleId) {
        // 如果不传递则,默认设成普通用户
        if (!StringUtils.hasText(roleId)) {
            roleId = getDefaultRoleId();
        }
        wcxUserMapper.updateEmpRole(userId, roleId);
    }

    /**
     * 获取默认角色code
     * @return
     */
    private String getDefaultRoleId(){
        WcxRole param = new WcxRole();
        param.setRoleCode(WcxConstant.ROLE_CODE_IS_NOT_LEADER);
        WcxRole wcxRole = wcxRoleMapper.selectOne(param);
        if (wcxRole == null) {
            throw new ServiceException("不存在编码为default的默认角色");
        }
        return wcxRole.getRoleId();
    }

    @Override
    @Transactional
    public void updateEmpRoleByEmpCardId(String empCardId, String roleId) {
        // 判断是否存在该用户,不存在则新增用户
            WcxUserDto emp = wcxUserMapper.findByEmpCardId(empCardId);
        if (!StringUtils.hasText(roleId)){
            if ( "admin".equals(emp.getNickName())){
                wcxUserMapper.deleteUserNickName(empCardId);
                roleId=emp.getRoleId();
            }else{
                // 如果不传递则,又不是提议管理员 默认设成普通用户
                roleId = getDefaultRoleId();
            }
        }
        
        String userId = null;
        // 判断是否存在该用户,不存在则新增用户
        if (emp == null) {
            userId = CommonUtil.getUUID();
            // 新增一个用户
            ErpEmp erpEmp = wcxUserMapper.selectEmpIdByNameAndCardId(null, empCardId);
            WcxUserNew wcxUserModel = getWcxUserModel(userId ,empCardId, erpEmp.getEmployeeName(), roleId);
            wcxUserMapper.insertOne(wcxUserModel);
        } else {
            //提议管理员 修改nickName
           String sugRoleId= wcxUserMapper.findRoleId();
            if (roleId.equals(sugRoleId)){
                userId = emp.getUserId();
                wcxUserMapper.updateUserSug(userId, "admin");
            }else {
                    userId = emp.getUserId();
                    wcxUserMapper.updateEmpRole(userId, roleId);
            }
        }
    }

    private WcxUserNew getWcxUserModel(String userId, String employeeCardId, String empName, String roleId){
        WcxUserNew wcxUser = new WcxUserNew();
        wcxUser.setUserId(userId);
        wcxUser.setOpenId(CommonUtil.getUUID28()); //  varchar(28) NOT NULL COMMENT '微信的唯一主键',
        wcxUser.setEmployeeId(null); //  int(11) DEFAULT NULL COMMENT '在职员工的唯一主键',
        wcxUser.setCreateDate(new Date()); //  datetime DEFAULT NULL COMMENT '时间日期',
        wcxUser.setStatus(WcxConstant.STATUS_DISABLE); //  int(2) DEFAULT NULL COMMENT '状态',
        wcxUser.setEmployeePhone(null); //  varchar(255) DEFAULT NULL COMMENT '用户手机号',
        wcxUser.setEmployeeName(empName); //  varchar(255) DEFAULT NULL COMMENT '用户姓名',
        wcxUser.setRoleId(roleId); //  varchar(36) NOT NULL COMMENT '用户角色主键',
        wcxUser.setEmployeeCardId(employeeCardId); //
        return wcxUser;
    }

    @Override
    public PageData selectPageList(String roleId, int pageIndex, int pageSize) {
        WcxUserDto param = new WcxUserDto();
        param.setRoleId(roleId);
        param.setPageIndex(pageIndex);
        param.setPageSize(pageSize);
        PageData pageData = selectPageList(param);
        return pageData;
    }

    @Override
    public PageData selectDocUserPageList(String userName, int pageIndex, int pageSize) {
        WcxUserDto param = new WcxUserDto();

        int pageOffset = PageUtil.getPageOffset(pageIndex, pageSize);
        param.setPageOffset(pageOffset);
        param.setPageSize(pageSize);
        param.setUserName(userName);
        List<WcxUserDto> data = wcxUserMapper.selectDocPageData(param);
        // 用于前端判断是否勾选
        if (data != null) {
            for (WcxUserDto datum : data) {
                datum.setStatus(0);
            }
        }
        Long total = wcxUserMapper.selectDocPageCount(param);

        PageRowBounds pageRowBounds = new PageRowBounds(pageIndex, pageSize);
        pageRowBounds.setTotal(total);
        pageRowBounds.setCount(true);

        PageData pageData = new PageData(data, pageRowBounds);
        return pageData;
    }

    /**
     * 获取操作者用户信息
     * @param request
     * @return
     */
    @Override
    public AccessToken getAccessToken(HttpServletRequest request){
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        return token;
    }
}
