/** @odoo-module **/

import { browser } from "@web/core/browser/browser";
import { Dialog } from "@web/core/dialog/dialog";
import { _lt } from "@web/core/l10n/translation";
import { useChildRef, useOwnedDialogs, useService } from "@web/core/utils/hooks";
import { sprintf } from "@web/core/utils/strings";
import { isMobileOS } from "@web/core/browser/feature_detection";
import * as BarcodeScanner from "@web/webclient/barcode/barcode_scanner";
const { useRef } = owl;
const {xml, Component} = owl;
import { standardFieldProps } from "@web/views/fields/standard_field_props";
import {registry} from "@web/core/registry";
import {useInputField} from "@web/views/fields/input_field_hook";

export class CodeField extends Component {
    setup() {
        console.log('CodeField created')
        console.log('this',this)
        console.log('this.props',this.props)
        console.log('this.props.record',this.props.value)
        useInputField({
           getValue: () => this.props.value,
           refName: "scan_code",
        });
        console.log('我是setup1')
        super.setup();
        this.orm = this.env.services.orm;
        this.record = this.props.record;
    }

     async onBarcodeBtnClick() {
        const barcode = await BarcodeScanner.scanBarcode();
        if (barcode) {
             await this.onBarcodeScanned(barcode);
            if ("vibrate" in browser.navigator) {
                browser.navigator.vibrate(100);
            }
        } else {
            this.notification.add(this.env._t("Please, scan again !"), {
                type: "warning",
            });
        }
    }
    async search(barcode) {
        // alert('我是search')
        const domain = [["code", "=", barcode]];
        console.log(domain)
        const fields = ["id", "code", "name", "state"];
        console.log(fields)
        const results = await this.orm.call("sf.tray", "search_read", [domain, fields]);
        const values = await this.orm.call("sf.tray", "search_read", [domain]);
        console.log(results)
        return results.map((result) => {
                return {
                  id: result.id,
                  code: result.code,
                  name: result.name,
                  state: result.state,
                  values: values,
                };
      });
    }
    async onBarcodeScanned(barcode) {
        const results = await this.search(barcode);
        console.log(results)
        const records = results.filter((r) => !!r.id);
        console.log(records)
        if (records.length === 1) {
            if (records[0].state === '空闲') {
                 console.log('currentModel',this)
                 console.log('this.record.data',this.record.data)
                console.log('this.record.data.id', this.record.data.id)
                const workorder = await this.orm.call('mrp.workorder', 'read', [this.record.data.id]);
                console.log('workorder', workorder[0])
                const updatedRecord = await this.orm.call("sf.tray", "write", [
                [records[0].id],
                {
                  state: "占用",
                  workorder_id: workorder[0].id,
                  production_id: workorder[0].product_id[0],
                  // workorder_id: workorder.id,
                }]);
                console.log(workorder[0].routing_type);
                console.log(workorder[0].production_id);
                // const productionIDS = await this.orm.call('mrp.production', 'search', [[['id', '=', workorder[0].production_id[0]]]]);
                const productionIDS = await this.orm.call('mrp.workorder', 'search', [[["production_id", "=", workorder[0].production_id[0]]]]);
                console.log('prooooooo', productionIDS);
                console.log('values', records[0].values[0]);
                productionIDS.forEach(async (data) => {
                  // 处理每一个数据
                  console.log(data);
                  const updatetrayRecord = await this.orm.call("mrp.workorder", "write", [
                    [data],
                    {
                      tray_id: records[0].values[0].id,
                      // tray_id: false,
                    }]);
                  console.log(updatetrayRecord)
                });
                this.props.update(records[0].code);
                $('.o_form_button_save').click();
            } else {
                if (records[0].state === '占用') {
                    console.log('此托盘已占用，请检查')
                    alert('此托盘已占用，请检查')
                } else {
                    console.log('此托盘已损坏，请登记')
                }
            }

        } else {
            const searchInput = this.autocompleteContainerRef.el.querySelector("input");
            searchInput.value = barcode;
            searchInput.dispatchEvent(new Event("input"));
            if (this.env.isSmall) {
                searchInput.click();
            }
        }
    }
}
CodeField.template = 'sf_machine_connect.CodeField'
// Register the field in the registry
CodeField.props = standardFieldProps;
registry.category("fields").add("code", CodeField);
