/*+***********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is: vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 *************************************************************************************/

Vtiger_Edit_Js("Dealer_Edit_Js", {

}, {

    getRecordId: function(container) {

        return jQuery('input[name="record"]', container).val();

    },
    setUbigeo: function(crmid) {
        var url = "index.php?module=Vtiger&action=GetData&record=" + crmid + "&source_module=Ubigeo";
        app.helper.showProgress();
        app.request.get({ "url": url }).then(
            function(err, data) {
                app.helper.hideProgress();
                if (err === null) {
                    console.log("data", data)
                    if (data.success) {
                        var obj = data.data;
                        $("#Dealer_editView_fieldName_distrito_fiscal").val(obj.ubigeo_tks_distrito);
                        $("#Dealer_editView_fieldName_provincia_fiscal").val(obj.ubigeo_tks_provincia);
                        $("#Dealer_editView_fieldName_departamento_fiscal").val(obj.ubigeo_tks_departamento);
                    } else {
                        app.helper.showErrorNotification({ "message": data.message });
                    }
                } else {
                    app.helper.showErrorNotification({ "message": err });
                }
            });
    },

    initDealer: function(container) {
        $("#Dealer_editView_fieldName_distrito_fiscal").attr("readonly", true).css("background-color", "rgb(235, 235, 228)"); // readonly ubigeo
        $("#Dealer_editView_fieldName_provincia_fiscal").attr("readonly", true).css("background-color", "rgb(235, 235, 228)"); // readonly ubigeo
        $("#Dealer_editView_fieldName_departamento_fiscal").attr("readonly", true).css("background-color", "rgb(235, 235, 228)"); // readonly ubigeo

        $("#Dealer_editView_fieldName_dealer_tks_nombre").attr("readonly", true).css("background-color", "rgb(235, 235, 228)"); // readonly
        $("#Dealer_editView_fieldName_dealer_tks_apellidos").attr("readonly", true).css("background-color", "rgb(235, 235, 228)"); // readonly
        $("#Dealer_editView_fieldName_dealer_tks_accountname").attr("readonly", true).css("background-color", "rgb(235, 235, 228)"); // readonly
        //console.log("hola");
        var name1 = $('select[name="dealer_tks_tipopersona"]');
        var leadsource = $('select[name="leadsource"]');
        var nombre = $('#Dealer_editView_fieldName_dealer_tks_nombre');
        var apellido = $('#Dealer_editView_fieldName_dealer_tks_apellidos');
        var accountname = $('#Dealer_editView_fieldName_dealer_tks_accountname');

        var view = '';
        var tab_label = '';
        var thisInstance = this;
        var queryString = window.location.search;
        var urlParams = new URLSearchParams(queryString);
        if (urlParams.has('view')) view = urlParams.get('view');
        if (urlParams.has('tab_label')) tab_label = urlParams.get('tab_label');

        name1.on('change', function() {
            if ($('select[name="dealer_tks_tipopersona"]').val() == 'Natural') {
                console.log("natural");
                $('#Dealer_editView_fieldName_dealer_tks_nombre').removeAttr("readonly");
                $("#Dealer_editView_fieldName_dealer_tks_nombre").css("background-color", "");
                $('#Dealer_editView_fieldName_dealer_tks_apellidos').removeAttr("readonly");
                $("#Dealer_editView_fieldName_dealer_tks_apellidos").css("background-color", "");
                $('#Dealer_editView_fieldName_dealer_tks_nombre').attr("required", true);
                $('#Dealer_editView_fieldName_dealer_tks_apellidos').attr("required", true);
                $("#Dealer_editView_fieldName_dealer_tks_accountname").attr("readonly", true).css("background-color", "rgb(235, 235, 228)"); // readonly
                apellido.blur(function() {
                    accountname.val(nombre.val() + " " + apellido.val());
                });
                nombre.blur(function() {
                    accountname.val(nombre.val() + " " + apellido.val());
                });
            } else if ($('select[name="dealer_tks_tipopersona"]').val() == 'Juridica') {
                $('#Dealer_editView_fieldName_dealer_tks_nombre').removeAttr("required");
                $('#Dealer_editView_fieldName_dealer_tks_apellidos').removeAttr("required");
                $("#Dealer_editView_fieldName_dealer_tks_nombre").attr("readonly", true).css("background-color", "rgb(235, 235, 228)"); // readonly
                $("#Dealer_editView_fieldName_dealer_tks_apellidos").attr("readonly", true).css("background-color", "rgb(235, 235, 228)"); // readonly
                $('#Dealer_editView_fieldName_dealer_tks_accountname').removeAttr("readonly");
                $("#Dealer_editView_fieldName_dealer_tks_accountname").css("background-color", "");
                nombre.val("");
                apellido.val("");
            }
        });

        name1.trigger("change");

        $("#Dealer_editView_fieldName_operaciones_leasing").attr("readonly", true).css("background-color", "rgb(235, 235, 228)");
        $("#Dealer_editView_fieldName_operaciones_factoring").attr("readonly", true).css("background-color", "rgb(235, 235, 228)");

        // el bloqueo no debe afectar al administrador del sistema
        var is_admin = _USERMETA.is_admin;

        if (is_admin == "false") {
            $("select[name='dealer_tks_origen'] option[value='Chatbot']").attr("disabled", true);
            $("select[name='dealer_tks_origen'] option[value='Chatbot']").removeClass("picklistColor_dealer_tks_origen_Chatbot");
            $("select[name='dealer_tks_origen'] option[value='Chatbot']").css("background-color", "rgb(97, 98, 100) !important");
            $("select[name='dealer_tks_origen'] option[value='Landing Page']").attr("disabled", true);
            $("select[name='dealer_tks_origen'] option[value='Landing Page']").removeClass("picklistColor_dealer_tks_origen_Landing_Page");
            $("select[name='dealer_tks_origen'] option[value='Landing Page']").css("background-color", "rgb(97, 98, 100) !important");
        }

        // solo Cuando el origen está lleno no lo deja editar
        if (is_admin == "false" && $('select[name="dealer_tks_origen"]').val() != '' && (thisInstance.getRecordId(container) != '' && thisInstance.getRecordId(container) != undefined)) {
            $('select[name="dealer_tks_origen"]').attr("readonly", true).css("background-color", "rgb(235, 235, 228)");
        }

        var nombreElm = "dealer_tks_ruc";
        var elmRUC = $('input[name=' + nombreElm + ']');
        var spanPadre = elmRUC.parent();
        var ruc = elmRUC.val();

        spanPadre.html('<div class="referencefield-wrapper ">' +
            '<div class="input-group">' +
            '<input name="representantes" type="hidden" id="representantes">' +
            '<input id="Dealer_editView_fieldName_' + nombreElm + '" type="text" class="marginLeftZero inputElement inputRuc"' +
            'name="' + nombreElm + '" value="' + ruc + '">' +
            '<span class="input-group-addon cursorPointer" title="Buscar en Sentinel" id="buscarRUC_Sentinel"><i class="fa fa-search"></i></span>' +
            '</div>' +
            '</div>');
        elmRUC.val(ruc);

        $(document).on('click', '#buscarRUC_Sentinel', function() {
            let ruc = $('input[name=dealer_tks_ruc]').val();
            if (ruc) {
                var params = {
                    'module': 'Accounts',
                    'action': 'getSentinelData',
                    'ruc': ruc,
                    'record': $('input[name="record"]').val()
                }
                app.helper.showProgress();
                app.request.post({ data: params }).then(function(err, result) {
                    if (!err) {
                        app.helper.hideProgress();
                        if (result.duplicado) {
                            var options = {
                                message: "La cuenta ya existe, si desea actualizar sus datos ingrese a la opción de modificar.",
                                title: 'Esta cuenta ya existe.'
                            }
                            var settings = {
                                'delay': 0
                            };
                            app.helper.showErrorNotification(options, settings);
                        } else {
                            if (result.data) {
                                let string_ = JSON.parse(result.data);
                                let data = string_.result;
                                console.log(string_);
                                $('[name=representantes]').val(JSON.stringify(data.representante_legal));
                                $('[name=dealer_tks_accountname]').val(data.razon_social);
                                $('[name=direccion_fiscal]').val(data.domicilio_fiscal);
                                $('[name=distrito_fiscal]').val(data.distrito);
                                $('[name=provincia_fiscal]').val(data.provincia);
                                $('[name=departamento_fiscal]').val(data.departamento);
                                switch (data.tipo_documento) {
                                    case 'R':
                                        $('[name=dealer_tks_tipopersona]').val('Juridica');
                                        break;

                                    default:
                                        $('[name=v]').val('Natural');
                                        break;
                                }
                                $('[name=dealer_tks_tipopersona]').select2();

                            } else {
                                var options = {
                                    message: "No se encontraron datos.",
                                    title: 'No hay datos de este RUC.'
                                }
                                var settings = {
                                    'delay': 0
                                };
                                app.helper.showErrorNotification(options, settings);
                            }
                        }
                    }
                });
            }
        });
    },


    /**
     * Function which will register basic events which will be used in quick create as well
     *
     */
    registerBasicEvents: function(container) {
        this._super(container);
        this.initDealer(container);
    }
});