# coding=utf-8
import os
import random
import traceback

from datetime import datetime
from django.core.management import BaseCommand
from openpyxl import Workbook, load_workbook
from openpyxl.writer.excel import ExcelWriter

from api.models import Tag, Service
from api.models import Doctor, ServiceAttr, ServiceAttrOption, ServiceItem, ServiceTag


def image_list():
    print('开始加载source数据!')
    wb = load_workbook(filename='source.xlsx')
    sheetnames = wb.get_sheet_names()
    sheet_image = wb.get_sheet_by_name(sheetnames[0])
    sheet_tag = wb.get_sheet_by_name(sheetnames[1])
    list_images = []
    dict_tags = {}
    for rx in range(2, sheet_image.max_row + 1):
        list_images.append(sheet_image.cell(row=rx, column=1).value)
    for rx in range(2, sheet_tag.max_row + 1):
        tag_name = sheet_tag.cell(row=rx, column=1).value
        tags = Tag.objects.filter(name=tag_name)
        data = {}
        if tags.count() > 0:
            tag_id = tags[0].id
            short_description_image = sheet_tag.cell(row=rx, column=2).value
            if short_description_image == 0:
                short_description_image = u''

            data['short_description_image'] = short_description_image
            shoushu = sheet_tag.cell(row=rx, column=3)
            is_shoushu = True if shoushu == u'Y' else False
            data['is_shoushu'] = is_shoushu
            data['buy_limit'] = sheet_tag.cell(row=rx, column=4).value
            dict_tags[str(tag_id)] = data
    print('source数据加载完毕!!!!!!')
    print('======================')

    return list_images, dict_tags


IMAGE_LIST, TAG_LIST = image_list()


