import random
import string
from django.utils import timezone
from django.conf import settings
from django.db import models
from apps.tenant.models import Tenant
from apps.tenant.option.models import Option
from apps.upload.models import Upload
from apps.tenant.repair_order.models import RepairOrder
from utils.exceptions import CustomError
from apps.tenant.device.models import DeviceModel


class InspectionOrder(models.Model):
    NOT_REPAIR = 1
    HAS_REPAIR = 2
    REPAIR = 3
    STATUS_CHOICES = (
        (NOT_REPAIR, '巡检正常'),
        (HAS_REPAIR, '已报修'),
        (REPAIR, '已修复'),
    )

    device = models.ForeignKey(DeviceModel, verbose_name='设备', on_delete=models.PROTECT, blank=True, null=True)
    device_name = models.CharField(max_length=100, verbose_name='设备名称')
    device_address = models.CharField(max_length=200, verbose_name='设备地址')
    no = models.CharField(max_length=50, verbose_name=u'编号', blank=True)
    status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, verbose_name=u'状态', default=NOT_REPAIR)
    tenant = models.ForeignKey(Tenant, verbose_name=u'租户', on_delete=models.PROTECT, blank=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u"巡检人员", on_delete=models.PROTECT,
                             editable=False, related_name='inspection_order_user')
    problem = models.CharField(max_length=500, verbose_name=u'巡检问题')
    create_time = models.DateTimeField(verbose_name=u'巡检时间', auto_now_add=True)
    images = models.ManyToManyField(Upload, verbose_name=u'图片', blank=True)
    repair_type = models.ForeignKey(Option, verbose_name=u'报修类型', on_delete=models.PROTECT, null=True)
    repair_order = models.ForeignKey(RepairOrder, verbose_name=u'转报修', on_delete=models.PROTECT, null=True)
    turn_repair_time = models.DateTimeField(verbose_name=u'转报修时间', null=True)
    turn_repair_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u"转报修人", on_delete=models.PROTECT,
                                         null=True, related_name='turn_repair_user')

    class Meta:
        db_table = 'inspection_order'
        verbose_name = '巡检工单'
        ordering = ['-create_time']
        index_together = (
            'status',
            'create_time',
        )
        default_permissions = ()
        permissions = [
            ('browse_inspection_order', u'查看'),
            ('add_inspection_order', u'添加'),
            ('delete_inspection_order', u'删除'),
            ('dturn_repair_inspection_order', u'转报修'),
        ]

    @staticmethod
    def get_instance_by_id(id, tenant):
        try:
            id = int(id)
        except:
            raise CustomError('无效的inspection_order_id')
        instance = InspectionOrder.objects.filter(pk=id, tenant=tenant).first()
        if not instance:
            raise CustomError('未找到对应的巡检工单实例')
        return instance

    def get_no(self):
        now = timezone.now()
        no = '%s%d-%s' % ('XJ', self.tenant.id, now.strftime('%Y%m%d%H%M%S'))
        return no

    def turn_repair(self, user):
        # 巡检转报修
        repair_order = RepairOrder.objects.create(tenant=self.tenant, device=self.device,
                                                  fault_des=self.problem, repair_type=self.repair_type, user=self.user,
                                                  tel=self.user.employee.tel,name=self.user.employee.name,
                                                  order_type=RepairOrder.INSPECTION_ORDER)
        repair_order.no = repair_order.get_no()
        images = self.images.all()
        for image in images:
            repair_order.images.add(image.id)
        repair_order.save()

        self.status = InspectionOrder.HAS_REPAIR
        self.repair_order = repair_order
        self.turn_repair_time = timezone.now()
        self.turn_repair_user = user

        self.save()
        return repair_order
