define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'shopro/agent/agent/index' + location.search,
                    // add_url: 'shopro/agent/agent/add',
                    // edit_url: 'shopro/agent/agent/edit',
                    // del_url: 'shopro/agent/agent/del',
                    multi_url: 'shopro/agent/agent/multi',
                    import_url: 'shopro/agent/agent/import',
                    table: 'shopro_agent',
                }
            });

            var table = $("#table");

            // 代理商列表页-初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'user_id', title: __('User_id')},
                        // {field: 'province_name', title: __('Province_name'), operate: 'LIKE'},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('Status normal'),"freeze":__('Status freeze'),"forbidden":__('Status forbidden')}, formatter: Table.api.formatter.status},
                        {field: 'real_name', title: __('Real_name'), operate: 'LIKE'},
                        {field: 'id_card', title: __('Id_card'), operate: 'LIKE'},
                        {field: 'commission_rate', title: __('Commission_rate'), operate:'BETWEEN'},
                        {field: 'total_commission', title: __('Total_commission'), operate:'BETWEEN'},
                        {field: 'apply_id', title: __('Apply_id')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, buttons: [
                            {
                                name: 'detail',
                                text: __('Detail'),
                                title: __('Detail'),
                                icon: 'fa fa-list',
                                classname: 'btn btn-info btn-xs btn-detail'
                            },
                            {
                                name: 'edit',
                                text: __('Edit'),
                                title: __('Edit'),
                                icon: 'fa fa-pencil',
                                classname: 'btn btn-primary btn-xs btn-editone',
                                url: 'shopro/agent/agent/edit'
                            },
                            {
                                name: 'del',
                                text: __('Delete'),
                                title: __('Delete'),
                                icon: 'fa fa-trash',
                                classname: 'btn btn-danger btn-xs btn-delone',
                                url: 'shopro/agent/agent/del'
                            }
                        ], formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            // 弹窗查看详情
            $(document).on('click', '.btn-detail', function () {
                // formatter.operate 按钮只有 data-row-index，没有 data-id
                // 需要通过 row-index 从表格数据中获取行记录的 pk(id)
                var rowIndex = $(this).data('row-index');
                var rowData = Table.api.getrowbyindex(table, rowIndex);
                var id = rowData ? rowData.id : Table.api.selectedids(table);
                console.log('---id:'+id);
                if (!id) return;
                Fast.api.open('shopro/agent/agent/detail?ids=' + id, __('Detail'), {
                    area: ['90%', '90%'],
                    callback: function () {
                        if (table.length && table.bootstrapTable) {
                            table.bootstrapTable('refresh');
                        }
                    }
                });
            });

            // 批量修改佣金比例按钮
            $(document).on('click', '.btn-commission-rate', function () {
                var ids = Table.api.selectedids(table);
                if (ids.length === 0) {
                    Toastr.error(lang('Please select at least one record'));
                    return;
                }
                Layer.open({
                    type: 1,
                    title: __('Batch_commission_rate'),
                    area: ['420px', '220px'],
                    content: '<div style="padding:20px 25px;">' +
                        '<div class="form-group">' +
                        '<label class="control-label">' + __('Commission_rate') + '</label>' +
                        '<input id="c-batch-rate" class="form-control" type="number" step="0.01" min="0" max="100" value="" placeholder="' + __('Please_input_commission_rate') + '">' +
                        '</div>' +
                        '</div>',
                    btn: [__('Ok'), __('Cancel')],
                    yes: function (index) {
                        var rate = $('#c-batch-rate').val();
                        if (rate === '' || isNaN(rate)) {
                            Toastr.error('请输入有效的数字');
                            return;
                        }
                        rate = parseFloat(rate);
                        if (rate < 0 || rate > 100) {
                            Toastr.error('佣金比例应在0-100之间');
                            return;
                        }
                        rate = Math.round(rate * 100) / 100;

                        Fast.api.ajax({
                            url: 'shopro/agent/agent/batch_commission_rate',
                            data: {
                                ids: ids.join(','),
                                commission_rate: rate
                            },
                            success: function () {
                                Layer.close(index);
                                table.bootstrapTable('refresh');
                            },
                            error: function () {
                                Toastr.error('批量修改佣金比例失败');
                            }
                        });
                    }
                });
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            var $table = $("#commission-table");
            if (!$table.length) return;

            var agentId = $table.data('agent-id');
            var statusList = $table.data('status-list') || {};
            var orderStatusList = $table.data('order-status-list') || {};
            var detailUrl = 'shopro/agent/agent/detail?ids=' + agentId;

            // 初始化 selectpicker
            require(['bootstrap-select'], function () {
                $('#commission-search-form .selectpicker').selectpicker();
            });

            // 初始化日期范围选择器
            require(['bootstrap-daterangepicker'], function () {
                $('#commission-toolbar .datetimerange').each(function () {
                    var $input = $(this);
                    var begin = $input.data('begin') || ($input.attr('name') + '_start');
                    var end = $input.data('end') || ($input.attr('name') + '_end');
                    // 创建隐藏的起止字段
                    if ($input.siblings('[name="' + begin + '"]').length === 0) {
                        $input.after('<input type="hidden" name="' + begin + '" value="">');
                    }
                    if ($input.siblings('[name="' + end + '"]').length === 0) {
                        $input.after('<input type="hidden" name="' + end + '" value="">');
                    }
                    $input.daterangepicker({
                        autoUpdateInput: false,
                        locale: {
                            format: 'YYYY-MM-DD',
                            applyLabel: '确定',
                            cancelLabel: '取消',
                            daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                            monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                        }
                    });
                    $input.on('apply.daterangepicker', function (ev, picker) {
                        $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
                        $input.siblings('[name="' + begin + '"]').val(picker.startDate.format('YYYY-MM-DD'));
                        $input.siblings('[name="' + end + '"]').val(picker.endDate.format('YYYY-MM-DD'));
                    });
                    $input.on('cancel.daterangepicker', function () {
                        $(this).val('');
                        $input.siblings('[name="' + begin + '"]').val('');
                        $input.siblings('[name="' + end + '"]').val('');
                    });
                });
            });

            // 构建查询参数
            var buildQueryParams = function (params) {
                var query = {
                    offset: params.offset || 0,
                    limit: params.limit || 10,
                    sort: params.sort || 'id',
                    order: params.order || 'desc'
                };
                // 处理普通表单字段
                $('#commission-search-form').find('input[type="text"],input[type="hidden"]').each(function () {
                    var name = $(this).attr('name');
                    var val = $(this).val();
                    if (val !== '' && name) {
                        query[name] = val;
                    }
                });
                // 处理多选下拉框：收集所有选中值，用逗号连接
                var orderStatusSelect = $('#commission-search-form select[name="order_status"]');
                if (orderStatusSelect.length && orderStatusSelect.val() && orderStatusSelect.val().length > 0) {
                    query.order_status = orderStatusSelect.val().join(',');
                }
                return query;
            };

            //代理商-佣金流水
            $table.bootstrapTable({
                url: detailUrl,
                toolbar: '#commission-toolbar',
                sidePagination: 'server',
                pagination: true,
                pageSize: 10,
                pageList: [10, 20, 50, 100],
                showRefresh: true,
                showToggle: false,
                showColumns: true,
                showExport: true,
                exportDataType: 'selected',
                exportTypes: ['excel'],
                exportOptions: {
                    fileName: '佣金流水_' + new Date().toISOString().slice(0, 10),
                    ignoreColumn: [0]
                },
                method: 'get',
                clickToSelect: true,
                singleSelect: false,
                queryParams: buildQueryParams,
                responseHandler: function (res) {
                    if (!res || res.code !== undefined && res.code == 0) {
                        Toastr.error((res && res.msg) || '佣金流水加载失败');
                        return { total: 0, rows: [] };
                    }
                    var data = res.data || res;
                    if (!data || (!data.total && !data.rows)) {
                        data = data || {};
                    }
                    return {
                        total: data.total || 0,
                        rows: data.rows || []
                    };
                },
                onLoadError: function (status, res) {
                    Toastr.error('佣金流水加载失败，请稍后重试');
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), width: 60, align: 'center', sortable: true},
                        {field: 'status', title: __('Commission_status'), width: 80, align: 'center',
                            formatter: function (value) {
                                var text = statusList[value] || '-';
                                var cls = '';
                                switch (parseInt(value)) {
                                    case 0:  cls = 'btn-warning'; break;  // 待结算
                                    case 1:  cls = 'btn-success'; break;  // 已结算
                                    case -1: cls = 'btn-default'; break;  // 已取消
                                    case -2: cls = 'btn-danger';  break;  // 已退款
                                    default: cls = 'btn-default'; break;
                                }
                                return '<button class="btn btn-xs ' + cls + '" style="pointer-events:none;">' + text + '</button>';
                            }
                        },
                        {field: 'order_id', title: __('Order_id'), width: 70, align: 'center'},
                        {field: 'order_sn', title: __('Order_sn'), width: 160, align: 'center'},
                        {field: 'order_createtime', title: __('Order_createtime'), width: 150, align: 'center', formatter: Table.api.formatter.datetime},
                        {field: 'commission_rate_snapshot', title: __('Commission_rate_snapshot'), width: 120, align: 'center',
                            formatter: function (value) {
                                return value !== null && value !== undefined ? value + '%' : '-';
                            }
                        },
                        {field: 'commission_amount', title: __('Commission_amount'), width: 100, align: 'center',
                            formatter: function (value) {
                                var price = value ? '¥' + parseFloat(value).toFixed(2) : '-';
                                 return '<span style="color:#f39c12;">' + price + '</span>';
                            }
                        },
                        // {field: 'reward_amount', title: __('Reward_amount'), width: 100, align: 'center',
                        //     formatter: function (value, row) {
                        //         var price = row.goods_pay_price || 0;
                        //         return '<span style="color:#f39c12;">¥' + (price * 0.05).toFixed(2) + '</span>';
                        //     }
                        // },
                        {field: 'order_status', title: __('Order_status'), width: 90, align: 'center',
                            formatter: function (value) { return orderStatusList[value] || value || '-'; }
                        },
                        {field: 'agent_id', title: __('Agent_id'), width: 120, align: 'center'},
                        {field: 'agent_user_id', title: __('Agent_user_id'), width: 120, align: 'center'},
                        {field: 'buyer_user_id', title: __('Buyer_user_id'), width: 120, align: 'center'},
                        {field: 'receive_province_name', title: __('Receive_province_name'), width: 120, align: 'center',
                            formatter: function (value) { return value || '-'; }
                        },
                        // {field: 'goods_title', title: __('Goods_title'), width: 150, align: 'left',
                        //     formatter: function (value) { return value || '-'; }
                        // },
                        // {field: 'goods_pay_price', title: __('Goods_pay_price'), width: 100, align: 'center',
                        //     formatter: function (value) {
                        //         return value ? '¥' + parseFloat(value).toFixed(2) : '-';
                        //     }
                        // },
                        {field: 'aftersale_order_sn', title: __('Aftersale_order_sn'), width: 160, align: 'center',
                            formatter: function (value) { return value || '-'; }
                        },
                        {field: 'order_confirm_time', title: __('Order_confirm_time'), width: 150, align: 'center', formatter: Table.api.formatter.datetime},
                        {field: 'createtime', title: __('Createtime'), width: 150, align: 'center', formatter: Table.api.formatter.datetime}
                    ]
                ]
            });

            Table.api.bindevent($table);

            // 搜索按钮
            $(document).on('click', '.btn-commission-search', function (e) {
                e.preventDefault();
                $table.bootstrapTable('refresh');
            });

            // 重置按钮
            $(document).on('click', '.btn-commission-reset', function (e) {
                e.preventDefault();
                $('#commission-search-form')[0].reset();
                // 重置 selectpicker
                $('#commission-search-form .selectpicker').selectpicker('deselectAll');
                // 清空日期范围隐藏字段
                $('#commission-search-form .datetimerange').val('').trigger('cancel.daterangepicker');
                $table.bootstrapTable('refresh');
            });

            // 勾选/取消勾选后控制按钮状态
            $table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function () {
                var selectedIds = $.map($table.bootstrapTable('getSelections'), function (row) {
                    return row.id;
                });
                var hasSelection = selectedIds.length > 0;
                $('#btn-batch-export, #btn-batch-status').prop('disabled', !hasSelection);
            });

            // 批量导出（服务端导出）
            $(document).on('click', '#btn-batch-export', function () {
                var selectedIds = $.map($table.bootstrapTable('getSelections'), function (row) {
                    return row.id;
                });
                if (selectedIds.length === 0) {
                    Toastr.error('请先选择要导出的记录');
                    return;
                }
                var entry = location.pathname.split('/')[1];
                var url = location.origin + '/' + entry + '/shopro/agent/agent/export_commission_log?ids=' + selectedIds.join(',');
                window.open(url);
            });

            // 批量修改结算状态
            $(document).on('click', '#btn-batch-status', function () {
                var selectedIds = $.map($table.bootstrapTable('getSelections'), function (row) {
                    return row.id;
                });
                if (selectedIds.length === 0) {
                    Toastr.error('请先选择要修改的记录');
                    return;
                }
                var optionsHtml = '';
                $.each(statusList, function (key, val) {
                    optionsHtml += '<option value="' + key + '">' + val + '</option>';
                });
                Layer.open({
                    type: 1,
                    title: '批量修改结算状态',
                    area: ['420px', '200px'],
                    content: '<div style="padding:20px 25px;">' +
                        '<div class="form-group">' +
                        '<label class="control-label">结算状态</label>' +
                        '<select id="c-batch-status" class="form-control">' + optionsHtml + '</select>' +
                        '</div>' +
                        '</div>',
                    btn: ['确定', '取消'],
                    yes: function (index) {
                        var status = $('#c-batch-status').val();
                        Fast.api.ajax({
                            url: 'shopro/agent/agent/batch_commission_status',
                            data: {
                                ids: selectedIds.join(','),
                                status: status
                            },
                            success: function () {
                                Layer.close(index);
                                $table.bootstrapTable('refresh');
                            },
                            error: function () {
                                Toastr.error('批量修改结算状态失败');
                            }
                        });
                    }
                });
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