class Command(BaseCommand):
    """
    导入美购数据
    需要在项目的根目录下添加source.xlsx
    python manage.py import_servicereserve_data 'dir_name'
    """

    def add_arguments(self, parser):
        """
        文件所在目录
        """
        parser.add_argument('dir_name', type=str)

    def handle(self, *args, **options):
        if options['dir_name'] is None:
            print 'dir_name is None'
            return
        dir_name = options['dir_name']
        list_file = os.listdir(dir_name)
        for _file in list_file:
            if _file.endswith('.xlsx'):
                #print (u'执行第{0}'.format(_file))
                print(_file)
                wb_result = Workbook()  # 新建一个工作薄
                ew_result = ExcelWriter(workbook=wb_result)  # 新建一个ExcelWriter,用来写wb_result
                dest_filename = _file[:-5] + '_result.xlsx'  # wb_result的名字
                if os.path.exists(os.path.join(dir_name, dest_filename)):
                    continue
                ws_result = wb_result.worksheets[0]  # 处理结果
                wb = load_workbook(filename=os.path.join(dir_name, _file))
                ws = wb.get_sheet_by_name(wb.get_sheet_names()[0])
                list_service = service_sheet(ws)
                tag_name_last = None
                user_name_last = None
                service_id_last = None
                for item in range(0, len(list_service)):

                    item_data = list_service[item]

                    tags = Tag.objects.filter(name=item_data['tag_name'])
                    ws_result.cell(row=item + 1, column=1).value = item_data['tag_name']
                    ws_result.cell(row=item + 1, column=2).value = item_data['doctor_user']
                    try:
                        if tags.count() == 0:
                            ws_result.cell(row=item + 1, column=3).value = u'该tag不存在!'
                            continue
                        tag = tags[0]
                        doctors = Doctor.objects.filter(user__username=item_data['doctor_user'])
                        if doctors.count() == 0:
                            ws_result.cell(row=item + 1, column=4).value = u'该医生不存在!'
                            continue
                        doctor = doctors[0]
                        if str(tag.id) not in TAG_LIST:
                            ws_result.cell(row=item + 1, column=5).value = u'该tag的相关资源不存在!' + tag.name
                            continue
                        if tag_name_last != item_data['tag_name'] or user_name_last != item_data['doctor_user']:
                            service_data = make_service_data(doctor, tag)

                            if service_data['service_image'] is None:
                                ws_result.cell(row=item + 1, column=5).value = u'美购图片不存在! ' + tag.name
                                continue
                            print u'开始执行{0}'.format(item_data['tag_name'])
                            service = Service(
                                doctor_id=doctor.id,
                                name=service_data['name'],
                                short_description=service_data['short_description'],
                                is_multiattribute=False,
                                image_header=service_data['service_image'],
                                channel='1',
                                payment_type='1',
                                service_flag=1,
                                ordering=100,
                                exchange_points_ceiling=0,
                                single_user_buy_limit=service_data['single_user_buy_limit'],
                                points_deduction_percent=10,
                                valid_duration=180,
                                total_num=10000,
                                sell_num_limit=10000,
                                fake_sold_num=0,
                                start_time=datetime.now(),
                                is_operation=service_data['is_operation'],
                                is_vouchsafe=False,
                                is_online=True,
                                share_get_cashback=True,
                                refund_anytime=True,
                                is_stage=False,
                                compensation_in_advance=True,
                                pre_payment_price=int(item_data['gengmei_price']) * 0.2,
                                total_price=int(item_data['gengmei_price']) * 0.2,
                                original_price=item_data['original_price'],
                                gengmei_price=item_data['gengmei_price'],
                                discount=int(item_data['gengmei_price']) * 0.1,
                                cash_back_rate=5,
                                is_self_support=False,
                                self_support_discount=0,
                                is_sink=False,
                                ceiling_price=item_data['gengmei_price'],
                                detail_description=service_data['detail_description'],
                                special_remind=service_data['special_remind'],
                                reservation=1,
                                notes=u'6月1号美购批量导入'
                            )
                            service.save()
                            service_tag = ServiceTag(
                                service_id=service.id,
                                tag_id=tag.id
                            )
                            service_tag.save()

                            tag_name_last = item_data['tag_name']
                            user_name_last = item_data['doctor_user']
                            service_id_last = service.id

                            ws_result.cell(row=item + 1, column=5).value = u'创建美购成功! ' + str(service.id)
                            serviceattr = ServiceAttr(
                                service_id=service.id,
                                name=u'维度'
                            )
                            serviceattr.save()
                            ws_result.cell(row=item + 1, column=7).value = u'添加多属性! ' + str(serviceattr.id)

                        else:
                            service = Service.objects.filter(id=service_id_last)[0]
                            service.is_multiattribute = True
                            service.save()
                            ws_result.cell(row=item + 1, column=6).value = u'美购已存在!' + str(service.id)
                            serviceattr = ServiceAttr.objects.filter(service_id=service.id)[0]

                        serviceattroptions = ServiceAttrOption(
                            service_attr_id=serviceattr.id,
                            name=item_data['multiattr_name']
                        )
                        serviceattroptions.save()
                        ws_result.cell(row=item + 1, column=8).value = u'添加多属性选项! ' + str(serviceattroptions.id)
                        serviceitem = ServiceItem(
                            key=serviceattroptions.id,
                            service_id=service.id,
                            original_price=item_data['original_price'],
                            gengmei_price=item_data['gengmei_price'],
                            pre_payment_price=int(item_data['gengmei_price']) * 0.2,
                            discount=int(item_data['gengmei_price']) * 0.1,
                            self_support_discount=0,
                        )
                        serviceitem.save()
                        ws_result.cell(row=item + 1, column=9).value = u'添加多属性选项的价格设置成功! ' + str(serviceitem.id)
                        print(u'{0}执行完毕!'.format(item_data['tag_name']))
                        print '======================='
                    except IndexError:
                        ws_result.cell(row=item + 1, column=10).value = u'添加失败! ' + u"**一句话描述不存在!"
                        continue
                    except Exception as e:
                        ws_result.cell(row=item + 1, column=10).value = u'添加失败! ' + e.message
                        traceback.print_exc()
                        print(u'{0}执行失败!!!!!!!!!!!!!!!!'.format(item_data['tag_name']))
                        print '*************************************'
                        continue

                ew_result.save(filename=os.path.join(dir_name, dest_filename))
        print('执行完毕!')


