# coding:utf-8
from __future__ import unicode_literals

import sys
reload(sys)
sys.setdefaultencoding('utf8')
import json
import hashlib
import requests


class ZhiDaHao(object):

    def __init__(self, url, sp_no, secret_key):
        self.url = url
        self.sp_no = sp_no
        self.secret_key = secret_key

    @staticmethod
    def convert_phone(phone):
        return phone[:3] + '0000' + phone[7:]

    def post_to_zhida(self, order):

        sp_no = self.sp_no
        status = 1
        order_no = str(order.id)
        total_amount = order.service.gengmei_price * 100
        goods_name = order.service.name
        order_source_url = 'http://zd.gmei.com/promotion/{service_id}/'.format(service_id=order.service.id)
        customer_name = order.user.last_name
        customer_mobile = self.convert_phone(order.phone)
        customer_address = u'暂无'

        detail = {
            'item_id': order_no,
            'name': goods_name,
            'price': total_amount,
            'amount': 1,
            'desc': order.service.short_description,
            'url': order_source_url
        }

        data_dict = {
            'sp_no': sp_no,
            'status': status,
            'order_no': order_no,
            'total_amount': total_amount,
            'goods_name': goods_name,
            'order_source_url': order_source_url,
            'customer_name': customer_name,
            'customer_mobile': customer_mobile,
            'customer_address': customer_address,
            'detail': json.dumps([detail])
        }

        data_list = [k + '=' + str(v) for k, v in data_dict.items()]
        data_list.sort()
        data = ''.join(data_list)
        signature = data + self.secret_key
        signed = hashlib.md5(signature.encode('utf-8')).hexdigest()
        data_dict['sign'] = signed

        r = requests.post(self.url, data=data_dict)
        text = json.loads(r.text)
        return text




