define('DS/UpdateModalValue/UpdateModalValue', [
    'UWA/Core',
    'DS/ApplicationFrame/Command',
    'DS/ENOXEngineerCommonUtils/XENModal',
    'DS/ENOXEngineerCommonUtils/xEngAlertManager',
    'DS/EngineeringItemCmd/SetPartNumberCmd/setPartNumberListView',
    'DS/ENOXEngineerCommonUtils/XENPlatform3DXSettings',
    'DS/ENOXEngineerCommonUtils/PromiseUtils',
    'DS/ENOXEngineerCommonUtils/XENCommandsAppContextProxy',
    'DS/ENOXEngineerCommonUtils/XENWebInWinHelper',
    'i18n!DS/EngineeringItemCmd/assets/nls/ExposedCmdsNls.json',
    'css!DS/UpdateModalValue/layui/css/layui.css',
    'DS/UpdateModalValue/layui/layui.all',
    'text!DS/UpdateModalValue/index.html',
    'DS/UpdateModalValue/layui/xmSelect'
], function (
    UWA,
    AFRCommand,
    XEngineerModal,
    xEngAlertManager,
    PartNumberListView,
    XENPlatform3DXSettings,
    PromiseUtils,
    XENCommandsAppContextProxy,
    XENWebInWinHelper,
    nlsKeys,
    LayUI,
    laycss,
    testHTML,
    xmSelect
) {
    'use strict';

    //todo
    var SetPartNumber = AFRCommand.extend({
        _setPartNumberListView: null,
        items: [],
        modal: null,
        transactionParameters: null,
        sTenentID: "OnPremise",
        securityContext: null,
        myBaseAppURL: null,
        init: function (options) {
            options = UWA.extend(options, {
                isAsynchronous: false
            });
            this._parent(options);

            // IR-749796-3DEXPERIENCER2021x
            // The initialization is to early to get the app Security context to correct it
            // the initialization has been deplaced in isUserGranted call and the that.enable() is now check with isUserGranted
            // XENCommandsAppContextProxy.loadCommandsSetting();
            this._initCommandPrereqs();
        },

        //人员验证
        isUserGranted: function () {
            var that = this;
            if (this.grantingPromise)
                return this.grantingPromise;
            this.grantingPromise = PromiseUtils.wrappedWithCancellablePromise(function (resolve, reject) {
                XENCommandsAppContextProxy.loadCommandsSetting()
                    .then(function (settings) {
                        if (settings && settings.isGrantedEnterpriseExtension) {
                            resolve(true);
                        } else {
                            if (XENPlatform3DXSettings.isCatiaV6Environment()) { //Setting added for IR-788376-3DEXPERIENCER2020x
                                resolve(true);
                            } else {
                                reject('user is not granted');
                            }
                        }
                    }).catch(function (reason) {
                        if (XENPlatform3DXSettings.isCatiaV6Environment()) { //Setting added for IR-788376-3DEXPERIENCER2020x
                            resolve(true);
                        } else {
                            console.error(reason);
                            reject('some failure');
                        }
                    });
            });
            return this.grantingPromise;
        },

        //todo 返回的值为 VPLMProjectLeader.Company Name.Common Space //该方法用处还需进一步验证
        getProvidedSC: function () {
            if (!this.options.context || !this.options.context.getSecurityContext)
                return null;

            var _sc = this.options.context.getSecurityContext() || {};
            var value = _sc.SecurityContext;
            if (_sc.SecurityContext) {
                if (value.startsWith('ctx::'))
                    value = value.substring(5);
                XENPlatform3DXSettings.setDefaultSecurityContext(value);
            }

            if (_sc.tenant) {
                XENPlatform3DXSettings.setPlatformId(_sc.tenant);
            }
            return value;
        },

        // 页面加载时触发
        execute: function () {
            var that = this;
            XENCommandsAppContextProxy.getAppContextPromise(this).then(function (context) {
                var ModalPhysicalId = "";
                //获取数据值
                that.items = that.options.context.getSelectedNodes().map(function (item) {
                    console.log(item);
                    //modalValue = item.options.grid['ds6w:identifier'];
                    ModalPhysicalId = item.getID();
                    console.log("==========>");
                    console.log(ModalPhysicalId);
                    return {
                        physicalId: item.getID(),
                        name: item.getLabel(),
                        sessionStoredEIN: (item.getSessionStoredEIN && item.getSessionStoredEIN()) ? item.getSessionStoredEIN() : undefined,
                        partNumber: item.options.grid['ds6wg:EnterpriseExtension.V_PartNumber']
                    };
                });
                if (XENPlatform3DXSettings.isBuildSecurityContext() && XENPlatform3DXSettings.isCloud()) {
                    var _platform = {};
                    var strTenentId = that.sTenentID;
                    var sURL = that.myBaseAppURL;
                    _platform[strTenentId] = {
                        "3DSpace": sURL
                    }
                    XENPlatform3DXSettings._platforms = _platform;
                    XENPlatform3DXSettings.setDefaultSecurityContext(that.securityContext.replace("ctx : ", ""));

                    that._setPartNumberListView = new PartNumberListView();
                    that._setPartNumberListView.render();
                    that.showDialog(ModalPhysicalId);
                } else {
                    var needSC = (!that.getProvidedSC());
                    XENPlatform3DXSettings.bindCommandsToABackend(needSC /* need to retrieve SC */).then(function () {
                        that.isUserGranted().then(function () {
                            that._setPartNumberListView = new PartNumberListView();
                            that._setPartNumberListView.render();
                            //todo

                            that.showDialog(ModalPhysicalId);
                        }).catch(function (reason) {
                            xEngAlertManager.errorNotif({
                                title: nlsKeys.get("error.not.granted"),
                                subtitle: nlsKeys.get("error.contact.admin"),
                            });
                            that.progressDialog.close();
                        });
                    }).catch(function (error) {
                        console.error(error);
                        //notify the user
                        xEngAlertManager.unexpectedFailure(nlsKeys.get('failure.setPartNumber.cmd.launch'));
                        that.progressDialog.close();
                    })
                }
            })
        },

        // 向页面写具体body页面
        showDialog: function (ModalPhysicalId) {
            let httpBaseUrl = "/3dspace/ModalInfo/";

            layui.use(['form', 'jquery'], function () {
                var form = layui.form;
                var $ = layui.jquery;
                let layer = layui.layer;

                //判断当前模型是否是在工作中的状态
                $.get({
                    url: httpBaseUrl + "GetModalState?PhysicalId=" + ModalPhysicalId,
                    crossDomain: true,
                    contentType: "application/json",
                    dataType: "json",
                    success: function (res) {
                        let modalCurrentState = res.data;
                        console.log(modalCurrentState);
                        if ("IN_WORK" == modalCurrentState) {
                            //公司代码数据
                            var companyCodeValue = "";

                            //物料组数据
                            var AEGVPMDataValue = "";

                            layer.open({
                                type: 1,
                                title: ["物料组修改", "font-size : 16px; font-weight: bold; color: #fff; background-color: #005685"],
                                area: ["700px", "350px"],
                                content: testHTML,
                                success: function () {
                                    var companyCodeSelect = xmSelect.render({
                                        el: '#demo1',
                                        filterable: true,
                                        radio: true,
                                        clickClose: true,
                                        data: [],
                                        toolbar: { show: true },
                                        on: function (data) {
                                            var arr = data.arr;
                                            if (arr.length > 0) {
                                                companyCodeValue = arr[0].value;
                                                console.log(companyCodeValue);
                                                GetMaterialGroupData(materialGroupSelect, companyCodeValue)
                                            }
                                        }
                                    })
                                    GetCompanyCodeData("GetCompanyCode", companyCodeSelect);

                                    var materialGroupSelect = xmSelect.render({
                                        el: '#demo2',
                                        filterable: true,
                                        radio: true,
                                        clickClose: true,
                                        toolbar: { show: true },
                                        on: function (data) {
                                            var arr = data.arr;
                                            console.log(arr);
                                            if (arr.length > 0) {
                                                AEGVPMDataValue = arr[0].material;
                                                console.log("0000000000");
                                                console.log(AEGVPMDataValue);
                                            }
                                        }
                                    })
                                }
                            })

                            function GetCompanyCodeData(url, companyCodeSelect) {
                                $.get({
                                    url: httpBaseUrl + url,
                                    crossDomain: true,
                                    contentType: "application/json",
                                    dataType: "json",
                                    success: function (res) {
                                        console.log(res.data);
                                        let companyCode = JSON.parse(res.data);
                                        companyCodeSelect.update({ data: companyCode });
                                    }
                                });
                            }

                            function GetMaterialGroupData(materialGroupSelect, value) {
                                $.get({
                                    url: httpBaseUrl + "GetMaterialGroup",
                                    crossDomain: true,
                                    contentType: "application/json",
                                    dataType: "json",
                                    success: function (res) {
                                        let AEGVPMDataValue = JSON.parse(res.data);

                                        let Array = [];

                                        $.each(AEGVPMDataValue, function (index, item) {
                                            let valueJson = {};

                                            if (item.value.includes(value)) {
                                                valueJson.name = item.name,
                                                    valueJson.value = item.value,
                                                    valueJson.material = item.material,
                                                    Array.push(valueJson);
                                            }
                                        })

                                        // console.log(Array);

                                        materialGroupSelect.update({ data: Array });
                                    }
                                });
                            }

                            // form.on('select(companyCode)', function (data) {
                            //     let companyCodeBySelect = data.value; //获取选中的省份索引

                            //     console.log("00000");
                            //     console.log(companyCodeBySelect);

                            //     //清空城市选择器
                            //     $('#MateriaGroup').empty();

                            //     console.log("123123");

                            //     console.log(AEGVPMData);


                            //     for (let index = 0; index < AEGVPMData.length; index++) {
                            //         console.log("234566");
                            //         console.log(AEGVPMData[index].code);
                            //         console.log(companyCodeBySelect);
                            //         if(AEGVPMData[index].code == companyCodeBySelect){
                            //             $('#MateriaGroup').append('<option value = "' + AEGVPMData[index].material + '">' + AEGVPMData[index].materialZH + '</option>')
                            //         }
                            //     }

                            //     form.render('select');
                            // });

                            $('#myButton').on('click', function (data) {
                                console.log(data);

                                // var selectedCompanyCode = $('#demo1').val();
                                // var selectedMateriaGroup = $('#demo2').val();
                                // console.log(ModalPhysicalId);
                                // console.log(selectedMateriaGroup);
                                // console.log(selectedCompanyCode);

                                if (AEGVPMDataValue != "" && AEGVPMDataValue != null) {
                                    $.post({
                                        url: httpBaseUrl + "UpdateModalInfo/" + ModalPhysicalId + "/" + companyCodeValue + "/" + AEGVPMDataValue,
                                        crossDomain: true,
                                        contentType: "application/json",
                                        dataType: "json",
                                        success: function (res) {
                                            layer.closeAll();
                                        }
                                    }).done(function () {
                                        layer.msg('修改成功');
                                    })
                                } else {
                                    layer.msg('物料组不能为空')
                                }
                            });
                        } else {
                            layer.msg('当前模型已发布，不可更改，请联系管理员');
                        }
                    }
                })
            })
        }
    });
    return SetPartNumber;
});