from odoo import models, fields
import datetime


class ReSaleOrder(models.Model):
    _inherit = 'sale.order'

    deadline_of_delivery = fields.Date('交货截止日期')
    person_of_delivery = fields.Char('交货人')
    telephone_of_delivery = fields.Char('交货人电话号码')
    address_of_delivery = fields.Char('交货人地址')

    # 业务平台分配工厂后在智能工厂先创建销售订单

    def sale_order_create(self, company_id, delivery_name, delivery_telephone, delivery_address,
                          deadline_of_delivery):
        now_time = datetime.datetime.now()
        partner = self.get_customer()
        order_id = self.env['sale.order'].sudo().create({
            'company_id': company_id.id,
            'date_order': now_time,
            'name': self.env['ir.sequence'].next_by_code('sale.order', sequence_date=now_time),
            'partner_id': partner.id,
            'state': 'draft',
            # 'user_id': user_id.id,
            'person_of_delivery': delivery_name,
            'telephone_of_delivery': delivery_telephone,
            'address_of_delivery': delivery_address,
            'deadline_of_delivery': deadline_of_delivery
        })
        return order_id

    def get_customer(self):
        customer = self.env['res.partner'].search([('name', '=', '业务平台')])
        if customer:
            return customer
        else:
            partner = self.env['res.partner'].create({'name': '业务平台'})
            return partner

    # 业务平台分配工厂时在创建完产品后再创建销售明细信息
    def sale_order_create_line(self, product, item):
        vals = {
            'order_id': self.id,
            'product_id': product.id,
            'name': '%s/%s/%s/%s/±%s/%s' % (
                product.model_long, product.model_width, product.model_height, product.model_volume,
                product.model_machining_precision,
                product.materials_id.name),
            'price_unit': product.list_price,
            'product_uom_qty': item['number'],
        }
        return self.env['sale.order.line'].create(vals)
