# coding=utf-8
import tablib
from django.core.management import BaseCommand
from django.db.models import Q
from gm_types.gaia import YINUO_TYPE
from openpyxl import load_workbook

from api.models import Service


class Command(BaseCommand):
    """
    设置众安保险默认的美购
    python manage.py set_zhongan_service
    /data/insurance/zhongan_original_data.xlsx
    生成 /data/insurance/zhongan_data.xlsx
    """

    def handle(self, *args, **options):

        dt_result = tablib.Dataset()
        dt_result.headers = [u'美购ID', u'众安保险类型']

        wb = load_workbook(filename=u'/data/insurance/zhongan_original_data.xlsx')
        sheetnames = wb.get_sheet_names()
        if sheetnames == 0:
            return
        ws = wb.get_sheet_by_name(sheetnames[0])
        for rx in range(2, ws.get_highest_row()):
            try:
                tag_id = int(ws.cell(row=rx, column=1).value)
                zhongan_id = ws.cell(row=rx, column=2).value
                services = Service.objects.filter(project_type=tag_id).exclude(is_insurance=True).exclude(
                    user_safe=True).exclude(
                    Q(doctor__practice_licence='') | Q(doctor__business_licence='')).exclude(
                    Q(doctor__hospital__practice_licence='') | Q(doctor__hospital__business_licence=''))
                print services.count()
                for service in services:
                    row = []
                    row.append(service.id)
                    row.append(zhongan_id)
                    service.zhongan_type = zhongan_id
                    service.save()
                    dt_result.append(row)
            except Exception as e:
                print e.message
                continue
        open(u'/data/insurance/zhongan.xlsx', 'wb').write(dt_result.xlsx)
        print('Done!')
