# coding=utf-8
from __future__ import unicode_literals
from django.core.management import BaseCommand
import xlrd
import tablib
from api.tasks.export_excel_task import get_mail
from api.models import Service
from gm_types.gaia import YINUO_TYPE


class Command(BaseCommand):
    def handle(self, *args, **options):
        data = xlrd.open_workbook('/tmp/一诺支持tag标签.xlsx')
        table = data.sheets()[0]
        tag_ids = table.col_values(0)[1:]
        services = Service.objects.filter(tags__id__in=tag_ids, is_online=True)
        services.update(user_safe=False, yinuo_type=YINUO_TYPE.CASUALTY, zhongan_type=None)

        data = xlrd.open_workbook('/tmp/支持售卖众安保险美购tag表—产品组合ID.xlsx')
        table = data.sheets()[0]

        for i in range(table.nrows)[1:]:
            row = table.row_values(i)
            tag_id = int(row[0])
            zhongan_type = int(row[1])
            print tag_id, zhongan_type
            Service.objects.filter(tags__id=tag_id, is_online=True).update(yinuo_type=YINUO_TYPE.NONE, user_safe=False,
                                                                           zhongan_type=zhongan_type)

        data = []
        services = Service.objects.filter(yinuo_type=YINUO_TYPE.CASUALTY, is_online=True)
        for service in services:
            l = [
                ','.join([str(tag.id) for tag in service.tags.all()]),
                ','.join([tag.name for tag in service.tags.all()]),
                service.id,
                service.name,
                '一诺',
            ]
            data.append(l)

        services = Service.objects.filter(zhongan_type__isnull=False, is_online=True)
        for service in services:
            l = [
                ','.join([str(tag.id) for tag in service.tags.all()]),
                ','.join([tag.name for tag in service.tags.all()]),
                service.id,
                service.name,
                service.zhongan_type,
            ]
            data.append(l)

        xls = tablib.Dataset(*data, headers=['tag ID', 'tag 名称', '美购 ID', '美购名称', '保险组合ID'])
        get_mail(u'保险美购', '保险美购', 'liuqingxue@gmei.com', xls).send()
