package hunnu.sj.raise_money.DataBase;
import android.content.Context;

import androidx.core.content.ContextCompat;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import hunnu.sj.raise_money.record.Record;
import hunnu.sj.raise_money.news.News;
import hunnu.sj.raise_money.R;
import hunnu.sj.raise_money.User;

public class UserService {
    public DatabaseHelper db = null;
    public Connection conn = null;
    public UserService(){
        this.db = DatabaseHelper.getDb();
    }

    public int login(String username,String password){
        conn = DatabaseHelper.getConnection();
        Statement sttmt;
        try{
            sttmt = conn.createStatement();
            String sql = "select * from user_info where username = '"+username+"'";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs1 = ps.executeQuery();
            boolean flag1 = rs1.next();
            if(!flag1){
                sttmt.close();
                return 0;       //当用户名不存在时返回0
            }
            ResultSet rs2 = sttmt.executeQuery("select * from user_info where username = '"+username+"'&&password = '"+password+"'");
            boolean flag2 = rs2.next();
            if(!flag2){
                rs2.close();
                sttmt.close();
                return 1;   //当用户名存在，密码错误时返回1
            }
            sttmt.close();
            return 2;       //都正确时，返回2
        }catch (Exception e){
            e.printStackTrace();
        }
            return -1;
    }

    public boolean register(User user){
        conn = DatabaseHelper.getConnection();//将用户的信息上传到数据库，上传成功返回true，失败false
        try{
            String sql = "insert into user_info(username,password,role,phone) values('"+user.getUsername()+"','"+user.getPassword()+"','"+user.getRole()+"','"+user.getPhone()+"')";
            Statement sttmt = conn.createStatement();
            sttmt.executeUpdate(sql);
            sttmt.close();
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

  public boolean donate(long stu_id,long user_id,float money){
      conn = DatabaseHelper.getConnection();//将用户捐款信息上传到数据库，成功返回true，失败返回false
      try{
          String time=getNetTime();
         // Date date = new Date();sdf.format(date)
          //SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateTimeInstance();
          String sql = "insert into record(stu_id,user_id,donatemon,time) values('"+stu_id+"','"+user_id+"','"+money+"','"+time+"')";
          String sql1 ="update stu_info set hasdonated=hasdonated+'"+money+"' where stu_id='"+stu_id+"'";
          //stu_id,stu_name,donatemon,time,username
          Statement sttmt = conn.createStatement();
          sttmt.executeUpdate(sql);
          sttmt.executeUpdate(sql1);
          sttmt.close();
          return true;
      }catch (Exception e){
          e.printStackTrace();
      }
      return false;
  }
  public String getNetTime() throws IOException {
        URL url;
        url = new URL("http://www.baidu.com");
        URLConnection baidu = url.openConnection();//生成连接对象
        baidu.connect(); //发出连接
        long  time13 =  baidu.getDate();
        DateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time13);
        String format = formatter.format(calendar.getTime());
        return format;
  }
  public boolean longterm(String name, Long stu_id,Long user_id){
      conn = DatabaseHelper.getConnection();//将长期资助信息上传到数据库，成功返回true，失败返回false
      try{
          String sql = "insert into usr_long_help(stu_id,user_id,flags) values('"+stu_id+"','"+user_id+"','"+0+"')";
          // where null=(select name from user_info where user_id='"+user_id+"')
          String sql1="update user_info set name='"+name+"' where (select name  from (select name from user_info  where user_id='"+user_id+"') t1 ) is not null";
          //update user_info set name="你的好爸爸" where (select name  from (select name from user_info  where user_id=1) t1 ) is null
          //stuid,useerid,flags
          Statement sttmt = conn.createStatement();
          sttmt.executeUpdate(sql);
          sttmt.executeUpdate(sql1);
          sttmt.close();
          return true;
      }
      catch (Exception e){
          e.printStackTrace();
      }
      return false;
  }
    public User getUserInfo(String username,String password){//从数据库获取用户的角色
        //SQLiteDatabase sdb=dbHelper.getReadableDatabase();
        String sql="select * from user_info where username = '" + username+"'and password = '"+password+"'";
        User user = new User();
        conn = DatabaseHelper.getConnection();
        try{
            Statement sttmt = conn.createStatement();
            ResultSet rs = sttmt.executeQuery(sql);
            rs.next();
            user.setUser_id(rs.getLong("user_id"));
            user.setUsername(rs.getNString("username"));
            user.setPassword(rs.getNString("password"));
            user.setPhone(rs.getNString("phone"));
            user.setRole(rs.getNString("role"));
            rs.close();
            sttmt.close();
            return user;
        }catch (SQLException e){
            e.printStackTrace();
        }
        return null;
    }

    public boolean UploadInfo(News news){//用户上传信息到数据库，服务器
        String sql = "insert into stu_info(name,descri) values('"+news.getName()+"','"+news.getDescri() + "')";
        conn = DatabaseHelper.getConnection();
        try{
            Statement sttmt = conn.createStatement();
            sttmt.executeUpdate(sql);
            sttmt.close();
            return true;
        }catch (SQLException e){
            e.printStackTrace();
        }
        return false;
    }

    public void getAllNews(Context context,ArrayList<News> list){
        //ArrayList<News> mlist = list;
        String sql = "select * from stu_info where flags = 1";
        conn = DatabaseHelper.getConnection();
        try{
            Statement sttmt = conn.createStatement();
            ResultSet rs = sttmt.executeQuery(sql);
            while (rs.next()){
                News news= new News();
                news.setStu_id(rs.getLong("stu_id"));
                news.setName(rs.getNString("name"));
                news.setDescri(rs.getNString("descri"));
                news.setHead_icon(ContextCompat.getDrawable(context, R.drawable.ic_launcher_background));
                list.add(news);
            }
            rs.close();
            sttmt.close();
        }catch(SQLException e){
            e.printStackTrace();
        }
    }

    public void getDonateRecords(ArrayList<Record> recordlist,long user_id){
        String sql = "select * from record,stu_info where record.stu_id = stu_info.stu_id and record.user_id='"+user_id+"'";

        conn = DatabaseHelper.getConnection();
        try{
            Statement sttmt = conn.createStatement();
            ResultSet rs = sttmt.executeQuery(sql);

            while(rs.next()){
                Record record = new Record();
                record.setStu_name(rs.getNString("name"));
                record.setTime(rs.getNString("time"));
                record.setDonatemon(rs.getFloat("donatemon"));
                recordlist.add(record);
            }
            rs.close();
            sttmt.close();
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

    public void getDonatedRecords(ArrayList<Record> recordlist,long id){
        String sql = "select * from record,user_info where record.user_id = user_info.user_id and record.stu_id = '"+id+"'";
        conn = DatabaseHelper.getConnection();
        try{
            Statement sttmt = conn.createStatement();
            ResultSet rs = sttmt.executeQuery(sql);
            while(rs.next()){
                Record record = new Record();
                record.setUser_name(rs.getNString("username"));
                record.setTime(rs.getNString("time"));
                record.setDonatemon(rs.getFloat("donatemon"));
                recordlist.add(record);
            }
            rs.close();
            sttmt.close();
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

}
