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

import xlrd
import math
import datetime
from django.conf import settings
from django.core.management import BaseCommand
from gm_types.gaia import DOCTOR_SECKILL_APPLY_STATUS
from api.models import User, DoctorSeckillApply, DoctorSeckillApplyRecord


def get_user_id():
    return 20296583 if settings.DEBUG else 31468349


def get_file_name():
    return "2.xlsx"


def _upload_button_apply_audit(person, apply_id, is_pass, reason):
    apply = DoctorSeckillApply.objects.get(id=apply_id)
    if apply.status == DOCTOR_SECKILL_APPLY_STATUS.PASS or apply.status == DOCTOR_SECKILL_APPLY_STATUS.REJECT:
        return {
            'code': 0,
            'apply_id': apply.id
        }
    if is_pass:
        price_info = apply.service_item.get_default_price_info()
        seckill_price = apply.seckill_price
        self_support_discount_rate = price_info['self_support_discount'] * 1.00 / price_info['gengmei_price']
        if seckill_price > 500:
            pre_payment_rate = price_info['pre_payment_price'] * 1.00 / price_info['gengmei_price']
            commission_rate = price_info['discount'] * 1.00 / price_info['gengmei_price']
            pre_payment_price = math.ceil(apply.seckill_price * pre_payment_rate)
            commission = math.ceil(apply.seckill_price * commission_rate)
        else:
            from doctor.tool.service_tool import count_pre_payment
            result = count_pre_payment(seckill_price)
            pre_payment_price = result['pre_payment_price_int']
            commission = result['discount']
        apply.status = DOCTOR_SECKILL_APPLY_STATUS.PASS
        apply.available_num = apply.stock
        # http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=28907071
        apply.left_stock = apply.stock
        apply.pre_payment_price = pre_payment_price
        apply.commission = commission
        apply.self_support_discount = math.ceil(apply.seckill_price * self_support_discount_rate)
        apply.pass_time = datetime.datetime.now()
    else:
        apply.status = DOCTOR_SECKILL_APPLY_STATUS.REJECT
        apply.available_num = None
        apply.left_stock = 0
        apply.pre_payment_price = None
        apply.commission = None
        apply.self_support_discount = None
        apply.pass_time = None
    apply.save()

    DoctorSeckillApplyRecord.objects.update_or_create(
        doctorseckillapply_id=apply.id, defaults={
            "is_pass": is_pass,
            'seckill_price': apply.seckill_price,
            'comment': reason or '',
            'person': person
        })
    return {
        'code': 1,
        'apply_id': apply.id
    }


class Command(BaseCommand):
    def handle(self, *args, **options):
        USER_ID = get_user_id()
        APPLY_FILES = get_file_name()
        user = User.objects.get(id=USER_ID)

        data = xlrd.open_workbook(APPLY_FILES.decode('utf-8'))
        for table in data.sheets()[:3]:
            table_name = table.name
            print("开始处理: {table_name}, 共计: {total}".format(
                table_name=table_name, total=table.nrows - 1))
            if table_name == "批量通过":
                for row in range(1, table.nrows):
                    doctorseckill_apply_id = table.row_values(row)[0]
                    d = DoctorSeckillApply.objects.get(id=doctorseckill_apply_id)
                    if d.status == DOCTOR_SECKILL_APPLY_STATUS.PASS:  # 审核通过
                        continue
                    elif d.status == DOCTOR_SECKILL_APPLY_STATUS.REJECT:  # 拒绝
                        d.status = DOCTOR_SECKILL_APPLY_STATUS.DEFAULT
                        d.save()
                    print("start to handle: ", doctorseckill_apply_id)
                    result = _upload_button_apply_audit(
                        person=user.person,
                        is_pass=True, reason='',
                        apply_id=doctorseckill_apply_id,
                    )

                    if result['code'] == 1:
                        print("doctorseckill_apply_id: {doctorseckill_apply_id}---success!".format(
                            doctorseckill_apply_id=doctorseckill_apply_id))
                    else:
                        print("doctorseckill_apply_id: {doctorseckill_apply_id}---fail!".format(
                            doctorseckill_apply_id=doctorseckill_apply_id))
            elif table_name == "批量驳回":
                for row in range(1, table.nrows):
                    doctorseckill_apply_id = table.row_values(row)[0]
                    d = DoctorSeckillApply.objects.get(id=doctorseckill_apply_id)
                    if d.status == DOCTOR_SECKILL_APPLY_STATUS.REJECT:
                        continue

                    elif d.status == DOCTOR_SECKILL_APPLY_STATUS.PASS:
                        d.status = DOCTOR_SECKILL_APPLY_STATUS.DEFAULT
                        d.save()

                    result = _upload_button_apply_audit(
                        person=user.person,
                        is_pass=False, reason='报价项目与规则不符合',
                        apply_id=doctorseckill_apply_id,
                    )

                    if result['code'] == 1:
                        print("doctorseckill_apply_id: {doctorseckill_apply_id}---success!".format(
                            doctorseckill_apply_id=doctorseckill_apply_id))
                    else:
                        print("doctorseckill_apply_id: {doctorseckill_apply_id}---fail!".format(
                            doctorseckill_apply_id=doctorseckill_apply_id))

        print("done!")