"use strict";
layui.extend({
    common: 'js/common',
    xmSelect:   'layui/dist/xm-select',
}).use(['jquery', 'form', 'common', 'upload', 'element','xmSelect'], function () {
    var $ = layui.jquery;
    var form = layui.form;
    var element = layui.element;
    var xmSelect = layui.xmSelect;
    var common = layui.common;
    //定义加载层id
    var loadId;
    //  页面元素
    var $node = {
        //  取消按钮
        resetBtn: $('button[type="reset"]'),
        fileName: $("#fileName"),
        fastDfsServer: $("#fastDfsServer"),
        iosAppUrl: $("#iosAppUrl"),
        downloadUrl: $("#downloadUrl"),
        packageMd5: $("#packageMd5"),
        downloadButton: $(".downloadButton"),

        must: '',
        packageType: $('input[name="packageType"]'),
        appType: $('input[name="app"]'),
        platform: $('input[name="platform"]'),

    };
    $.ajax({
        type: 'GET',
        url: '/permissions/dict/getByCode/deviceFactory',
        success: function (result) {
            deviceFactoryDict.update({data:result.list}).setValue([$('#factoryValue').val()]);
            $.ajax({
                type: 'GET',
                url: '/deviceTemplate/manage/getListByLikeTypeCode',
                data: {
                    deviceFactory : deviceFactoryDict.getValue('keyStr'),
                    isSelect : true,
                },
                success: function (result) {
                    deviceModelNumberSelect.update({data:result.list,disabled: false}).setValue([$('#deviceModelNumberValue').val()]);
                },
            });
        },
    });
    var deviceFactoryDict = xmSelect.render({
        el: '#factory',
        name: 'deviceFactory',
        layVerify: 'required',
        radio: true,
        clickClose: true,
        prop: {
            name: 'dictValue',
            value: 'dictKey',
        },
        on: function (data) {
            deviceModelNumberSelect.update({data : initDeviceTemplateFn(data),disabled: false});
        },
        model: {
            label: {
                type: 'text',
                text: {
                    left: '',
                    right: '',
                    separator: ', ',
                },
            }
        },
    });
    var deviceModelNumberSelect = xmSelect.render({
        el:'#device_model_number',
        name:'deviceModelNumber',
        tips:'请先选择设备厂商',
        empty:'暂时没有该设备厂商的设备配置与型号，请先添加该设备厂商的设备配置',
        disabled:true,
        radio: true,
        prop: {
            name: 'typeCode',
            value: 'typeCode'
        },
        clickClose: true,
        filterable: true,
        remoteSearch: true,
        remoteMethod:function (val,cb,show) {
            $.ajax({
                type: 'GET',
                url: '/deviceTemplate/manage/getListByLikeTypeCode',
                data: {
                    deviceFactory : deviceFactoryDict.getValue('keyStr'),
                    typeCode : val,
                    isSelect : true,
                },
                success:function (result) {
                    cb(result.list);
                },
                error:function () {
                    cb([]);
                }
            })
        },
        model: {
            label: {
                type: 'text',
                text: {
                    left: '',
                    right: '',
                    separator: ', ',
                },
            }
        },
    });
    layui.form.on('select(deviceFactory)',function (data) {
        deviceModelNumberSelect.update({data : initDeviceTemplateFn(),disabled: false});
    });
    function initDeviceTemplateFn(data) {
        var deviceTemplateList;
        common.sendSyncRequest("/deviceTemplate/manage/getListByLikeTypeCode", 'get', {
            deviceFactory : data.change[0].dictKey,
            isSelect : true,
        }, function (result) {
            deviceTemplateList = result.list;
        });
        return deviceTemplateList;
    }

    //  绑定表单提交事件
    layui.form.on("submit(entity_submit_event)", function (data) {
        layui.common.timer($('button[lay-filter="entity_submit_event"]'));
        var id = data.field.id;
        var url = "";
        if (id) {
            url = '/permissions/appPackage/edit';
        } else {
            url = '/permissions/appPackage/add';
        }
        if (data.field.packageType == 2) {
            data.field.downloadUrl = $node.iosAppUrl.val();
        }
        $.ajax({
            url: url,
            data: data.field,
            type: 'POST',
            success: function () {
                $node.resetBtn.click();
                parent.location.reload();
            }
        });
    });

    //监听选项卡切换
    element.on('tab(packageType)', function (data) {
        //选项卡下标index：    0：Android     1：IOS
        let index = data.index;
        if (index == 0) {
            $('#upFile span').before($node.must);
            $node.fileName.attr('lay-verify', 'required');
            $node.iosAppUrl.removeAttr('lay-verify');
            $node.packageType.val('1');
            $('input[name="platform"]').val('Android');
        } else if (index == 1) {
            $node.must = $('#upFile .must').remove();
            $node.fileName.removeAttr('lay-verify');
            $node.iosAppUrl.attr('lay-verify', 'required');
            $node.packageType.val('2');
            $('input[name="platform"]').val('IOS');
        }
        $('input[name="packageName"]').val('');
        $('input[name="version"]').val('');
        $('textarea[name="description"]').val('');
        $('input[name="downLoadUrl"]').val('');
        $('input[name="packageMd5"]').val('');
    });

    //  点击取消事件
    $node.resetBtn.on('click', function () {
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    });

    //视频上传
    layui.upload.render({
        elem: '#fileUploadButton'
        , url: '/common/file/upload/?isNeedMd5=true'
        ,exts: 'jpg|png|jpeg'
        , accept: 'file' //视频
        , before: function (obj) {
            //开启加载动画
            loadId = layer.msg('文件上传中', {
                icon: 16,
                shade: 0.4,
                time: false //取消自动关闭
            });
        }
        , done: function (res) {
            //关闭加载动画
            layer.close(loadId);
            if (res.code == "200") {
                var appType = $node.appType.val();
                var fullPath = res.data.fullPath;
                if (appType === "app") {
                    var names = fullPath.split('.');
                    var lastName = names[names.length - 1];
                    if (lastName != 'apk') {
                        layer.msg("上传的包格式不正确");
                        return;
                    }
                }
                $node.downloadButton.attr("href", $node.fastDfsServer.val() + fullPath);
                var fileName = fullPath;
                if (fullPath.lastIndexOf("/") >= 0) {
                    fileName = fullPath.substr(fullPath.lastIndexOf("/") + 1);
                }
                $node.fileName.val(fileName);
                //显示文件下载
                $node.downloadButton.show();
                //服务器地址
                $node.downloadUrl.val(fullPath);
                //文件的md5
                $node.packageMd5.val(res.data.md5);
            } else {
                layer.msg("上传失败");
            }
        }
        , error: function () {
            //关闭加载动画
            layer.close(loadId);
            layer.msg("上传失败");
        }
    });
});
