"use strict";
layui.extend({
    common    :   'js/common'
}).use(['jquery','layer','common','form'],function () {
    var $ = layui.jquery;

    var regionText = '';

    (function () {

        var regions = {};

        function getList(data) {
            return $.ajax({
                url : '/permissions/region/authorize/getAuthorizeRegion',
                data : data
            });
        }

        function renderingRegion(list,$node) {
            $node.html('<option value="">请选择</option>');
            list.forEach(function (region) {
                $node.append('<option value="' + region.id + '">' + region.name + '</option>');
                regions[region.id] = region;
            });
            layui.form.render('select');
        }

        function getProvinceList() {
            getList({ groupBy : 1 }).then(function (result) {
                if (result.code === '200'){
                    renderingRegion(result.list,$('#province'));
                } else {
                    layer.alert(result.msg);
                }
            });
        }

        function getCityList(pid){
            getList({ groupBy : 2, pid : pid }).then(function (result) {
                if (result.code === '200'){
                    renderingRegion(result.list,$('#city'));
                } else {
                    layer.alert(result.msg);
                }
            });
        }

        layui.form.on('select(province_filter)', function(data){
            var pid = data.value;
            if (pid){
                getCityList(pid);
            } else {
                $('#city').html('');
                layui.form.render('select');
            }
        });

        layui.form.on('select(city_filter)', function(data){
            var region = regions[data.value];
            regionText = region ? regions[region.pid].name + '-' + region.name : '';
        });

        getProvinceList();

    })();

    layui.form.on("submit(entity_submit_event)",function(data){
        var entity = data.field;
        if (!entity.regionCode){
            layer.msg("请选择省份和城市");
            return;
        }
        if (!entity.value){
            layer.msg("请输入阈值");
            return;
        }
        entity.region = regionText;
        $.ajax({
            url : '/ad/threshold_config/add',
            type : 'POST',
            data : entity
        }).then(function (result) {
            if (result.code === '200'){
                $('button[type="reset"]').click();
                parent.location.reload();
            } else {
                layer.alert(result.msg);
            }
        });
    });

    $('button[type="reset"]').on('click',function () {
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    });

});
