# coding=utf-8
import xlrd
import datetime

from django.core.management import BaseCommand

from lasker.models import AwardResult
from gm_types.gaia import SERVICE_FLAG
from api.models import BDTransferSingleRecord,BDTransferCommunicationRecord,BDTransferAssist,BDTransferOperationRecord,BDTransfer,Doctor,BuDan,Tag,\
    GaiaRPCFaultException,User,transaction,Merchant
from gm_types.error import ERROR
from gm_types.gaia import BDTRANSFER_OBJECT_STATE, SINGLE_TYPE, TRANSFER_SOURCE, USER_GENDER, REPEAT_TYPE, AssistStatus, BUDAN_STATUS, VISIT_METHOD,BD_SERVICE_TYPE,USERACTIVE_STATUS,TEAM_TYPE,BD_SERVICE_TYPE
from api.tool.user_tool import get_user_from_context, get_user_by_id
from utils.execel import ExcelReader

class Command(BaseCommand):
    """ Import famous doctor award list from excel to database """

    def handle(self, *args, **options):
        path = 'bdtransfer_single_record_data_2.xlsx'
        e_reader = ExcelReader(path)
        e_reader.sheet_select_by_name(u"Sheet1")
        row_num=e_reader.row_number
        print(row_num)
        # temp=e_reader.read_column(2)
        # print(set(temp),len(set(temp)))
        # temp=e_reader.read_column(4)
        # print(set(temp),len(set(temp)))
        # temp=e_reader.read_column(5)
        # print(set(temp),len(set(temp)))
        # temp=e_reader.read_column(7)
        # print(set(temp),len(set(temp)))
        # return
        res=[]
        for line in range(2,row_num):
            try:
                row=e_reader.read_row(line)
                if not row[3]:
                    continue
                bdtransfer_id = row[3]
                print(row[4],row[6])
                project_ids =[int(e) for e in str(row[6]).split("；")]
                user_name=row[1]
                merchant=Merchant.objects.get(id=row[4])
                doctor_id =merchant.doctor_id
                print(bdtransfer_id,doctor_id,project_ids,user_name,row[4])
                res=bdtransfer_single_record_handler(
                    bdtransfer_id=bdtransfer_id,
                    record_id=None,
                    doctor_id=doctor_id,
                    project_ids=project_ids,
                    appointment_time=None,
                    consultation_time=None,
                    operation_time=None,
                    user_name=user_name
                )
                print(res)
            except:
                print("error")

    
