# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb
import math
from threadpool import ThreadPool, makeRequests
from DBUtils.PooledDB import PooledDB

from django.conf import settings
from django.core.management import BaseCommand


HOST = settings.DATABASES.get('default').get('HOST')
NAME = settings.DATABASES.get('default').get('USER')
PASSWORD = settings.DATABASES.get('default').get('PASSWORD')
DB_NAME = settings.DATABASES.get('default').get('NAME')

pool = PooledDB(MySQLdb, 5, host=HOST, user=NAME, passwd=PASSWORD, db=DB_NAME, port=3306)

task_pool = ThreadPool(num_workers=4)


def update_http(url_http):
    url_http = url_http.strip()

    if url_http.startswith("https://heras.igengmei.com"):
        url_http = url_http.replace("https://heras.igengmei.com", "http://hera.s.igengmei.com")
        return url_http

    if url_http.startswith("http://hera.s.igengmei.com"):
        url_http = url_http.replace("http://hera.s.igengmei.com", "https://heras.igengmei.com")
        return url_http

    if url_http.startswith("http://pic.igengmei.com"):
        url_http = url_http.replace("http://pic.igengmei.com", "https://pic.igengmei.com")
        return url_http

    return False


def batch_update(data_list):
    db = pool.connection()
    cursor_batch = db.cursor()
    for row in data_list:
        id = row[0]
        content = update_http(row[1])
        if not content:
            continue
        update_sql = "update {table_n} set {column_n} = '{content}' where id = {id_n};".format(table_n=Command.table_n,
                                                                                             column_n=Command.column_n,
                                                                                             content=content,
                                                                                             id_n=id)
        try:
            cursor_batch.execute(update_sql)
            print("id==", id)
            db.commit()
        except:
            # 发生错误时回滚
            db.rollback()
    cursor_batch.close()
    db.close()


class Command(BaseCommand):
    table_n, column_n = '', ''

    def add_arguments(self, parser):
        parser.add_argument('table', nargs='+', type=str)
        parser.add_argument('column', nargs='+', type=str)
        """python manage.py  img_transfer_https 'user' 'name' 只能更改一列  use_index 是否使用偏移量
            如果不用id那么就用index值 默认使用id
          表名字就是 user  列名就是name
        """

    def handle(self, *args, **options):
        table_name = options.get('table')
        column = options.get('column')

        if not table_name:
            print("please input table_name")
            return

        if not column:
            print("please input column_name")
            return

        interval = 400

        db = pool.connection()
        # 使用cursor()方法获取操作游标
        cursor = db.cursor()

        index, cloumn_str, table_name = 0, 'id', table_name[0]
        cloumn_str = 'id,' + str(column[0])
        Command.table_n, Command.column_n = table_name, column[0]

        sql = "select {column_n} from {table_n} where id >{start} ORDER BY id limit {interval_n} ;"

        offset_index = 0
        while(True):
            try:
                query_sql = sql.format(column_n=cloumn_str, table_n=table_name, start=index, interval_n=interval)

                # 执行SQL语句
                cursor.execute(query_sql)
                # 获取所有记录列表
                results = cursor.fetchall()
                if not results:
                    break

                index = results[-1][0]

                offset_index += interval

                per_num, args_list = 100, []
                cnt = int(math.ceil(interval / per_num))

                for i in range(cnt):
                    data_arg = list(results[i*per_num:(i+1)*per_num])
                    args_list.append(data_arg)

                temp = makeRequests(batch_update, args_list=args_list)

                [task_pool.putRequest(req) for req in temp]
            except:
                print("Error: unable to fecth data")
        cursor.close()
        db.close()

        task_pool.wait()
        #task_pool.dismissedWorkers(4)
        print("Done")
