# coding=utf-8
# create by oldman at 2018/8/7
import tablib
from django.core.management import BaseCommand
from django.db import transaction
from openpyxl import load_workbook

from api.tasks.export_maidan_order_task import get_mail
from hippo.models import Doctor
from hippo.models import Merchant
from maidan.models import MaidanOrderStatementRelationship
from pay.models import OrderStatementRelationship
from pay.models import StatementAll
from pay.tool import DatetimeTool


def read_excel():
    """
    读取excel获取要处理的数据
    :return:
    """
    wb = load_workbook(filename=u'merchant.xlsx')
    sheetnames = wb.get_sheet_names()
    ws = wb.get_sheet_by_name(sheetnames[0])
    results = []
    for rx in range(2, ws.max_row + 1):
        try:
            doctor_id = ws.cell(row=rx, column=1).value
            merchant_id = ws.cell(row=rx, column=8).value
            results.append(
                {
                    'merchant_id': merchant_id,
                    'doctor_id': doctor_id
                }
            )

        except Exception as e:
            continue
    print u'excel读取完毕'
    return results


class Command(BaseCommand):
    """
    python manage.py update_2018_08_07_revert_statements
    重新跑七月份的结算单
    """

    def handle(self, *args, **options):
        dt_success = tablib.Dataset()
        dt_erro = tablib.Dataset()
        dt_success.headers = (u'statement_all_id',u'statement_all_id')
        dt_erro.headers = (u'statement_all_id', u'excption')
        # 删除7月份的对账单
        last_month_dt = DatetimeTool().get_first_day_month(d_months=-1)
        statement_date = last_month_dt.strftime("%Y%m")
        statementalls = StatementAll.objects.filter(statement_date=statement_date)
        for statementall in statementalls:
            statemenall_id = statementall.id
            try:
                with transaction.atomic():
                    # 处理总对账单
                    service_statement = statementall.service_statement
                    maidan_statement = statementall.maidan_statement
                    statementall.delete()
                    # 处理买单对账单
                    MaidanOrderStatementRelationship.objects.filter(statement=maidan_statement).delete()
                    maidan_statement.delete()
                    # 处理美购对账单
                    OrderStatementRelationship.objects.filter(statement=service_statement).delete()
                    service_statement.delete()
                    dt_success.append((
                        statemenall_id,
                        statemenall_id
                    ))
            except Exception as e:
                print e.message
                print statemenall_id
                dt_erro.append(
                    statemenall_id,
                    e
                )
                continue

        to_list = 'lipeng@igengmei.com'
        dt_success.title = u'对账单删除成功'
        dt_erro.title = u'对账单删除失败'
        body = u'对账单删除'
        book = tablib.Databook((dt_success, dt_erro))
        get_mail(u'对账单删除', body, to_list, book).send()
        print('Done')