def bdtransfer_single_record_handler(bdtransfer_id=None, doctor_id=None, project_ids=None,
                                     record_id=None, budan_id=None, consultation_time=None, appointment_time=None, is_terminate=False, operation_time=None,user_name=None):
    """商务转诊派单记录Handler

    :param bdtransfer_id: 商务转诊ID
    :param doctor_id: 医生ID
    :param project_ids: 项目对应的二级标签TAGS
    :param record_id: 派单记录ID
    :param budan_id: 补单ID
    :param is_terminate: 是否终止派单记录
    :return:
    """

    def _adjustment_assistor(bdtransfer, operate_user, is_order=False):
        # 调整一下顾问和协助顾问关系
        follower = bdtransfer.current_follow_up_consultant
        if operate_user != follower:
            date_30days_before = datetime.now() - timedelta(days=30)
            has_communicate = BDTransferCommunicationRecord.objects.filter(bdtransfer=bdtransfer, user=follower,
                                                                           communication_time__range=(
                                                                               date_30days_before,
                                                                               datetime.now())).exists()
            has_single = BDTransferSingleRecord.objects.filter(dbtransfer=bdtransfer, user=follower).exists()
            has_budan = BDTransferSingleRecord.objects.filter(dbtransfer=bdtransfer, budan__isnull=False).exists()
            if (not has_single) or (not has_communicate and not is_order) or (not has_budan and is_order):
                res = BDTransferAssist.objects.filter(bdtransfer=bdtransfer, assistor=operate_user).update(assistor=follower)
                if not res:
                    BDTransferAssist.objects.create(bdtransfer=bdtransfer, assistor=follower, status=AssistStatus.PASSED)
                bdtransfer.current_follow_up_consultant = operate_user
                bdtransfer.assigner = operate_user.id
                bdtransfer.save()
                BDTransferOperationRecord.objects.create(
                    bdtransfer=bdtransfer,
                    operate_user=operate_user,
                    action=OPERATION_ACTION.REASSIGN,
                    content='顾问{}调整成为跟进顾问，顾问{}调整成为协助顾问'.format(operate_user.username, follower.username)
                )

        if is_order:
            ordered_user_ids = BDTransferSingleRecord.objects.filter(dbtransfer=bdtransfer).values_list("user").all()
            has_budan = BDTransferSingleRecord.objects.filter(dbtransfer=bdtransfer, budan__isnull=False).exists()
            if not has_budan:
                ordered_user_ids = [i for i, in ordered_user_ids]
                assists = BDTransferAssist.objects.filter(bdtransfer=bdtransfer, is_delete=False).exclude(assistor_id__in=ordered_user_ids).all()
                for assist in assists:
                    BDTransferOperationRecord.objects.create(
                        bdtransfer=bdtransfer,
                        operate_user=operate_user,
                        action=OPERATION_ACTION.DEL_ASSISTOR,
                        content='自动删除协助顾问{}'.format(assist.assistor.username)
                    )
                BDTransferAssist.objects.filter(bdtransfer=bdtransfer, is_delete=False).exclude(assistor_id__in=ordered_user_ids).update(is_delete=True)



    operate_user = User.objects.get(username=user_name)
    if consultation_time is not None:
        consultation_time = datetime.strptime(consultation_time, '%Y-%m-%d %H:%M:%S')
    if appointment_time is not None:
        appointment_time = datetime.strptime(appointment_time, '%Y-%m-%d %H:%M:%S')
    if operation_time is not None:
        operation_time = datetime.strptime(operation_time, '%Y-%m-%d %H:%M:%S')
    # 修改single status 状态
    status = SINGLE_TYPE.NO_ORDER_FORM
    if appointment_time:
        status = SINGLE_TYPE.HAS_APPOINTMENT
    if consultation_time:
        status = SINGLE_TYPE.HAS_CONSULTATION

    if bdtransfer_id:
        bdtransfer = BDTransfer.get_by_id(bdtransfer_id)
    if record_id:
        bdtransfer_single_record = BDTransferSingleRecord.get_by_id(id=record_id)
    try:
        if doctor_id:
            doctor = Doctor.objects.get(id=doctor_id)
        if budan_id:
            budan = BuDan.objects.get(id=budan_id)
    except Doctor.DoesNotExist:
        gen(CODES.DOCTOR_NOT_FOUND)
    except BuDan.DoesNotExist:
        gen(CODES.BUDAN_NOT_FOUND)
    if project_ids:
        tag_objs = Tag.objects.filter(id__in=project_ids).all()
        assert len(tag_objs) == len(project_ids)
    with transaction.atomic():
        if record_id and doctor_id and project_ids:  # 修改
            bdtransfer_single_record.doctor = doctor
            bdtransfer_single_record.project.clear()
            bdtransfer_single_record.appointment_time = appointment_time
            bdtransfer_single_record.consultation_time = consultation_time
            bdtransfer_single_record.operation_time = operation_time
            bdtransfer_single_record.status = status
            bdtransfer_single_record.add(*tag_objs)
            bdtransfer_single_record.save()
        elif bdtransfer_id and doctor_id and project_ids:  # 新增
            bdtransfer_single_record = bdtransfer.single_records.create(
                user=operate_user, doctor=doctor, consultation_time=consultation_time,
                appointment_time=appointment_time, status=status, operation_time=operation_time,
                is_new=False
            )
            bdtransfer_single_record.project.add(*tag_objs)
            _adjustment_assistor(bdtransfer, operate_user)

        elif record_id and budan_id:  # 关联补单信息
            _adjustment_assistor(bdtransfer_single_record.dbtransfer, operate_user, is_order=True)
            bdtransfer_single_record.budan = budan
            bdtransfer_single_record.status = SINGLE_TYPE.HAS_ORDER_FORM
            bdtransfer_single_record.confirm_user = operate_user
            bdtransfer_single_record.save()
        elif record_id and not is_terminate:  # 删除
            bdtransfer_single_record.delete()
        elif record_id and is_terminate:  # 终止派单, 但不删除
            bdtransfer_single_record.status = SINGLE_TYPE.HAS_TERMINATE
            bdtransfer_single_record.save()
        else:
            raise GaiaRPCFaultException(ERROR.UNKNOWN_ERROR, u'无效的操作', data=None)
