/** @odoo-module **/

import { registry } from "@web/core/registry";
import { standardFieldProps } from "@web/views/fields/standard_field_props";
import { useBus, useService } from "@web/core/utils/hooks";
const { Component, xml } = owl;


export class BarcodeHandlerField extends Component {
    setup() {
        console.log('99999999111');
        this.actionService = useService("action")
        console.log(this.actionService)

        const barcode = useService("barcode");
        // this.rpc  = useService("rpc");
        // useBus(barcode.bus, "barcode_scanned", this.onBarcodeScanned.bind(this));
        useBus(barcode.bus, "barcode_scanned", this.onBarcodeScanned.bind(this));
    }
        async _rpc(params) {
        // const { data } = await this.env.services.rpc('/web/dataset/call_kw', params);
        const response = await this.env.services.rpc('/web/dataset/call_kw', params);
        console.log('response', response);
        console.log('response.result', response.result);

        // return response
        const responseObject = JSON.parse(response)
        return responseObject;
    }

    async onBarcodeScanned(event) {
        const { barcode } = event.detail;
        this.props.update(barcode);
        // const actionService = useService("action");
        // const productId = 12345
        console.log('111222222222211111');

        // 根据条形码获取相关数据，例如产品ID
        const response = await this._rpc({
            model: 'mrp.workorder',
            method: 'get_product_id_by_barcode',
            args: [barcode],
            kwargs:{},
        });
        // console.log(productId.result)
        if (response.result) {
            const action = response.result;
            console.log(action)
            console.log('11111111111111111111111111111111111');
            // 通过产品ID执行操作并跳转到表单视图
            // await this.actionService.doAction({
            //     // type: 'ir.actions.act_window',
            //     // res_model: 'product.product',
            //     // res_id: productId,
            //     // views: [[false, 'form']],
            //     // target: 'current',
            //     'name': '工单',
            //     'type': 'ir.actions.act_window',
            //     'views': [[false, 'form']],
            //     'view_mode': 'form',
            //     'res_model': 'mrp.workorder',
            //     'view_id': 918,
            //     'res_id': 1023,
            //     'target': 'current',
            // });
            await this.actionService.doAction(response.result);
        } else {
            console.error("Barcode not found or RPC call failed.");
        }
    }

}

BarcodeHandlerField.template = xml``;
BarcodeHandlerField.props = { ...standardFieldProps };

registry.category("fields").add("barcode_handlerrr", BarcodeHandlerField);
