/* 项目: jdg-core-base
 * 文件: multi_selection
 * 模块名称:
 * Copyright 2018 JDG <www.yunside.com>
 * Created by bjccdsrlcr (longjie.jiang@yunside.com) @ 11/25/19
 */
odoo.define('jd_report.dynamic_selection', function (require) {
    "use strict";
    var core = require('web.core');
    var Model = require('web.DataModel');
    var FieldSelection = core.form_widget_registry.get('selection');
    var _t = core._t;
    FieldSelection.include({
        query_values: function () {
            var self = this;
            var def;
            if (this.field.type === "many2one") {
                var model = new Model(this.field.relation);
                def = model.call("name_search", ['', this.get("domain")], {"context": this.build_context()});
            } else {
                var domain = this.get('domain');
                var values = [];
                if (domain.length > 0) {
                    _.each(this.field.selection, function (item) {
                        if ($.inArray(item[0], eval(domain)) !== -1) {
                            values.push(item)
                        }
                    });
                } else {
                    values = this.field.selection
                }
                // var values = _.reject(this.field.selection, function (v) { return v[0] === false && v[1] === ''; });
                def = $.when(values);
            }
            this.records_orderer.add(def).then(function (values) {
                if (!_.isEqual(values, self.get("values"))) {
                    self.set("values", values);
                }
            });
            if (this.node.attrs.widget === 'report_selection') {
                this.$el.selectpicker('refresh')
            }
        },
        render_value: function () {
            var values = this.get("values");
            values = [[false, this.node.attrs.placeholder || '']].concat(values);
            var found = _.find(values, function (el) {
                return el[0] === this.get("value");
            }, this);
            if (!found) {
                found = [this.get("value"), _t('Unknown')];
                values = [found].concat(values);
            }
            if (!this.get("effective_readonly")) {
                this.$el.empty();
                for (var i = 0; i < values.length; i++) {
                    this.$el.append($('<option/>', {
                        value: JSON.stringify(values[i][0]),
                        html: values[i][1]
                    }))
                }
                this.$el.val(JSON.stringify(found[0]));
            } else {
                this.$el.text(found[1]);
            }
            if (this.node.attrs.widget === 'report_selection') {
                this.$el.selectpicker()
            }
        },

    })
});
