# coding=utf-8
import json
import requests
from django.utils import timezone
from django.conf import settings
from hashlib import md5
from utils.exceptions import CustomError
from apps.base import Formater
from django.db import transaction
from rest_framework.views import APIView
from rest_framework.decorators import action
from rest_framework import generics
from utils import response_ok
from apps.account import tenant_log
from apps.foundation.models import BizLog, Config
from apps.customer.models import CustomerVehicle
from rest_framework.exceptions import NotFound
from utils.format import *



def gender_sign(gateway_key):
    ts = timezone.now().strftime('%Y%m%d%H%M%S')
    token = gateway_key + ts

    m = md5()
    m.update(token.encode("utf8"))
    sign = m.hexdigest()
    return ts, sign


class XGJ():
    @staticmethod
    def vehicle_inquiry(instance): #询价单
        xgj_ip = Config.getConfigValue(Config.KEY_XGJ_IP)
        xgj_session_key = Config.getConfigValue(Config.KEY_XGJ_SESSION_KEY)

        if xgj_ip and xgj_session_key:
            ts, sign = gender_sign(xgj_session_key)
            url = xgj_ip + 'api/wechat_applet/vehicle_floor_add/?ts=' + ts + '&sign=' + sign

            param = {
                'company': instance.shop.xgj_id,
                'tel': instance.tel,
                'name': instance.name,
                'model': instance.model.series.brand.name + '-' + instance.model.series.name + '-' + instance.model.name,
                'guide_price': Formater.formatPriceShow(instance.model.price),
                'shop_price': Formater.formatPriceShow(instance.model.sale_price),
                'notes': instance.notes or u'小程序咨询'
            }
            result = requests.post(url=url, data=json.dumps(param))
            result = result.json()

            if not result['success']:
                if 'errors' in result:
                    tenant_log(instance.customer.user, BizLog.INSERT, u'新车询价同步销管佳失败[%s]，id=%d' % (str(result['errors']), instance.id))
                else:
                    tenant_log(instance.customer.user, BizLog.INSERT, u'新车询价同步销管佳失败,id=%d' % (instance.id))
            else:
                tenant_log(instance.customer.user, BizLog.INSERT, u'新车询价同步销管佳成功，id=%d' % (instance.id))
        else:
            tenant_log(instance.customer.user, BizLog.INSERT, u'新车询价同步销管佳失败，没有设置销管佳地址或密钥，id=%d' % (instance.id))

    @staticmethod
    def drive_reserve(instance): #试驾单
        xgj_ip = Config.getConfigValue(Config.KEY_XGJ_IP)
        xgj_session_key = Config.getConfigValue(Config.KEY_XGJ_SESSION_KEY)

        if xgj_ip and xgj_session_key:
            ts, sign = gender_sign(xgj_session_key)
            url = xgj_ip + 'api/wechat_applet/vehicle_drive_add/?ts=' + ts + '&sign=' + sign

            param = {
                'company': instance.shop.xgj_id,
                'tel': instance.tel,
                'name': instance.name,
                'model': instance.model.series.brand.name + '-' + instance.model.series.name + '-' + instance.model.name,
                'date': strfdate(instance.date),
                'notes': instance.notes or u'小程序预约'
            }
            result = requests.post(url=url, data=json.dumps(param))
            result = result.json()

            if not result['success']:
                if 'errors' in result:
                    tenant_log(instance.customer.user, BizLog.INSERT, u'试驾预约同步销管佳失败[%s]，id=%d' % (str(result['errors']), instance.id))
                else:
                    tenant_log(instance.customer.user, BizLog.INSERT, u'试驾预约同步销管佳失败,id=%d' % (instance.id))
            else:
                tenant_log(instance.customer.user, BizLog.INSERT, u'试驾预约同步销管佳成功，id=%d' % (instance.id))
        else:
            tenant_log(instance.customer.user, BizLog.INSERT, u'试驾预约同步销管佳失败，没有设置销管佳地址或密钥，id=%d' % (instance.id))

    @staticmethod
    def vehicle_estimate(instance): #置换咨询
        xgj_ip = Config.getConfigValue(Config.KEY_XGJ_IP)
        xgj_session_key = Config.getConfigValue(Config.KEY_XGJ_SESSION_KEY)

        if xgj_ip and xgj_session_key and instance.shop.is_xgj:
            ts, sign = gender_sign(xgj_session_key)
            url = xgj_ip + 'api/wechat_applet/vehicle_exchange_add/?ts=' + ts + '&sign=' + sign

            param = {
                'company': instance.shop.xgj_id,
                'tel': instance.customer.tel,
                'name': instance.customer.name,
                'model': instance.brand.name + '-' + instance.model,
                'plate_date': strfdate(instance.plate_date),
                'mileage': instance.mileage,
                'notes': instance.notes or u'小程序咨询'
            }
            result = requests.post(url=url, data=json.dumps(param))
            result = result.json()

            if not result['success']:
                if 'errors' in result:
                    tenant_log(instance.customer.user, BizLog.INSERT, u'置换咨询同步销管佳失败[%s]，id=%d' % (str(result['errors']), instance.id))
                else:
                    tenant_log(instance.customer.user, BizLog.INSERT, u'置换咨询同步销管佳失败,id=%d' % (instance.id))
            else:
                tenant_log(instance.customer.user, BizLog.INSERT, u'置换咨询同步销管佳成功，id=%d' % (instance.id))
        else:
            tenant_log(instance.customer.user, BizLog.INSERT, u'置换咨询同步销管佳失败，没有设置销管佳地址或密钥，或所选门店在销管佳中不存在，id=%d' % (instance.id))

    @staticmethod
    def maint_reserve(instance):  # 售后预约
        xgj_ip = Config.getConfigValue(Config.KEY_XGJ_IP)
        xgj_session_key = Config.getConfigValue(Config.KEY_XGJ_SESSION_KEY)

        if xgj_ip and xgj_session_key:
            ts, sign = gender_sign(xgj_session_key)
            url = xgj_ip + 'api/wechat_applet/maint_reserve_add/?ts=' + ts + '&sign=' + sign

            param = {
                'company': instance.shop.xgj_id,
                'tel': instance.tel,
                'name': instance.name,
                'model': instance.vehicle.name,
                'number': instance.vehicle.number,
                'vin': instance.vehicle.vin,
                'date': strfdate(instance.date),
                'notes': instance.notes
            }
            result = requests.post(url=url, data=json.dumps(param))
            result = result.json()

            if not result['success']:
                if 'errors' in result:
                    tenant_log(instance.customer.user, BizLog.INSERT,
                               u'售后预约同步销管佳失败[%s]，id=%d' % (str(result['errors']), instance.id))
                else:
                    tenant_log(instance.customer.user, BizLog.INSERT, u'售后预约同步销管佳失败,id=%d' % (instance.id))
            else:
                tenant_log(instance.customer.user, BizLog.INSERT, u'售后预约同步销管佳成功，id=%d' % (instance.id))
        else:
            tenant_log(instance.customer.user, BizLog.INSERT, u'售后预约同步销管佳失败，没有设置销管佳地址或密钥，id=%d' % (instance.id))

    @staticmethod
    def insur_consultation(instance):  # 续保咨询
        xgj_ip = Config.getConfigValue(Config.KEY_XGJ_IP)
        xgj_session_key = Config.getConfigValue(Config.KEY_XGJ_SESSION_KEY)

        if xgj_ip and xgj_session_key:
            ts, sign = gender_sign(xgj_session_key)
            url = xgj_ip + 'api/wechat_applet/insur_consultation_add/?ts=' + ts + '&sign=' + sign

            param = {
                'company': instance.shop.xgj_id,
                'tel': instance.tel,
                'name': instance.name,
                'content': instance.content
            }
            result = requests.post(url=url, data=json.dumps(param))
            result = result.json()

            if not result['success']:
                if 'errors' in result:
                    tenant_log(instance.customer.user, BizLog.INSERT,
                               u'续保咨询同步销管佳失败[%s]，id=%d' % (str(result['errors']), instance.id))
                else:
                    tenant_log(instance.customer.user, BizLog.INSERT, u'续保咨询同步销管佳失败,id=%d' % (instance.id))
            else:
                tenant_log(instance.customer.user, BizLog.INSERT, u'续保咨询同步销管佳成功，id=%d' % (instance.id))
        else:
            tenant_log(instance.customer.user, BizLog.INSERT, u'续保咨询同步销管佳失败，没有设置销管佳地址或密钥，id=%d' % (instance.id))

    @staticmethod
    def get_order(id):  # 售后工单
        vehicle = CustomerVehicle.objects.filter(id=id).first()
        xgj_ip = Config.getConfigValue(Config.KEY_XGJ_IP)
        xgj_session_key = Config.getConfigValue(Config.KEY_XGJ_SESSION_KEY)

        if xgj_ip and xgj_session_key:
            ts, sign = gender_sign(xgj_session_key)
            url = xgj_ip + 'api/wechat_applet/maint_order/list/?ts=' + ts + '&sign=' + sign

            param = {
                'tel': vehicle.tel,
                'number': vehicle.number,
            }
            result = requests.post(url=url, data=json.dumps(param))
            result = result.json()

            return result
        return {'data': []}