from odoo import api, fields, models, SUPERUSER_ID, _
from odoo.exceptions import ValidationError
from datetime import datetime
import jionlp as jio
import logging
from odoo.exceptions import UserError
import requests
import base64

_logger = logging.getLogger(__name__)


class JdEclp(models.Model):
    _inherit = 'stock.picking'

    senderNickName = fields.Char(string='寄件工厂简称', required=True, default='MW')
    receiverName = fields.Char(string='收件人姓名', compute='_truck_info')
    receiverMobile = fields.Char(string='收件人电话', compute='_truck_info')
    receiverProvinceName = fields.Char(string='收件人省', compute='_truck_info')
    receiverCityName = fields.Char(string='收件人市', compute='_truck_info')
    receiverCountyName = fields.Char(string='收件人县', compute='_truck_info')
    receiverTownName = fields.Char(string='收件人详细地址', compute='_truck_info')
    receiverCompany = fields.Char(string='收货人公司', required=True)
    remark = fields.Char(string='物流面单备注', default='无')
    grossWeight = fields.Char(string='总重量', required=True, default=0)
    grossVolume = fields.Char(string='总体积', default=0)
    expressItemName = fields.Char(string='货物名称', required=True, default='非标工件')
    pickupBeginTime = fields.Char(string='期望取件时间')
    deliveryType = fields.Selection([('6', '特快零担'), ('25', '特快重货')], string='运输类型', default='25')
    # bill = fields.Char(string='物流面单')

    bill = fields.Many2one('ir.attachment', string='物流面单', compute='query_bill_pdf')

    @api.depends('carrier_tracking_ref')
    def query_bill_pdf(self):
        self.bill = self.env['ir.attachment'].sudo().search([('name', '=', self.carrier_tracking_ref)])


    @api.depends('origin')
    def _truck_info(self):
        sale_order_id = self.env['sale.order'].search([('name', '=', self.origin)])
        raw_addres = sale_order_id.address_of_delivery
        self.receiverName = sale_order_id.person_of_delivery
        self.receiverMobile = sale_order_id.telephone_of_delivery
        self.receiverProvinceName = jio.parse_location(raw_addres)['province']
        self.receiverCityName = jio.parse_location(raw_addres)['city']
        self.receiverCountyName = jio.parse_location(raw_addres)['county']
        self.receiverTownName = jio.parse_location(raw_addres)['detail']
        # self.receiverMobile = sale_order_id.telephone_of_delivery

    def create_order(self):
        # sale_order_id = self.env['sale.order'].search([('name', '=', self.origin)])

        # if self.carrier_id == '京东物流':
        createTime = str(datetime.now())
        json1 = {
            'params': {
                'orderNo': self.origin,
                'senderNickName': self.senderNickName,
                'receiverName': self.receiverName,
                'receiverMobile': self.receiverMobile,
                'receiverProvinceName': self.receiverProvinceName,
                'receiverCityName': self.receiverCityName,
                'receiverCountyName': self.receiverCountyName,
                'receiverTownName': self.receiverTownName,
                'remark': self.remark,
                'grossWeight': self.grossWeight,
                'grossVolume': self.grossVolume,
                'createTime': createTime,
                # 'createUser': self.user_id,
                'expressItemName': self.expressItemName,
                'pickupBeginTime': self.pickupBeginTime,
                'deliveryType': self.deliveryType,
                'receiverCompany': self.receiverCompany,
            },
        }
        _logger.info('准备调接口1')
        url1 = 'https://bfm.cs.jikimo.com/api/create/jd/order'
        requests.post(url1, json=json1, data=None)
        _logger.info('调用成功1')
        _logger.info('准备调接口2')
        json2 = {
            'params': {
                'orderNo': self.origin,
            },
        }
        url2 = 'https://bfm.cs.jikimo.com/api/get/jd/no'
        response = requests.post(url2, json=json2, data=None)
        # _logger.info('调用成功2', response.json()['result']['wbNo'])
        self.carrier_tracking_ref = response.json()['result']['wbNo']


        # else:
        #     raise UserError("选择京东物流才能下单呦")

    def get_bill(self):

        json1 = {
            'params': {
                'no': self.origin,
            },
        }
        url1 = 'https://bfm.cs.jikimo.com/api/create/jd/bill'
        response = requests.post(url1, json=json1, data=None)
        # _logger.info('调用成功2', response.json())

        # _logger.info('调用成功2', response.text)
        bill_url_str = response.json()['result']['jingdong_eclp_co_generateBdWayBillFile_responce']['result']['content']
        bill_url = 'http:' + bill_url_str
        data = base64.b64encode(requests.get(bill_url).content)
        # self.bill = ''
        _logger.info('调用成功2')
        attachment = self.env['ir.attachment'].sudo().create({
            'datas': data,
            'type': 'binary',
            'description': '快递面单',
            'name': self.carrier_tracking_ref,
            # 'res_id': invoice.id,
            # 'res_model': 'stock.picking',
            'public': True,
            'mimetype': 'application/pdf',
            # 'model_name': 'stock.picking',
        })
        _logger.info(attachment)
        # _logger.info(attachment.datas)
        # _logger.info(attachment.datas_fname)



