(function () {
    var scopeName = "field_6903530450190094319";

    var ContractNoImpl = function (options) {
        this.customWidgetType = scopeName;
        this._create(options);
    };

    ContractNoImpl.prototype = {
        constructor: ContractNoImpl,

        _create: function (options) {
            this._options = options;
            this._widgetId = options.privateId;
            this._widgetProxy = options.adaptation;
            this._wrapper = document.getElementById(this._widgetId);
            this._field = this._widgetProxy.childrenGetData(this._widgetId);
            this._tunnelId = 'Event' + this._widgetId;

            if (!this._wrapper) return console.warn('没有找到组件渲染的容器');

            this.clicked = 0;
            this._update();
        },

        _update: function (field) {
            if (field) this._field = field;
            this._destroy();
            this._buildRendering();
            this._postCreate();
        },

        _buildRendering: function () {
            var elemId = 'section-' + this._widgetId;
            var btnId = 'section-' + this._widgetId + '-btn';
            var tpl = '<section id="section-' + elemId + '">' +
                '<button id="' + btnId + '" style="display:block;border:1px solid blue;border-radius:5px;margin:8px 16px;padding:5px;line-height:24px;text-align:center">' + this._field.display + '</button>' +
                '</section>';

            this._wrapper.innerHTML = tpl;
            this._el = this._wrapper.querySelector('#' + elemId);
            this._btnEl = this._wrapper.querySelector('#' + btnId);
        },

        _postCreate: function () {
            this._fieldElement = this._wrapper.querySelector('.field0313__');

            if (this._fieldElement) {
                this._unbindTouchStart = this._bind(this._fieldElement, 'touchstart', this.onTouchStart.bind(this));
                this._unbindTouchEnd = this._bind(this._fieldElement, 'touchend', this.onTouchEnd.bind(this));
                this._unbindTouchMove = this._bind(this._fieldElement, 'touchmove', this.onTouchMove.bind(this));
            }

            this._unbindTap = this._bind(this._btnEl, 'click', this.onClick.bind(this)); // 改为 click
            this._unbindUpdate = this._listen(this._tunnelId, this._update.bind(this));
        },

        _destroy: function () {
            if (this._fieldElement) {
                this._unbindTouchStart && this._unbindTouchStart();
                this._unbindTouchEnd && this._unbindTouchEnd();
                this._unbindTouchMove && this._unbindTouchMove();
            }
            this._unbindTap && this._unbindTap();
            this._unbindUpdate && this._unbindUpdate();
            this._el = this._btnEl = this._fieldElement = null;
        },

        _bind: function (el, evt, cb) {
            el.addEventListener(evt, cb, false);
            return function () {
                el.removeEventListener(evt, cb, false);
            };
        },

        _listen: function (evt, cb) {
            var hub = this._widgetProxy.ObserverEvent;
            hub.listen(evt, cb);
            return function () {
                hub.remove(evt, cb);
            };
        },

        onTouchStart: function () {
            if (this._fieldElement) {
                this._fieldElement.style.backgroundColor = "#005297";
            }
        },

        onTouchEnd: function () {
            if (this._fieldElement) {
                this._fieldElement.style.backgroundColor = "#008BFF";
            }
        },

        onTouchMove: function () {
            if (this._fieldElement) {
                this._fieldElement.style.backgroundColor = "#005297";
            }
        },

        onClick: function () {
            var tableName = this._options.formMessage.tableName;
            var formmains = this._options.getData.formdata.formmains[tableName];
            var tableMap = formmains.elements;
            var contractNo = '', ncCorpCode = '', djNo = '', bipResult = '';
            const keys = Object.keys(tableMap);

            keys.forEach((k) => {
                let display = tableMap[k].display;
                let value = tableMap[k].value;
                if (display === '自动生成合同编号') contractNo = value;
                if (display === 'NC公司编码') ncCorpCode = value;
                if (display === '单据编号') djNo = value;
                if (display === 'BIP返回结果') bipResult = value;
            });

            if (bipResult.includes("推送BIP成功")) {
                alert("当前合同已成功推送BIP系统，禁止重复生成合同编号");
                return;
            }

            var proceed = true;
            if (contractNo !== '') {
                proceed = confirm('当前合同已经存在合同编号是否选择变更！');
            }

            if (ncCorpCode === '') {
                alert("合同主体编号为空，填写合同主体编号");
                return;
            }

            if (proceed) {
                const url = `${window.location.origin}/seeyon/servlet/ordinaryCodeServlet`;
                const params = new URLSearchParams({
                    unitCode: ncCorpCode,
                    oanum: djNo
                });

                fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: params.toString()
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.isSucceed === "200") {
                            formmains.elements["field0249"].value = data.newCode; // 请确认 field0249 是你实际的字段key
                        } else if (data.isSucceed === "500") {
                            alert(data.msg);
                        } else {
                            alert("生成失败，请联系管理员");
                        }
                    })
                    .catch(() => {
                        alert("生成失败，请联系管理员");
                    });
            }

            this._update();
        }
    };

    var myWidgets = {};

    ContractNoImpl.init = function (options) {
        var widget = new ContractNoImpl(options);
        myWidgets[widget._widgetId] = widget;
    };

    ContractNoImpl.destroy = function (widgetId) {
        var widget = myWidgets[widgetId];
        if (widget) widget._destroy();
        delete myWidgets[widgetId];
    };

    window[scopeName] = ContractNoImpl;
})();
