#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import openpyxl
from collections import namedtuple

from django.core.management import BaseCommand

from api.models.service import Service, ServiceTag
from api.models.tag import Tag


class Command(BaseCommand):
    nt = namedtuple('TAG_TYPES', ['OPERATION', 'UN_OPERATION'])
    TAG_TYPES = nt(OPERATION=u'手术', UN_OPERATION=u'非手术')

    @property
    def read_info_from_file(self):
        re_data = dict()
        base_path = os.path.dirname(os.path.dirname(__file__))
        file_name = os.path.join(base_path, 'files', 'edit_service_operation_status.xlsx')

        wb = openpyxl.load_workbook(file_name)
        tags_sheet = wb.get_sheet_by_name(u'技术协助部分')

        operation_tag_list, un_operation_tag_list = [], []
        for idx, row in enumerate(tags_sheet.rows):
            if idx >= 1:
                _tag_type = row[3].value or ''
                _value = int(row[2].value or 0)

                if _tag_type == self.TAG_TYPES.OPERATION:
                    operation_tag_list.append(_value)

                elif _tag_type == self.TAG_TYPES.UN_OPERATION:
                    un_operation_tag_list.append(_value)

                else:
                    continue

        re_data.update({
            "operation_tag_list": operation_tag_list,
            "un_operation_tag_list": un_operation_tag_list,
        })

        return re_data

    def update_service_status(self, service_ids, status):
        _span = 1000
        for i in range(0, len(service_ids), _span):
            _service_ids = service_ids[i:i + _span]
            update_count = Service.objects.filter(is_online=True, id__in=_service_ids).update(is_operation=status)

            _msgt = self.TAG_TYPES.OPERATION if status else self.TAG_TYPES.UN_OPERATION
            print(u"UPDATE {} SERVICE OPERATION STATUS. current_count {}".format(_msgt, update_count))

    def handle(self, *args, **options):
        print("BEGIN")

        _tag_data = self.read_info_from_file

        print("GET OPERATION SERVICE_ID")
        operation_service_ids = set(ServiceTag.objects.filter(
            tag_id__in=_tag_data.get("operation_tag_list", [])).values_list("service_id", flat=True).distinct())

        print("GET UN_OPERATION SERVICE_ID")
        un_operation_service_ids = set(ServiceTag.objects.filter(
            tag_id__in=_tag_data.get("un_operation_tag_list", [])).values_list("service_id", flat=True).distinct())

        self.update_service_status(list(operation_service_ids - un_operation_service_ids), True)
        print("UPDATE SERVICE OPERATION DOWN")

        self.update_service_status(list(un_operation_service_ids - operation_service_ids), False)
        print("UPDATE SERVICE UN_OPERATION DOWN")

        print("END")
