NewDBManager.java 32.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
package com.gimi.common.cinema.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;
import com.gimi.common.cinema.model.LocalMovieMessage;
import com.gimi.common.cinema.model.QueryType;
import com.gimi.common.cinema.model.SourceType;
import com.gimi.common.cinema.utils.LogUtils;
import com.xgimi.gimicinema.activity.CinemaConfig;
import com.xgimi.gimicinema.application.FangTangApplication;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class NewDBManager {
    private static NewDBManager mNewDBManager;
    private SQLiteDatabase db;

    public NewDBManager(Context context) {
        NewDBHelper helper = new NewDBHelper(context);
        //因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);
        //所以要确保context已初始化,可以把实例化DBManager的步骤放在Activity的onCreate里
        db = helper.getWritableDatabase();
    }

    public static NewDBManager getInstance() {
        if (mNewDBManager == null) {
            synchronized (NewDBManager.class) {
                if (mNewDBManager == null) {
                    mNewDBManager = new NewDBManager(FangTangApplication.getInstance().getApplicationContext());
                }
            }
        }
        return mNewDBManager;
    }


    /**
     * 利用事务批量添加本地数据
     *
     * @param localMovieMessageList movie list
     * @param clear                 if clear
     * @return boolean
     */
    public boolean add(List<LocalMovieMessage> localMovieMessageList, boolean clear) {
        boolean result = false;
        db.beginTransaction();  //开始事务
        try {
            //do delete if need
            if (clear) {
                db.delete(NewDBHelper.TABLE_NAME, null, null);
            }
            for (LocalMovieMessage person : localMovieMessageList) {
                ContentValues cv = constructCv(person);
                db.insert(NewDBHelper.TABLE_NAME, null, cv);
            }
            db.setTransactionSuccessful();  //设置事务成功完成
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        } finally {
            db.endTransaction();    //结束事务
        }
        return result;
    }

    /**
     * public static final String ID = "id";
     * public static final String NAME = "name";
     * public static final String PATH = "path";
     * public static final String POSTER_PATH = "poster_path";
     * public static final String PINYIN = "pinyin";
     * public static final String TYPE = "type";
     * public static final String DOUBAN_ID = "douban_id";
     * public static final String MD5 = "md5";
     * public static final String CLASS_DESCRIBE = "class_describe";
     * public static final String MOVIE_LENGTH = "movie_length";
     * public static final String DOUBAN_RATING = "douban_rating";
     *
     * @param localMovieMessage movie msg
     * @return contentValues
     */
    private ContentValues constructCv(LocalMovieMessage localMovieMessage) {
        ContentValues cv = new ContentValues();
        cv.put(NewDBHelper.NAME, localMovieMessage.getMovieName());
        cv.put(NewDBHelper.PATH, localMovieMessage.getPlayPath().replace(CinemaConfig.BASIC_ROOT, ""));
        String posterPath = localMovieMessage.getPosterPath();
        if (!TextUtils.isEmpty(posterPath)) {
            cv.put(NewDBHelper.POSTER_PATH, posterPath.replace(CinemaConfig.BASIC_ROOT, ""));
        }
        cv.put(NewDBHelper.PINYIN, localMovieMessage.getNamePinyin());
        cv.put(NewDBHelper.MD5, localMovieMessage.getMd5());
        if (localMovieMessage.getDoubanRating() != 0) {
            cv.put(NewDBHelper.DOUBAN_RATING, localMovieMessage.getDoubanRating());
        }
        if (localMovieMessage.getCount() != 0) {
            cv.put(NewDBHelper.MOVIE_COUNT, localMovieMessage.getCount());
        }
        if (!TextUtils.isEmpty(localMovieMessage.getDoubanId())) {
            cv.put(NewDBHelper.DOUBAN_ID, localMovieMessage.getDoubanId());
        }
        if (!TextUtils.isEmpty(localMovieMessage.getDlTime())) {
            cv.put(NewDBHelper.MOVIE_DL_TIME, localMovieMessage.getDlTime());
        }
        if (localMovieMessage.getClassDescribe() != null) {
            cv.put(NewDBHelper.CLASS_DESCRIBE, localMovieMessage.getClassDescribe());
        }
        if (localMovieMessage.getMovieLength() != null) {
            cv.put(NewDBHelper.MOVIE_LENGTH, localMovieMessage.getMovieLength());
        }
        if (localMovieMessage.getType() != null) {
            cv.put(NewDBHelper.TYPE, localMovieMessage.getType());
        }
        if (localMovieMessage.getScreenTime() != null) {
            cv.put(NewDBHelper.SCREEN_TIME, localMovieMessage.getScreenTime());
        }
        return cv;
    }

    /**
     * 利用事务批量添加本地数据,存在的数据不再更新,不存在的直接插入
     *
     * @param localMovieMessageList lst
     * @return boolean
     */
    public boolean add1905(List<LocalMovieMessage> localMovieMessageList) {
        boolean result = false;
        for (LocalMovieMessage localMovieMessage : localMovieMessageList) {
            result = insertLocalMM1905(localMovieMessage);
        }
        return result;
    }

    private boolean insertLocalMM1905(LocalMovieMessage localMovieMessage) {
        int id = queryId1905(localMovieMessage);
        return updateLocalMM1905(localMovieMessage, id);
    }

    private int queryId1905(LocalMovieMessage lmm) {
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        Cursor c = db.query(NewDBHelper.TABLE_NAME, null, "md5 = ? and path = ?",
                new String[]{"qnyb_abc_test", lmm.getPlayPath()}, null, null, null);
        readCursor2List(persons, c);
        c.close();
        if (persons.size() == 0) {
            return -1;
        } else {
            for (LocalMovieMessage person : persons) {
                if (person.getPlayPath().equals(lmm.getPlayPath())
                        && person.getMd5().equals(lmm.getMd5())) {
                    return person.getId();
                }
            }
            return -1;
        }
    }

    private boolean updateLocalMM1905(LocalMovieMessage localMovieMessage, int id) {
        boolean result;
        if (id == -1) {
            result = add(localMovieMessage, true);
        } else {
            return updateDoubanMsg(localMovieMessage);
        }
        return result;
    }

    /**
     * 利用事务批量添加本地数据,存在的数据不再更新,不存在的直接插入
     *
     * @param localMovieMessageList lst
     * @return boolean
     */
    public boolean add(List<LocalMovieMessage> localMovieMessageList) {
        boolean result = false;
        for (LocalMovieMessage localMovieMessage : localMovieMessageList) {
            result = insertLocalMM(localMovieMessage);
        }
        return result;
    }

    /**
     * 利用事务批量添加本地数据,存在的数据不再更新,不存在的直接插入
     *
     * @param localMovieMessageList lst
     * @return boolean
     */
    public boolean addByTransaction(List<LocalMovieMessage> localMovieMessageList) {
        boolean result = false;
        LogUtils.i("scan-time Transaction", System.currentTimeMillis() + "");
        db.beginTransaction();  //开始事务
        try {
            for (int i = 0; i < localMovieMessageList.size(); i++) {
                ContentValues values = constructCv(localMovieMessageList.get(i));
                db.insertWithOnConflict(NewDBHelper.TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE);
            }
            db.setTransactionSuccessful();
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();    //结束事务
        }
        LogUtils.i("scan-time Transaction", System.currentTimeMillis() + ":" + result);
        return result;
    }

    public void deleteFileNotExists() {
        List<LocalMovieMessage> result = query();
        for (LocalMovieMessage lmm : result)
            if (!new File(lmm.getPlayPath()).exists()
                    && !"qnyb_abc_test".equals(lmm.getMd5())) {
                delete(lmm);
                Log.d("lovely", "delete success " + lmm.getMovieName());
            }
    }

    /**
     * 单个添加本地数据
     *
     * @param localMovieMessage movie message
     */
    public void add(LocalMovieMessage localMovieMessage) {
        db.beginTransaction();  //开始事务
        try {
            ContentValues contentValues = constructCv(localMovieMessage);
            db.insert(NewDBHelper.TABLE_NAME, null, contentValues);
            db.setTransactionSuccessful();  //设置事务成功完成
        } finally {
            db.endTransaction();    //结束事务
        }
    }

    /**
     * 单个添加本地数据
     *
     * @param localMovieMessage local
     */
    public boolean add(LocalMovieMessage localMovieMessage, boolean insert) {
        boolean result = false;
        db.beginTransaction();  //开始事务
        try {
            if (insert) {
                ContentValues contentValues = constructCv(localMovieMessage);
                db.insert(NewDBHelper.TABLE_NAME, null, contentValues);
            } else {
                ContentValues contentValues = constructCv(localMovieMessage);
                db.updateWithOnConflict(NewDBHelper.TABLE_NAME, contentValues, "id=?",
                        new String[]{String.valueOf(localMovieMessage.getId())}, SQLiteDatabase.CONFLICT_REPLACE);
//                db.update(NewDBoHelper.TABLE_NAME, contentValues, " id = ", new String[]{String.valueOf(localMovieMessage.getId())});
            }
            db.setTransactionSuccessful();  //设置事务成功完成
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();    //结束事务
        }
        return result;
    }


    private int queryId(LocalMovieMessage lmm) {//not right
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        Cursor c = db.query(NewDBHelper.TABLE_NAME, null, "md5 = ?", new String[]{lmm.getMd5()}, null, null, null);
        readCursor2List(persons, c);
        c.close();
        if (persons.size() == 0) {
            return -1;
        } else {
            for (LocalMovieMessage person : persons) {
                if (person.getPlayPath().equals(lmm.getPlayPath()) && person.getMd5().equals(lmm.getMd5())
                        && person.getPlayPath().startsWith("/mnt/samba")) {
                    return person.getId();
                }
            }
            return -1;
        }
    }

    private LocalMovieMessage queryByPath(String lmm) {
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        Cursor c = db.query(NewDBHelper.TABLE_NAME, null, "path = ?", new String[]{lmm}, null, null, null);
        readCursor2List(persons, c);
        c.close();
        if (persons.size() == 0) {
            return null;
        } else {
            for (LocalMovieMessage person : persons) {
                if (person.getPlayPath().equals(lmm)) {
                    return person;
                }
            }
            return null;
        }
    }

    private void readCursor2List(ArrayList<LocalMovieMessage> persons, Cursor c) {
        while (c.moveToNext()) {
            LocalMovieMessage person = new LocalMovieMessage();
            person.setId(c.getInt(c.getColumnIndex(NewDBHelper.ID)));
            person.setMovieName(c.getString(c.getColumnIndex(NewDBHelper.NAME)));
            person.setPlayPath(c.getString(c.getColumnIndex(NewDBHelper.PATH)));
            person.setPosterPath(c.getString(c.getColumnIndex(NewDBHelper.POSTER_PATH)));
            person.setNamePinyin(c.getString(c.getColumnIndex(NewDBHelper.PINYIN)));
            person.setType(c.getString(c.getColumnIndex(NewDBHelper.TYPE)));
            person.setDoubanId(c.getString(c.getColumnIndex(NewDBHelper.DOUBAN_ID)));
            person.setMd5(c.getString(c.getColumnIndex(NewDBHelper.MD5)));
            person.setClassDescribe(c.getString(c.getColumnIndex(NewDBHelper.CLASS_DESCRIBE)));
            person.setMovieLength(c.getString(c.getColumnIndex(NewDBHelper.MOVIE_LENGTH)));
            int columnIndex = c.getColumnIndex(NewDBHelper.DOUBAN_RATING);
            person.setDoubanRating(c.getDouble(columnIndex));
            int timeIndex = c.getColumnIndex(NewDBHelper.LAST_PLAY_TIME);
            if (timeIndex != -1) {
                person.setLastPlayTime(c.getLong(timeIndex));
            }
            int screenIndex = c.getColumnIndex(NewDBHelper.SCREEN_TIME);
            if (screenIndex != -1) {
                person.setScreenTime(c.getString(screenIndex));
            }
            int dlTimeIdx = c.getColumnIndex(NewDBHelper.MOVIE_DL_TIME);
            if (dlTimeIdx != -1) {
                person.setDlTime(c.getString(dlTimeIdx));
            }
            int countIdx = c.getColumnIndex(NewDBHelper.MOVIE_COUNT);
            if (countIdx != -1) {
                person.setCount(c.getInt(countIdx));
            }
            persons.add(person);
        }
    }

    private boolean insertLocalMM(LocalMovieMessage localMovieMessage) {
        int id = queryId(localMovieMessage);
        return updateLocalMM(localMovieMessage, id);
    }

    private boolean updateLocalMM(LocalMovieMessage localMovieMessage, int id) {
        boolean result;
        if (id == -1) {
            result = add(localMovieMessage, true);
        } else {
            localMovieMessage.setId(id);
            result = add(localMovieMessage, false);
        }
        return result;
    }

    /**
     * query all
     *
     * @return persons
     */
    public List<LocalMovieMessage> query() {
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        Cursor c = db.query(NewDBHelper.TABLE_NAME, null, null, null, null, null, null);
        readCursor2List(persons, c);
        c.close();
        return persons;
    }

    /**
     * query queryIdNotNullAndPostNull
     *
     * @return persons
     */
    public List<LocalMovieMessage> queryIdNotNullAndPostNull() {
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        getNullItems(persons, NewDBHelper.DOUBAN_ID + " is not null and " + NewDBHelper.POSTER_PATH + " is null");
        return persons;
    }

    private void getNullItems(ArrayList<LocalMovieMessage> persons, String condition) {
        Cursor c = db.query(NewDBHelper.TABLE_NAME, null, condition, null, null, null, null);
        readCursor2List(persons, c);
        c.close();
    }

    /**
     * query poster
     *
     * @return persons
     */
    public ArrayList<LocalMovieMessage> queryPosterDoubanIdNull() {
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        getNullItems(persons, NewDBHelper.POSTER_PATH + "  is null and " + NewDBHelper.DOUBAN_ID + " is null");
        return persons;
    }

    /**
     * query all movie from 1905 and qn
     *
     * @return persons
     */
    public List<LocalMovieMessage> queryType(String key, QueryType queryType, SourceType sourceType) {
        String sql = "SELECT distinct(path),id,name,poster_path,path,pinyin,md5,douban_id,type,class_describe,movie_length,douban_rating,screen_time" +
                " FROM movie_message where";/* + " path like '%" + key + "%'";*/
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        StringBuffer sb = new StringBuffer(sql);

        String queryQn = " path like '%/" + key + "/%'";
        if (sourceType == SourceType.SOURCE_ALL || sourceType == SourceType.SOURCE_JUST_QN) {
            sb.append(queryQn);
        }

        String order = " order by pinyin asc";
        switch (queryType) {
            case QUERY_TYPE_SCREEN_TIME:
                order = " order by screen_time desc";
                break;
            case QUERY_TYPE_RATING:
                order = " order by douban_rating desc";
                break;
            case QUERY_TYPE_DOWNLOAD_TIME:
                order = " order by cast(movie_dl_time as int) desc";
                break;
            case QUERY_TYPE_DEMAND:
                order = " order by cast(movie_count as int) desc";
                break;
            default:
                order = " order by screen_time desc";
                break;
        }
//        String order = " order by " + orderKey + (isUp ? " desc" : " asc");
        String sqlSub = " and path not like '%/LXJ/%'";
        if (key.equals("XJ/")) {
            if (sourceType == SourceType.SOURCE_ALL || sourceType == SourceType.SOURCE_JUST_QN) {
                sb.append(sqlSub);
            }
        }

        //if use 1905
        String query1905 = getAppendCond(key);
        if (sourceType == SourceType.SOURCE_ALL || sourceType == SourceType.SOURCE_JUST_1905) {
            if (sourceType == SourceType.SOURCE_ALL) {
                if (!TextUtils.isEmpty(query1905)) {
                    sb.append(" or ");
                }
            }
            sb.append(query1905);
        }
        if (sourceType == SourceType.SOURCE_JUST_1905 && TextUtils.isEmpty(query1905)) {
            return persons;
        }
//        sb.append(query1905);

        sb.append(order);

        Cursor c = db.rawQuery(sb.toString(), null);
        readCursor2List(persons, c);
        c.close();
        return persons;
    }

    private static final int RECOMMEND_MOVIE_COUNT = 200;
    private static final int PXB_MOVIE_COUNT = 200;

    /**
     * query all recommend qn
     *
     * @return persons
     */
    public List<LocalMovieMessage> queryAllNewMovies() {
        String sql = "SELECT * FROM movie_message order by cast(movie_dl_time as int) desc limit " + RECOMMEND_MOVIE_COUNT;/* + " path like '%" + key + "%'";*/
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        StringBuffer sb = new StringBuffer(sql);

        Cursor c = db.rawQuery(sb.toString(), null);
        readCursor2List(persons, c);
        c.close();
        return persons;
    }

    /**
     * query all recommend qn
     *
     * @return persons
     */
    public List<LocalMovieMessage> queryRandomMovies() {
//        String sql = "SELECT * FROM movie_message order by cast(movie_dl_time as int) desc limit " + 1;/* + " path like '%" + key + "%'";*/
//        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
//        StringBuffer sb = new StringBuffer(sql);
//
//        Cursor c = db.rawQuery(sb.toString(), null);
//        readCursor2List(persons, c);
//        c.close();
        return queryTJLimit(1);
    }

    /**
     * query all recommend qn
     *
     * @return persons
     */
    public LocalMovieMessage queryPlayMovie(String md5) {
        md5 = md5.toUpperCase();
        Log.d("room-info", "md5:" + md5);
        String sql = "SELECT * FROM movie_message where md5 = '" + md5 + "'" + " COLLATE NOCASE;";

        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        StringBuffer sb = new StringBuffer(sql);

        Cursor c = db.rawQuery(sb.toString(), null);
        readCursor2List(persons, c);
        c.close();
        if (persons.size() >= 1) {
            return persons.get(0);
        }
        return null;
    }

    /**
     * query all recommend qn
     *
     * @return persons
     */
    public List<LocalMovieMessage> queryAllDemandMovies() {
        String sql = "SELECT * FROM movie_message order by cast(" + NewDBHelper.MOVIE_COUNT + " as int) desc, cast(movie_dl_time as int) desc limit " + PXB_MOVIE_COUNT;/* + " path like '%" + key + "%'";*/
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        StringBuffer sb = new StringBuffer(sql);

        Cursor c = db.rawQuery(sb.toString(), null);
        readCursor2List(persons, c);
        c.close();
        return persons;
    }

    private String getAppendCond(String key) {
        String rtn = "";
        if (key.contains("KH")) {
            rtn = " class_describe like '%科幻%' and md5 = 'qnyb_abc_test'";
            return rtn;
        } else if (key.contains("DZ")) {
            rtn = " class_describe like '%动作%' and md5 = 'qnyb_abc_test'";
            return rtn;
        } else if (key.contains("KB")) {
            rtn = " class_describe like '%恐怖%' and md5 = 'qnyb_abc_test'";
            return rtn;
        } else if (key.contains("XJ")) {
            if (!key.contains("LXJ")) {
                rtn = " class_describe like '%喜剧%' and md5 = 'qnyb_abc_test'";
            }
            return rtn;
        } else if (key.contains("AQ")) {
            rtn = " class_describe like '%爱情%' and md5 = 'qnyb_abc_test'";
            return rtn;
        } else if (key.contains("JQ")) {
            rtn = " class_describe like '%剧情%' and md5 = 'qnyb_abc_test'";
            return rtn;
        } else if (key.contains("DM")) {
            rtn = " class_describe like '%儿童%'  and md5 = 'qnyb_abc_test' or class_describe like '%动画%' and md5 = 'qnyb_abc_test'";
            return rtn;
        } else if (key.contains("TJ")) {
            rtn = " class_describe like '%经典%' and md5 = 'qnyb_abc_test'";
            return rtn;
        } else if (key.contains("TY")) {
            rtn = " class_describe like '%运动%' and md5 = 'qnyb_abc_test'";
            return rtn;
        }
        return rtn;
    }

    public List<LocalMovieMessage> queryTop(int top, QueryType queryType) {
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        String orderBy = NewDBHelper.DOUBAN_RATING + " desc";
        switch (queryType) {
            case QUERY_TYPE_NAME:
                orderBy = NewDBHelper.PINYIN + " asc";
                break;
            case QUERY_TYPE_SCREEN_TIME:
                orderBy = "screen_time desc";
                break;
            default:
                orderBy = NewDBHelper.DOUBAN_RATING + " desc";
                break;
        }
        Cursor c = db.query(NewDBHelper.TABLE_NAME, null, null, null, null, null, orderBy, String.valueOf(top));
        readCursor2List(persons, c);
        c.close();
        return persons;
    }

    /**
     * query all
     *
     * @return persons
     */
    public List<LocalMovieMessage> queryRecommend() {
        return queryTJLimit(4);
    }

    private List<LocalMovieMessage> queryTJLimit(int limitNum) {
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        String sql = "SELECT * FROM movie_message where path like '%/TJ/%' and poster_path is not null";
        StringBuffer sb = new StringBuffer(sql);
//        String order = " order by douban_rating desc";
        String order = " order by random()";
        String limit = " limit " + limitNum;
        sb.append(order).append(limit);

        Cursor c = db.rawQuery(sb.toString(), null);
        readCursor2List(persons, c);
        c.close();
        return persons;
    }

    /**
     * query all
     *
     * @return persons
     */
    public List<LocalMovieMessage> queryRecommendInDetail() {
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
//        String sql = "SELECT * FROM movie_message where path like '%/TJ/%' and poster_path is not null";
        String sql = "SELECT * FROM movie_message where path like '%/TJ/%'" + " order by random() limit 7 ";
        StringBuffer sb = new StringBuffer(sql);

        Cursor c = db.rawQuery(sb.toString(), null);
        readCursor2List(persons, c);
//        if (persons.size() < 5) {
//            sql = sql + " class_describe like '%经典%' and md5 = 'qnyb_abc_test'";
//        }
        c.close();
        return persons;
    }

    /**
     * query all record contain key, return list
     *
     * @return List<Person>
     */
    public List<LocalMovieMessage> queryKey(String key) {
        key = key.toLowerCase();
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        /*StringBuffer keyBuffer = new StringBuffer();
        keyBuffer.append("'");
        for (int i = 0; i < key.length(); i++) {
            keyBuffer.append("%").append(key.charAt(i)).append("%");
        }
        keyBuffer.append("'");*/
//        Cursor c = db.rawQuery("SELECT * FROM movie_message where pinyin LIKE '%" + key + "%' order by length(pinyin) asc limit 0,20", null);
        String sql = "SELECT * FROM movie_message where pinyin LIKE  " + "'%" + key + "%'" + "  order by length(name) asc limit 99";
        Cursor c = db.rawQuery(sql, null);
        readCursor2List(persons, c);
        c.close();
        return persons;
    }

    /**
     * query all record contain key, return list
     *
     * @return List<Person>
     */
    public List<LocalMovieMessage> querySearchRecommend() {
        return queryTJLimit(22);
    }

    /**
     * 删除
     *
     * @param lmm movie message
     * @return boolean
     */
    public boolean delete(LocalMovieMessage lmm) {
        db.delete(NewDBHelper.TABLE_NAME, "id = ?", new String[]{String.valueOf(lmm.getId())});
//        String sql = "DELETE FROM movie_message where id = " + lmm.getId();
//        db.execSQL(sql);
        return false;
    }

    /**
     * 更新电影分类,豆瓣评分
     *
     * @param lmm movie message
     * @return boolean
     */
    public boolean updateDoubanMsg(LocalMovieMessage lmm) {
        boolean result = false;
        db.beginTransaction();
        try {
            ContentValues cv = constructCv(lmm);
            db.update(NewDBHelper.TABLE_NAME, cv, "id = ? ", new String[]{String.valueOf(lmm.getId())});
            db.setTransactionSuccessful(); // changes get rolled back if this not called
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        } finally {
            db.endTransaction(); // commit or rollback
        }
        return result;
    }

    /**
     * 更新电影分类,豆瓣评分
     *
     * @param lmm movie message
     * @return boolean
     */
    public boolean updateMovieMsg(LocalMovieMessage lmm) {
        boolean result;
        db.beginTransaction();
        ContentValues cv = constructCv(lmm);
//        db.update(NewDBHelper.TABLE_NAME, cv, "id = ? ", new String[]{String.valueOf(lmm.getId())});
        db.updateWithOnConflict(NewDBHelper.TABLE_NAME, cv, "id = ? ", new String[]{String.valueOf(lmm.getId())}, SQLiteDatabase.CONFLICT_REPLACE);
        db.setTransactionSuccessful(); // changes get rolled back if this not called
        result = true;
        db.endTransaction(); // commit or rollback
        return result;
    }

    /**
     * updateMovieCount,现想主要用于已有本地数据,更新网络数据
     *
     * @param lmm movie message
     * @return boolean
     */
    public boolean updateMovieCount(LocalMovieMessage lmm) {
        boolean result = false;
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            cv.put(NewDBHelper.MOVIE_COUNT, lmm.getCount());
            db.update(NewDBHelper.TABLE_NAME, cv, "id = ? ", new String[]{String.valueOf(lmm.getId())});
            db.setTransactionSuccessful(); // changes get rolled back if this not called
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        } finally {
            db.endTransaction(); // commit or rollback
        }
        return result;
    }

    /**
     * updateMovieCount,现想主要用于已有本地数据,更新网络数据
     *
     * @param path  movie path
     * @param count movie click count
     * @return boolean
     */
    public boolean updateMovieCount(String path, int count) {
        LocalMovieMessage localMovieMessage = queryByPath(path);
        if (localMovieMessage != null) {
            localMovieMessage.setCount(count);
            return updateMovieCount(localMovieMessage);
        }
        return false;
    }


    public boolean updatePlayTime(LocalMovieMessage lmm) {
        boolean result = false;
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            cv.put(NewDBHelper.LAST_PLAY_TIME, System.currentTimeMillis());
            db.update(NewDBHelper.TABLE_NAME, cv, "id = ? ", new String[]{String.valueOf(lmm.getId())});
            db.setTransactionSuccessful(); // changes get rolled back if this not called
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        } finally {
            db.endTransaction(); // commit or rollback
        }
        return result;
    }

    public List<LocalMovieMessage> queryLastPlay(int top) {
        ArrayList<LocalMovieMessage> persons = new ArrayList<LocalMovieMessage>();
        Cursor c = db.query(NewDBHelper.TABLE_NAME, null,
                NewDBHelper.LAST_PLAY_TIME + " != ?", new String[]{String.valueOf(0)},
                null, null, NewDBHelper.LAST_PLAY_TIME + " desc", String.valueOf(top));
        readCursor2List(persons, c);
        c.close();
        return persons;
    }

    /**
     * 获取电影时长数据不正常的数据
     *
     * @return 电影时长数据不正常的数据
     * SELECT path md5 FROM movie_message WHERE movie_length like '%000%' or movie_length = '0' or movie_length isnull
     */
    public ArrayList<LocalMovieMessage> checkWithoutDurationMovies() {
        ArrayList<LocalMovieMessage> withoutDurationMoviesList = new ArrayList<>();
        Cursor cursorWithoutDurationMovies = db.query(NewDBHelper.TABLE_NAME, null,
                "movie_length like '%000%' or movie_length = '0' or movie_length isnull",
                null, null, null, null);
        if (cursorWithoutDurationMovies != null && cursorWithoutDurationMovies.getCount() > 0) {
            readCursor2List(withoutDurationMoviesList, cursorWithoutDurationMovies);
        }
        if (cursorWithoutDurationMovies != null) {
            cursorWithoutDurationMovies.close();
        }
        return withoutDurationMoviesList;
    }

    /**
     * 更新电影时长
     */
    public boolean updateMovieDuration(String id, String duration) {
        //UPDATE movie_message SET movie_length = '126' WHERE id = '20529'
        boolean result = true;
        try {
            db.execSQL("UPDATE movie_message SET movie_length = ? WHERE id = ?", new String[]{duration, id});
            LogUtils.i("updateMovieDurationDb", "id:" + id + ",duration:" + duration);
        } catch (Exception e) {
            result = false;
        }
//        db.beginTransaction();
//        boolean result;
//        try {
//            ContentValues contentValues = new ContentValues();
//            contentValues.put(NewDBHelper.MOVIE_LENGTH, duration);
//            db.update(NewDBHelper.TABLE_NAME, contentValues, NewDBHelper.ID + " = ?", new String[]{id});
//            db.setTransactionSuccessful(); // changes get rolled back if this not called
//            result = true;
//        } catch (Exception e) {
//            e.printStackTrace();
//            result = false;
//        } finally {
//            db.endTransaction(); // commit or rollback
//        }
        return result;
    }

    /**
     * 更新封面路径
     *
     * @param path 封面Path
     * @param id   数据库主键
     */
    public void updatePosterPath(String path, String id) {
        String sql = "UPDATE " + NewDBHelper.TABLE_NAME + " SET " + NewDBHelper.POSTER_PATH + " = ? WHERE " + NewDBHelper.ID + " = ?";
        try {
            db.execSQL(sql, new String[]{path, id});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取没有封面的电影
     */
    public ArrayList<LocalMovieMessage> checkWithoutPosterMovies() {
        ArrayList<LocalMovieMessage> withoutPosterMoviesList = new ArrayList<>();
        Cursor cursorWithoutPosterMovies = db.query(NewDBHelper.TABLE_NAME, null,
                NewDBHelper.POSTER_PATH + " is null",
                null, null, null, null);
        if (cursorWithoutPosterMovies != null && cursorWithoutPosterMovies.getCount() > 0) {
            readCursor2List(withoutPosterMoviesList, cursorWithoutPosterMovies);
        }
        if (cursorWithoutPosterMovies != null) {
            cursorWithoutPosterMovies.close();
        }
        return withoutPosterMoviesList;
    }

    /**
     * close database
     */
    public void closeDB() {
        db.close();
        db = null;
        mNewDBManager = null;
    }
}