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

    var Controller = {
        index: function () {
            Table.api.init({
                extend: {
                    index_url: 'shopro/aityron/list',
                }
            });

            var table = $("#aityron-table");

            function renderText(value, width) {
                value = value === null || value === undefined || value === '' ? '-' : value;
                width = width || '160px';
                return '<div class="text-left" style="max-width:' + width + ';word-break:break-all;white-space:normal;">' + value + '</div>';
            }

            function renderImage(value) {
                if (!value) {
                    return '<span class="text-muted">-</span>';
                }

                return '<img src="' + value + '" data-url="' + value + '" class="img-preview" style="width:48px;height:48px;object-fit:cover;border-radius:6px;border:1px solid #eee;cursor:pointer;" title="点击查看原图">';
            }

            function renderResultMedia(value, row) {
                if (!value) {
                    return '<span class="text-muted">-</span>';
                }

                if (parseInt(row.ai_type, 10) === 1) {
                    // 视频：默认不预加载，点击后播放
                    return '<div style="position:relative;width:140px;height:90px;border-radius:6px;overflow:hidden;background:#000;">' +
                           '<video src="' + value + '" controls preload="none" style="width:100%;height:100%;" onclick="this.play()">' +
                           '</video>' +
                           '<div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);pointer-events:none;">' +
                           '<span style="color:#fff;font-size:12px;">点击播放</span>' +
                           '</div>' +
                           '</div>';
                }

                // AI结果图片：点击弹窗显示原图
                return '<img src="' + value + '" data-url="' + value + '" class="img-preview" style="width:48px;height:48px;object-fit:cover;border-radius:6px;border:1px solid #eee;cursor:pointer;" title="点击查看原图">';
            }

            function renderStatus(value, row) {
                if (row.ai_status == 1) {
                    return '<span class="label label-success">' + value + '</span>';
                } else if (row.ai_status == 0) {
                    return '<span class="label label-warning">' + value + '</span>';
                } else {
                    return '<span class="label label-danger">' + value + '</span>';
                }
            }

            // 初始化表格参数
            var tableOptions = {
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                sortOrder: 'desc',
                search: false,
                commonSearch: true,
                toolbar: '#toolbar',
                escape: false,
                showColumns: true,
                showToggle: true,
                showRefresh: true,
                pagination: true,
                pageSize: 10,
                queryParams: function (params) {
                    return {
                        page: params.pageNumber || (params.limit ? Math.floor((params.offset || 0) / params.limit) + 1 : 1),
                        list_rows: params.pageSize || params.limit || 10,
                        sort: params.sort || params.sortName || 'id',
                        order: params.order || params.sortOrder || 'desc',
                        filter: params.filter || JSON.stringify({}),
                        search: params.search || params.searchText || ''
                    };
                },
                responseHandler: function (res) {
                    if (res && res.code === 1 && res.data) {
                        return {
                            total: res.data.total || 0,
                            rows: res.data.rows || []
                        };
                    }

                    return {
                        total: 0,
                        rows: []
                    };
                },
                columns: [[
                    {
                        field: 'id',
                        title: __('ID')
                    },
                    {
                        field: 'user_id',
                        title: __('用户ID')
                    },
                    {
                        field: 'ai_type_text',
                        title: __('类型'),
                        formatter: function (value) {
                            return value === '视频'
                                ? '<span class="label label-info">视频</span>'
                                : '<span class="label label-primary">图片</span>';
                        }
                    },
                    {
                        field: 'user_info',
                        title: __('用户'),
                        formatter: function (value) {
                            if (value && value.nickname) {
                                return '<div class="text-left">' + 
                                    (value.avatar ? '<img src="' + Fast.api.cdnurl(value.avatar) + '" style="width:30px;height:30px;border-radius:50%;vertical-align:middle;margin-right:5px;">' : '') +
                                    '<span style="vertical-align:middle;">' + value.nickname + (value.mobile ? ' (' + value.mobile + ')' : '') + '</span>' +
                                    '</div>';
                            }
                            return '<span class="text-muted">未登录</span>';
                        }
                    },
                    {
                        field: 'goods_id',
                        title: __('商品ID')
                    },
                    {
                        field: 'goods_title',
                        title: __('商品名称'),
                        formatter: function (value) {
                            return renderText(value, '180px');
                        }
                    },
                    // {
                    //     field: 'goods_subtitle',
                    //     title: __('商品副标题'),
                    //     formatter: function (value) {
                    //         return renderText(value, '180px');
                    //     }
                    // },
                    {
                        field: 'goods_image',
                        title: __('商品图片'),
                        formatter: function (value) {
                            return renderImage(value);
                        }
                    },
                    {
                        field: 'image_3d',
                        title: __('3D图片'),
                        formatter: function (value) {
                            return renderImage(value);
                        }
                    },
                    {
                        field: 'person_image',
                        title: __('人物图片'),
                        formatter: function (value) {
                            return renderImage(value);
                        }
                    },
                    {
                        field: 'ai_url',
                        title: __('AI结果'),
                        formatter: function (value, row) {
                            return renderResultMedia(value, row);
                        }
                    },
                    {
                        field: 'ai_status_text',
                        title: __('试戴状态'),
                        formatter: function (value, row) {
                            return renderStatus(value, row);
                        }
                    },
                    {
                        field: 'ai_err_msg',
                        title: __('错误信息'),
                        formatter: function (value) {
                            return renderText(value, '220px');
                        }
                    },
                    // {
                    //     field: 'ai_task_id',
                    //     title: __('AI任务ID'),
                    //     formatter: function (value) {
                    //         return renderText(value, '160px');
                    //     }
                    // },
                    {
                        field: 'createtime_text',
                        title: __('创建时间'),
                        formatter: function (value) {
                            return renderText(value, '140px');
                        }
                    },
                    {
                        field: 'updatetime_text',
                        title: __('更新时间'),
                        formatter: function (value) {
                            return renderText(value, '140px');
                        }
                    },
                    // {
                    //     field: 'deletetime_text',
                    //     title: __('删除时间'),
                    //     formatter: function (value) {
                    //         return renderText(value, '140px');
                    //     }
                    // },
                    // {
                    //     field: 'operate',
                    //     title: __('操作'),
                    //     events: Table.api.events.operate,
                    //     formatter: function (value, row, index) {
                    //         var buttons = [];
                    //         buttons.push('<a href="javascript:;" class="btn btn-xs btn-info btn-detail" data-id="' + row.id + '" title="查看详情"><i class="fa fa-eye"></i>详情</a>');
                    //         return buttons.join(' ');
                    //     }
                    // }
                ]]
            };

            // 初始化表格
            table.bootstrapTable(tableOptions);
            Table.api.bindevent(table);

            // 点击图片弹窗显示大图
            $(document).on('click', '.img-preview', function () {
                var url = $(this).data('url');
                if (url) {
                    Layer.open({
                        type: 1,
                        title: false,
                        closeBtn: 1,
                        shadeClose: true,
                        area: ['auto', 'auto'],
                        content: '<img src="' + url + '" style="max-width:90vw;max-height:90vh;display:block;" />'
                    });
                }
            });

            // 时间范围选择器
            if ($.fn.daterangepicker) {
                $('#createtime_range').daterangepicker({
                    autoUpdateInput: false,
                    locale: {
                        format: 'YYYY-MM-DD'
                    }
                });
                
                $('#createtime_range').on('apply.daterangepicker', function(ev, picker) {
                    $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
                });
            }

            // 搜索按钮
            $('.btn-search').on('click', function () {
                var filter = {};
                
                if ($('#user_id').val()) {
                    filter.user_id = $('#user_id').val();
                }
                if ($('#goods_id').val()) {
                    filter.goods_id = $('#goods_id').val();
                }
                if ($('#goods_title').val()) {
                    filter.goods_title = $('#goods_title').val();
                }
                if ($('#ai_status').val()) {
                    filter.ai_status = $('#ai_status').val();
                }
                if ($('#createtime_range').val()) {
                    filter.createtime_range = $('#createtime_range').val();
                }
                
                table.bootstrapTable('refresh', {
                    query: {
                        filter: JSON.stringify(filter)
                    }
                });
            });

            // 重置按钮
            $('.btn-reset').on('click', function () {
                $('#user_id').val('');
                $('#goods_id').val('');
                $('#goods_title').val('');
                $('#ai_status').val('');
                $('#createtime_range').val('');
                
                table.bootstrapTable('refresh', {
                    query: {
                        filter: JSON.stringify({})
                    }
                });
            });

            // 详情按钮事件
            $(document).on('click', '.btn-detail', function () {
                var id = $(this).data('id');
                Fast.api.open('shopro/aityron/detail?id=' + id, '查看详情', {
                    area: ['80%', '80%'],
                    callback: function (data) {
                        table.bootstrapTable('refresh');
                    }
                });
            });

            Controller.api.bindevent();
        },

        detail: function () {
            var id = Fast.api.query('id');
            
            Fast.api.ajax({
                url: 'shopro/aityron/detail',
                type: 'GET',
                data: { id: id }
            }, function (ret, res) {
                if (res.code === 1 && res.data) {
                    var data = res.data;
                    
                    // 渲染详情信息
                    var html = '<div class="panel panel-default">';
                    html += '<div class="panel-body">';
                    
                    // 基本信息
                    html += '<table class="table table-striped">';
                    html += '<tr><th width="150">ID</th><td>' + data.id + '</td></tr>';
                    html += '<tr><th>类型</th><td>' + (data.ai_type == 1 ? '<span class="label label-info">视频</span>' : '<span class="label label-primary">图片</span>') + '</td></tr>';
                    html += '<tr><th>试戴状态</th><td>' + data.ai_status_text + '</td></tr>';
                    
                    // 用户信息
                    if (data.user_info) {
                        html += '<tr><th>用户</th><td>';
                        if (data.user_info.avatar) {
                            html += '<img src="' + Fast.api.cdnurl(data.user_info.avatar) + '" style="width:40px;height:40px;border-radius:50%;vertical-align:middle;margin-right:10px;">';
                        }
                        html += '<span style="vertical-align:middle;">' + (data.user_info.nickname || '未知') + '</span>';
                        if (data.user_info.mobile) {
                            html += ' <span class="text-muted">(' + data.user_info.mobile + ')</span>';
                        }
                        html += '</td></tr>';
                    }
                    
                    // 商品信息
                    html += '<tr><th>商品标题</th><td>' + (data.goods_title || '') + '</td></tr>';
                    html += '<tr><th>商品副标题</th><td>' + (data.goods_subtitle || '') + '</td></tr>';
                    
                    // 图片信息
                    if (data.ai_type == 0) {
                        html += '<tr><th>人物图片</th><td><img src="' + data.person_image + '" data-url="' + data.person_image + '" class="img-preview" style="max-width:300px;max-height:300px;cursor:pointer;" title="点击查看原图"></td></tr>';
                        html += '<tr><th>商品图片</th><td><img src="' + data.goods_image + '" data-url="' + data.goods_image + '" class="img-preview" style="max-width:300px;max-height:300px;cursor:pointer;" title="点击查看原图"></td></tr>';
                        html += '<tr><th>3D图片</th><td><img src="' + data.image_3d + '" data-url="' + data.image_3d + '" class="img-preview" style="max-width:300px;max-height:300px;cursor:pointer;" title="点击查看原图"></td></tr>';
                        if (data.ai_url) {
                            html += '<tr><th>AI 生成结果</th><td><img src="' + data.ai_url + '" data-url="' + data.ai_url + '" class="img-preview" style="max-width:300px;max-height:300px;cursor:pointer;" title="点击查看原图"></td></tr>';
                        }
                    } else {
                        html += '<tr><th>人物图片</th><td><img src="' + data.person_image + '" data-url="' + data.person_image + '" class="img-preview" style="max-width:300px;max-height:300px;cursor:pointer;" title="点击查看原图"></td></tr>';
                        html += '<tr><th>商品图片</th><td><img src="' + data.goods_image + '" data-url="' + data.goods_image + '" class="img-preview" style="max-width:300px;max-height:300px;cursor:pointer;" title="点击查看原图"></td></tr>';
                        html += '<tr><th>3D图片</th><td><img src="' + data.image_3d + '" data-url="' + data.image_3d + '" class="img-preview" style="max-width:300px;max-height:300px;cursor:pointer;" title="点击查看原图"></td></tr>';
                        if (data.ai_url) {
                            html += '<tr><th>AI 生成视频</th><td><div style="position:relative;max-width:600px;max-height:400px;border-radius:6px;overflow:hidden;background:#000;">' +
                                    '<video src="' + data.ai_url + '" controls preload="none" style="width:100%;height:100%;" onclick="this.play()">' +
                                    '</video>' +
                                    '<div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);pointer-events:none;">' +
                                    '<span style="color:#fff;font-size:14px;">点击播放</span>' +
                                    '</div>' +
                                    '</div></td></tr>';
                        }
                    }
                    
                    // 错误信息
                    if (data.ai_err_msg) {
                        html += '<tr><th>错误信息</th><td><span class="text-danger">' + data.ai_err_msg + '</span></td></tr>';
                    }
                    
                    // 任务 ID
                    if (data.ai_task_id) {
                        html += '<tr><th>AI 任务 ID</th><td>' + data.ai_task_id + '</td></tr>';
                    }
                    
                    // 时间信息
                    html += '<tr><th>创建时间</th><td>' + data.createtime_text + '</td></tr>';
                    if (data.updatetime_text) {
                        html += '<tr><th>更新时间</th><td>' + data.updatetime_text + '</td></tr>';
                    }
                    
                    html += '</table>';
                    html += '</div>';
                    html += '</div>';
                    
                    $('.panel-body').html(html);
                    
                    // 详情页点击图片弹窗显示大图
                    $(document).on('click', '.img-preview', function () {
                        var url = $(this).data('url');
                        if (url) {
                            Layer.open({
                                type: 1,
                                title: false,
                                closeBtn: 1,
                                shadeClose: true,
                                area: ['auto', 'auto'],
                                content: '<img src="' + url + '" style="max-width:90vw;max-height:90vh;display:block;" />'
                            });
                        }
                    });
                }
                return false;
            });
            
            Controller.api.bindevent();
        },

        api: {
            bindevent: function () {
                // 绑定事件
            }
        }
    };

    return Controller;
});
