/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/6/15
 */
package org.ts.ddcs.UserController.service.impl;


import org.ts.ddcs.UserController.entity.UserEntity;
import org.ts.ddcs.UserController.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;


@Service("UserService")
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public UserEntity getUserInfoByOpenId(String openId) {
        String sql = "SELECT w.OPEN_ID,w.USER_ID FROM t_au_user_wx w WHERE w.OPEN_ID='" + openId + "'";
        List<Map<String, Object>> wxs = jdbcTemplate.queryForList(sql);
        if (null != wxs && wxs.size() == 1) {
            sql = "SELECT u.ID,u.LOGIN_ID,u.USER_NAME,o.ID orgId,o.ORG_NAME FROM t_au_user u ";
            sql += " LEFT JOIN t_au_org_user ou on ou.USER_ID = u.ID ";
            sql += " LEFT JOIN t_au_org o on o.ID = ou.ORG_ID ";
            sql += " WHERE u.IS_VALID=1 AND  u.ID = '" + (String) wxs.get(0).get("USER_ID") + "' ";
            List<UserEntity> list = jdbcTemplate.query(sql, new RowMapper<UserEntity>() {
                @Override
                public UserEntity mapRow(ResultSet resultSet, int i) throws SQLException {
                    UserEntity entity = new UserEntity();
                    entity.setId(resultSet.getString("ID"));
                    entity.setLoginId(resultSet.getString("LOGIN_ID"));
                    entity.setOpenId(openId);
                    entity.setUserName(resultSet.getString("USER_NAME"));
                    entity.setOrgId(resultSet.getString("orgId"));
                    entity.setOrgName(resultSet.getString("ORG_NAME"));
                    return entity;
                }
            });
            if (null != list && list.size() > 0) {
                return list.get(0);
            }
        }
        return null;
    }
}
