# -*- coding: utf-8 -*-
import json
import logging
from odoo import http
from odoo.http import request


class Sf_Bf_Connect(http.Controller):

    @http.route('/api/bfm_process_order/list', type='http', auth='sf_token', methods=['GET', 'POST'], csrf=False,
                cors="*")
    def get_bfm_process_order_list(self, **kw):
        """
        接收业务平台加工订单分配工厂时传送来的订单数据并生成销售订单和产品及坯料
        :param kw:
        :return:
        """
        res = {'status': 1, 'factory_order_no': ''}
        logging.info('get_bfm_process_order_list:%s' % kw)
        try:
            product_id = request.env.ref('sf_dlm.product_template_sf').sudo()
            self_machining_id = request.env.ref('sf_dlm.product_embryo_sf_self_machining').sudo()
            outsource_id = request.env.ref('sf_dlm.product_embryo_sf_outsource').sudo()
            purchase_id = request.env.ref('sf_dlm.product_embryo_sf_purchase').sudo()
            company_id = request.env.ref('base.main_company').sudo()
            # user_id = request.env.ref('base.user_admin').sudo()
            bfm_process_order_list = json.loads(kw['bfm_process_order_list'])
            order_id = request.env['sale.order'].with_user(request.env.ref("base.user_admin")).sale_order_create(
                company_id, kw['delivery_name'], kw['delivery_telephone'], kw['delivery_address'],
                kw['delivery_end_date'])
            i = 1
            # 给sale_order的default_code字段赋值
            aa = request.env['sale.order'].sudo().search([('name', '=', order_id.name)])
            logging.info('get_bfm_process_or===================================:%s' % order_id.name)
            aa.default_code = kw['order_number']
            logging.info('get_bfm_process_order_listaaaaaaaaaaaaaaaaaaaaaaaaaaaa================:%s' % aa.default_code)
            # # 给stock.picking的default_code字段赋值
            # bb = request.env['stock.picking'].sudo().search([('origin', '=', order_id.name)])
            # logging.info('get_bfm_process_or===================================:%s' % order_id.name)
            # bb.default_code = kw['order_number']
            # logging.info('get_bfm_process_order_listbbbbbbbbbbbbbbbbbbbbbbbbbbbb================:%s' % bb.default_code)

            for item in bfm_process_order_list:
                product = request.env['product.template'].sudo().product_create(product_id, item, order_id,
                                                                                kw['order_number'], i)
                bom_data = request.env['mrp.bom'].with_user(request.env.ref("base.user_admin")).get_bom(product)
                logging.info('bom_data:%s' % bom_data)
                if bom_data:
                    bom = request.env['mrp.bom'].with_user(request.env.ref("base.user_admin")).bom_create(product,
                                                                                                          'normal',
                                                                                                          False)
                    bom.with_user(request.env.ref("base.user_admin")).bom_create_line_has(bom_data)
                else:
                    if product.materials_type_id.gain_way == '自加工':
                        # 创建坯料
                        self_machining_embryo = request.env['product.template'].sudo().no_bom_product_create(
                            self_machining_id,
                            item,
                            order_id, 'self_machining', i)
                        # 创建坯料的bom
                        self_machining_bom = request.env['mrp.bom'].with_user(
                            request.env.ref("base.user_admin")).bom_create(
                            self_machining_embryo, 'normal', False)
                        # 创建坯料里bom的组件
                        self_machining_bom_line = self_machining_bom.with_user(
                            request.env.ref("base.user_admin")).bom_create_line(
                            self_machining_embryo)
                        if self_machining_bom_line == False:
                            res['status'] = 2
                            res['message'] = '该订单模型的材料型号在您分配的工厂里暂未有原材料,请先配置再进行分配'
                            request.cr.rollback()
                            return json.JSONEncoder().encode(res)
                        # 产品配置bom
                        product_bom_self_machining = request.env['mrp.bom'].with_user(
                            request.env.ref("base.user_admin")).bom_create(
                            product, 'normal', False)
                        product_bom_self_machining.with_user(request.env.ref("base.user_admin")).bom_create_line_has(
                            self_machining_embryo)
                    elif product.materials_type_id.gain_way == '外协':
                        # 创建坯料
                        outsource_embryo = request.env['product.template'].sudo().no_bom_product_create(outsource_id,
                                                                                                        item,
                                                                                                        order_id,
                                                                                                        'subcontract',
                                                                                                        i)
                        # 创建坯料的bom
                        outsource_bom = request.env['mrp.bom'].with_user(request.env.ref("base.user_admin")).bom_create(
                            outsource_embryo,
                            'subcontract', True)
                        # 创建坯料的bom的组件
                        outsource_bom_line = outsource_bom.with_user(
                            request.env.ref("base.user_admin")).bom_create_line(outsource_embryo)
                        if outsource_bom_line == False:
                            res['status'] = 2
                            res['message'] = '该订单模型的材料型号在您分配的工厂里暂未有原材料,请先配置再进行分配'
                            request.cr.rollback()
                            return json.JSONEncoder().encode(res)
                        # 产品配置bom
                        product_bom_outsource = request.env['mrp.bom'].with_user(
                            request.env.ref("base.user_admin")).bom_create(product, 'normal', False)
                        product_bom_outsource.with_user(request.env.ref("base.user_admin")).bom_create_line_has(
                            outsource_embryo)
                    elif product.materials_type_id.gain_way == '采购':
                        purchase_embryo = request.env['product.template'].sudo().no_bom_product_create(purchase_id,
                                                                                                       item,
                                                                                                       order_id,
                                                                                                       'purchase', i)
                        # 产品配置bom
                        product_bom_purchase = request.env['mrp.bom'].with_user(
                            request.env.ref("base.user_admin")).bom_create(product, 'normal', False)
                        product_bom_purchase.with_user(request.env.ref("base.user_admin")).bom_create_line_has(
                            purchase_embryo)
                order_id.with_user(request.env.ref("base.user_admin")).sale_order_create_line(product, item)
                i += 1
            res['factory_order_no'] = order_id.name
            return json.JSONEncoder().encode(res)
        except Exception as e:
            logging.info('get_bfm_process_order_list error:%s' % e)
            res['status'] = -1
            res['message'] = '工厂创建销售订单和产品失败，请联系管理员'
            request.cr.rollback()
            return json.JSONEncoder().encode(res)


class jdElcp(http.Controller):

    @http.route('/api/jd_create/order', type='http', auth='none', methods=['GET', 'POST'], csrf=False,
                cors="*")
    def get_jd_order(self, **kw):
        """
        回调函数：拿到京东返回的下单数据
        """
        logging.info('get_jd_order================:%s', kw)
        # aa = request.env['stock.picking'].sudo().search([('origin', '=', kw['orderNo'])])
        # aa.carrier_tracking_ref = kw['wbNo']
        # logging.info('get_jd_order================:%s' %
        #              aa.carrier_tracking_ref)

    @http.route('/api/jd_create/bill', type='http', auth='none', methods=['GET', 'POST'], csrf=False,
                cors="*")
    def get_jd_bill(self, **kw):
        """
        回调函数：拿到京东返回的快递面单
        """
        logging.info('get_jd_bill================:%s', kw)
        aa = request.env['stock.picking'].sudo().search([('origin', '=', kw['orderNo'])])
        aa.bill_url = kw['bill']
        logging.info('get_jd_bill================:%s' %
                     aa.bill_url)
