define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    
    Fast.config.openArea = ['1200px','80%'];
    
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'platform/index' + location.search,
                    add_url: 'platform/add',
                    edit_url: 'platform/edit',
                    // del_url: 'platform/del',
                    multi_url: 'platform/multi',
                    import_url: 'platform/import',
                    table: 'platform',
                } 
            });

            let down_success = false;
              
            function updateProgress(){
                if(down_success) return;
                $.ajax({
                    url:"platform/updateProgress",
                    type:"GET",
                    dataType:"JSON",
                    success:(res)=>{ 
                        if(res.code == 1){
                            setpdateProgress(res.data);
                            if(res.data != 100){
                                updateProgress(); 
                            }
                        }
                    }
                });
            } 
            
            function setpdateProgress(num=0){
                $(".upgrade-progress-line").css({width:`${num}%`});
                $(".upgrade-progress-text").text(`${num}%`);
            }

            function wipecache(callback){
                $.ajax({
                    url: 'ajax/wipecache',
                    dataType: 'json',
                    data: {type: 'all'},
                    cache: false,
                    success: function (ret) {
                        if(typeof callback == 'function'){
                            callback();
                        }
                    }, error: function () {
                        if(typeof callback == 'function'){
                            callback();
                        }
                    }
                });
            }

            function initUploadWxapp(tips){
                Layer.confirm(
                    tips||"您还未加载上传小程序代码组件，是否加载？",
                    {icon: 3, title: __('Warning'),  shadeClose: true, btn: [__('OK'), __('Cancel')]},
                    function (index) {
                        let loadIndex = layer.msg('加载中，请稍后', {
                            icon: 16,
                            shade: 0.01,
                            time:false
                        });

                        $.ajax({
                            url:"platform/initupload",
                            type:"GET",
                            dataType:"JSON",
                            success:(res)=>{
                                layer.close(loadIndex)
                                if(res.code == 1){
                                    layer.msg(res.message||res.msg, {icon: 1});
                                }
                                else{
                                    layer.msg(res.message||res.msg, {icon: 5});
                                }
                            },
                            error:(err)=>{
                                layer.msg("接口错误", {icon: 5});
                            }
                        });
                    }
                );
            }

            function updateSuccessful(){
                $.ajax({
                    url:"platform/updateSuccessful",
                    type:"GET",
                    dataType:"JSON",
                    success:(res)=>{
                        if(res.code == 1){
                            // layer.msg(res.message||res.msg, {icon: 1});
                        }
                        else{
                            // layer.msg(res.message||res.msg, {icon: 5});
                        }
                    },
                    error:(err)=>{
                        // layer.msg("接口错误", {icon: 5});
                    }
                });
            }

            $("#btn-copy-version").on("click",function(){
                let value = $(this).attr("data-text");
                if(!value) return layer.msg("复制版本号失败",{icon:2});
                
                let dom = document.createElement("input");
                dom.value = value;
                document.body.appendChild(dom);
                dom.select();
                document.execCommand("copy");
                document.body.removeChild(dom);
                layer.msg("复制版本号成功",{icon:1})
            })

            $("#btn-uploadWxapp").on("click",function(){
                Layer.confirm(
                    "确定上传微信小程序代码吗？",
                    {icon: 3, title: __('Warning'),  shadeClose: true, btn: [__('OK'), __('Cancel')]},
                    function (index) {
                        let loadIndex = layer.msg('上传中，请稍后', {
                            icon: 16,
                            shade: 0.01,
                            time:false
                        });

                        $.ajax({
                            url:"platform/uploadWxapp",
                            type:"GET",
                            dataType:"JSON",
                            success:(res)=>{
                                layer.close(loadIndex)
                                if(res.code == 1){
                                    layer.msg(res.message||res.msg, {icon: 1});
                                }
                                else{
                                    if(res.code == -2){
                                        initUploadWxapp(res.message||res.msg);
                                    }
                                    else{
                                        layer.msg(res.message||res.msg, {icon: 5});
                                    }
                                }
                            },
                            error:(err)=>{
                                layer.msg("接口错误", {icon: 5});
                            }
                        });
                    }
                );
            });
            
            $("#btn-upgrade").on("click",function(){
                Layer.confirm(
                        "请更新前请备份站点和数据库。",
                        {icon: 3, title: __('Warning'),  shadeClose: true, btn: [__('OK'), __('Cancel')]},
                        function (index) {
                            Layer.close(index);
                            $("#upgradem").show();
                            $.ajax({
                                url:"platform/update",
                                type:"GET",
                                dataType:"JSON",
                                success:(res)=>{
                                    down_success = true;
                                    setpdateProgress(100);
                                    setTimeout(()=>{
                                        $("#upgradem").hide();
                                        if(res.code == 1){
                                            let loadIndex = layer.msg('正在解压更新，请稍后。。。', {
                                                icon: 16,
                                                shade: 0.01,
                                                time:false
                                            });
                                            $.ajax({
                                                url:"platform/updatesql",
                                                type:"GET",
                                                dataType:"JSON",
                                                success:(res)=>{
                                                    layer.close(loadIndex)
                                                    console.log(res,555);
                                                    if(res.code == 1){
                                                        layer.msg(res.message, {icon: 1});
                                                        wipecache(function(){
                                                            setTimeout(function() {
                                                                parent.$(".main-sidebar").hide();
                                                                parent.location.reload();
                                                            }, 1000);
                                                        });
                                                        updateSuccessful();
                                                    }
                                                    else{
                                                        layer.msg(res.message, {icon: 5});
                                                    }
                                                    
                                                },
                                                error:(err)=>{
                                                    layer.close(loadIndex);
                                                    layer.msg("接口错误", {icon: 5});
                                                }
                                            });
                                        }
                                        else{
                                            layer.msg(res.message, {icon: 5});
                                        }
                                    },1000);
                                },
                                error:(err)=>{
                                    down_success = true;
                                    layer.msg(JSON.stringify(err), {icon: 5});
                                }
                            });
                            
                            setTimeout(()=>{
                                updateProgress(); 
                            },100);
                        }
                );
            });
             
                

            var table = $("#table");
            
            Table.api.events.operate['click .btn-jump'] = function(e, value, row, index){
                window.open("platform/index?id="+row.id);
            }

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                pagination:false,
                columns: [
                    [
                        // {checkbox: true},
                        {field: 'id', title: __('平台ID')},
                        {field: 'name', title: __('Name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'type', title: __('Type'), searchList: {"1":__('Type 1'),"2":__('Type 2'),"3":__('Type 3'),"4":__('Type 4')}, operate:'FIND_IN_SET', formatter: Table.api.formatter.label},
                        {field: 'status', title: __('Status'), searchList: {"1":__('Status 1'),"0":__('Status 0')}, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons:[
                                {
                                    name: 'jump',
                                    text: '进入后台',
                                    title: '进入后台',
                                    icon:"fa fa-send",
                                    hidden: function (row) {
                                        return false;
                                    },
                                    classname: 'btn btn-lg btn-success btn-jump mr',
                                    visibility: false,
                                    success: function (data, ret) {
                                        $(".btn-refresh").trigger("click");
                                    },
                                    error: function (err) {
                                        console.log(err);
                                    }
                                }
                            ]
                        }
                    ]
                ]
            });
 
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        xufei: function () {
            Controller.api.bindevent();
            
            $(".btn-buy").on("click",function(){
    
                let html = `
                <div style="display:flex;flex-direction: column;align-items: center;">
                    <img src="" style="width:200px;height:200px;" />
                    <div>扫码前往小程序购买</div>
                </div>`;
                
                layer.open({
                    title: '购买',
                    content: $("#buy_tpl").html()
                });   
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