def service_sheet(ws):
    """
    处理service的excel数据
    """
    list_service = []
    for rx in range(2, ws.max_row + 1):
        dict_service = {}
        dict_service['tag_name'] = ws.cell(row=rx, column=1).value
        dict_service['multiattr_name'] = ws.cell(row=rx, column=2).value
        dict_service['original_price'] = ws.cell(row=rx, column=3).value  # 市场价
        dict_service['gengmei_price'] = ws.cell(row=rx, column=4).value
        dict_service['doctor_user'] = ws.cell(row=rx, column=5).value
        list_service.append(dict_service)
    return list_service


def make_service_data(doctor, tag):
    """
    封装美购数据
    """
    Services = ServiceTag.objects.filter(tag__id=tag.id).values('service__id')
    serviceids_list = []
    for service in Services:
        serviceids_list.append(service.get('service__id', None))

    def short_desc_format(sdesc):
        rep_list = [u'「特惠」', u'「优选」', u'「千元推荐」']
        for i in rep_list:
            sdesc = sdesc.replace(i, '')
        return sdesc

    short_descriptions = Service.objects.filter(id__in=serviceids_list).values('short_description')
    short_description_list = []
    for item in short_descriptions:
        if item.get('short_description', None) is not None:
            short_description_list.append(short_desc_format(item.get('short_description')))
    print short_descriptions
    service_data = {}
    service_data['name'] = u'【' + doctor.hospital.city.name + u'@' + doctor.name + u'】' + tag.name
    if len(short_description_list) > 0:
        random_short_description = random.randint(0, len(short_description_list) - 1)
        service_data['short_description'] = short_description_list[random_short_description]
        print service_data['short_description']
    else:
        raise IndexError

    rand_image = random.randint(0, len(IMAGE_LIST) - 1)
    service_data['service_image'] = IMAGE_LIST[rand_image]
    if TAG_LIST.get(str(tag.id), None) is not None:
        service_data['single_user_buy_limit'] = TAG_LIST.get(str(tag.id)).get('buy_limit')
        service_data['is_operation'] = TAG_LIST.get(str(tag.id)).get('is_shoushu')
    else:
        service_data['single_user_buy_limit'] = 2
        service_data['is_operation'] = False
    service_data['detail_description'] = u"""
  {0}
 【美购有效期】
自购买之日起6个月。希望您尽快去手术，以避免您忘记最终造成不必要的损失。
![]({1})
【消费流程】
下订单并支付预约金—— 拨打医生400电话预约面诊（提前一天）——手术前，将订单密码交给医生，并支付余下手术费用。
【如何预约】
点击医生头像进入其个人主页，拨打免费400电话联系医生进行面诊。
【如何退款】
点击App首页右下角的“我”，找到“我的订单”，在“未消费”栏里找到该订单，点击取消。退款将在7-15个工作日内到达当初付款的账户。
【如何返现】
步骤一.手术后，在APP内开帖分享治疗过程。
1）需分享术前清晰照2张
2）更新术后当天、次日、一周、两周……恢复后的文字描述和照片，不少于（返现金额/50 +1）次日志分享，每次清晰照片不少于2张，文字描述不少于20字。
步骤二.发帖满3个月后在「我---我的订单---已消费」里找到此订单，进入订单页，申请返现；所长会审核日记是否合格，若合格所长会将（更美价*5%）元现金返还至用户支付账户。
本活动的最终解释权归更美及项目医院所有。
     """.format(service_data['short_description'],
                TAG_LIST[str(tag.id)]['short_description_image'])  # TAG_LIST[str(tag.id)]['short_description_image']
    service_data['special_remind'] = u"""
【消费须知】
1.下单后，请先通过App内的400 电话预约医生/医院（电话方式见上文）
2.请在确定手术后，才将验证密码交给医生/医院。验证密码交给医生/医院后，视为已经手术，您将无法退款。
3.下单后，您到医院还需缴纳（更美价-预约金）元。请您下单时备注购买的具体项目内容。此外，医院可能还有挂号费等小额收费。
4.若您还有其他问题，请在工作日的08:00-22:00之间，拨打更美客服电话：4008-010-231转6666。
    """
    return service_data
