#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__: vv
# Date: 2019/8/29

import xlrd
from api.models import Person
from django.core.management import BaseCommand
from gm_types.gaia import DOCTOR_SECKILL_APPLY_STATUS
from api.models import DoctorSeckillApply, DoctorSeckillApplyRecord

filename = ''
user_id = 0


def update_pre_payment_price_and_discount(data):
    """
    更新抽成和预付款
    :param user_id:
    :param data:
    :return:
    """
    apply_id = data['apply_id']
    serviceitem_id = data['serviceitem_id']
    commission_rate = data['commission_rate']
    pre_payment_price = data['pre_payment_price']

    apply = DoctorSeckillApply.objects.get(id=apply_id)
    seckill_price = apply.seckill_price

    def reason_str(str):
        print(str + "apply_id: {}, serviceitem_id: {}, "
              "seckill_price: {}".format(apply_id, serviceitem_id, seckill_price))

    if apply.status != DOCTOR_SECKILL_APPLY_STATUS.PASS:
        reason_str("审核未通过, 不能修改...")
        return False

    if seckill_price > 500:
        reason_str("活动价超过500, 不能修改...")
        return False

    if pre_payment_price > seckill_price:
        reason_str("预付款不能超过活动价...")
        return False

    if commission_rate > 100:
        reason_str("抽成比例不能超过100...")
        return False

    apply.pre_payment_price = pre_payment_price # 预付款价格
    apply.commission = commission_rate  # 抽成50%
    apply.save()

    try:
        person = Person.objects.get(user_id=user_id)
    except Person.DoesNotExist:
        person = None

    record_date = {
        'doctorseckillapply_id': apply_id,
        'is_pass': True,
        'seckill_price': apply.seckill_price,
        'comment': '',
        'person': person
    }

    DoctorSeckillApplyRecord.objects.create(**record_date)

    return True


class Command(BaseCommand):

    def handle(self, *args, **options):
        data = xlrd.open_workbook(filename)
        table = data.sheets()[0]

        for row in range(1, table.nrows):
            row_data = table.row_values(row)
            try:
                apply_id = int(row_data[0])
                serviceitem_id = int(row_data[1])
                pre_payment_price = int(row_data[2])
                discount = int(row_data[3])
            except ValueError:
                apply_id = -1
                serviceitem_id = -1
                pre_payment_price = 0
                discount = 0

            data = {
                "apply_id": apply_id,
                "serviceitem_id": serviceitem_id,
                "pre_payment_price": pre_payment_price,
                "discount": discount
            }
            update_pre_payment_price_and_discount(data=data)
