#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__: vv
# Date: 2019/9/29
import xlrd
import openpyxl
from django.core.management import BaseCommand
from api.models import DoctorSeckillApply, Service, ServiceItem

export_file_name = "doctorapply.xlsx"
input_file_name = "input_apply_data.xlsx"


class Command(BaseCommand):
    def handle(self, *args, **options):
        excel_obj = openpyxl.Workbook()
        _sheet = excel_obj.active
        data = xlrd.open_workbook(input_file_name.decode('utf-8'))
        sheet = data.sheets()[0]
        all_data_infos = []
        for index in range(1, sheet.nrows):
            row = sheet.row_values(index)
            apply_id = None
            try:
                apply_id = int(row[0])
            except:
                print("apply_id does not exist", apply_id)
                continue
            d = DoctorSeckillApply.objects.get(id=apply_id)
            serviceitem_datas = Service.get_current_price_info_by_service_item_ids([d.service_item_id])
            service_item_data = serviceitem_datas.get(d.service_item_id)
            if not service_item_data:
                print(d.service_item_id, '不存在价格信息--------------')
                continue

            if service_item_data.get('pre_payment_price') == 199 and service_item_data.get('gengmei_price') == 199:
                continue

            # 专场id
            activity_id = service_item_data['selling_rule'].get('activity_id')

            # 美购id
            serviceitem = ServiceItem.objects.get(id=d.service_item_id)
            service_id = serviceitem.service_id

            # 美购名称
            name = serviceitem.service.name

            # 机构名称
            hospital_name = serviceitem.service.hospital.name

            # 商务
            merchant = serviceitem.service.doctor.business_partener.last_name

            # 活动价格
            active_price = service_item_data.get('gengmei_price')

            # 预付款
            pre_payment_price = service_item_data.get('pre_payment_price')

            # 抽成
            discount = service_item_data.get('discount')

            all_data_infos.append(
                [apply_id, activity_id, service_id, d.service_item_id, name, hospital_name,
                 merchant, active_price, pre_payment_price, discount]
            )

        count = 0
        for line_data in all_data_infos:
            if count == 0:
                _sheet.append(['申请id', '专场ID','美购id','skuid','美购名称', '机构名称','商务','活动价格','预付款','抽成金额'])
            else:
                _sheet.append(line_data)
            count += 1
        excel_obj.save(export_file_name)
