#coding: utf8
import sys
import xlrd

from django.core.management import BaseCommand
from django.db.models import Q
from gm_types.gaia import TRANSFER_SOURCE, BDTRANSFER_OBJECT_STATE
from api.models import BDTransfer, User

reload(sys)
sys.setdefaultencoding('utf-8')


class Command(BaseCommand):

    def handle(self, *args, **options):
        file="export_history_user.xlsx"
        data = xlrd.open_workbook(file.decode('utf-8'))
        sheet = data.sheets()[0]
        exist_list=[]
        for index in range(2, sheet.nrows):
            row = sheet.row_values(index)
            if row:
                creator_name, current_follow_up_consultant, wechat = row[0], row[1], row[2]
                user_phone, wechat_nickname = str(row[3]).split('.')[0], row[4]
                try:
                    wechat = str(int(wechat))
                except ValueError:
                    wechat = wechat
                u = User.objects.filter(username=creator_name).first()
                if not u:
                    continue
                creator = u.id

                f = User.objects.filter(username=current_follow_up_consultant).first()
                if not f:
                    continue
                current_follow_up_consultant_id = f.id
                q = Q()
                if wechat:
                   q |=  Q(wechat=wechat)

                if user_phone:
                    q |= Q(user_phone=user_phone)

                objs=BDTransfer.objects.filter(q)
                if objs.exists():
                    for obj in objs:
                        exist_list.append(obj.id)
                    continue
                else:
                    try:
                        BDTransfer.objects.get_or_create(
                            creator=str(creator), current_follow_up_consultant_id=current_follow_up_consultant_id,
                            wechat=wechat, user_phone=user_phone, wechat_nickname=wechat_nickname, is_assign=1,
                            object_state=BDTRANSFER_OBJECT_STATE.HAS_PASSED_INFOMATION,
                            source=TRANSFER_SOURCE.NEITOU_GONGZHONG
                        )
                        print('导入:wechat:{0},user_phone:{1}成功!').format(wechat,user_phone)

                    except Exception as e:
                        print('wrong action:wechat:{0},user_phone:{1}').format(wechat,user_phone)
                        print(str(e))

        print exist_list
