<div class="search-form">
    <div class="input-group mb-3" style="max-width: 600px;">
        <input type="text" class="form-control" id="prescription_no" placeholder="请输入处方编号" style="width: 200px;">
        <div class="input-group-append">
            <div class="form-check" style="margin-left: 10px;">
                <input type="checkbox" class="form-check-input" id="is_eseal" name="is_eseal">
                <label class="form-check-label" for="is_eseal">带电子印章</label>
            </div>
            <button class="btn btn-primary" type="button" id="search-btn" style="margin-left: 10px;">
                <i class="fa fa-search"></i> 搜索打印处方
            </button>
        </div>
    </div>
</div>

<div class="prescription-preview" id="prescription-container" style="display:none">
    <div class="text-center">
        <img id="prescription-image" class="img-fluid" style="max-width:30%">
        <div class="mt-3">
            <button class="btn btn-success" id="download-btn">
                <i class="fa fa-download"></i> 下载处方
            </button>

            <button class="btn btn-primary" id="print-btn">
                <i class="fa fa-print"></i> 打印处方
            </button>
        </div>
    </div>
</div>

<link href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/select2/4.0.13/css/select2.min.css" type="text/css" rel="stylesheet" />
<script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/select2/4.0.13/js/select2.min.js" type="application/javascript"></script>
<script>
Dcat.ready(function () {
    console.log('文档加载完成');

    // 初始化处方打印页面
    const prescriptionHandler = new class {
        constructor() {
            console.log('初始化处方处理器');
            this.init();
        }

        init() {
            console.log('开始绑定事件');
            // 绑定搜索事件
            $('#prescription_no').on('keypress', (e) => {
                if (e.which === 13) {
                    console.log('回车搜索触发');
                    this.search();
                }
            });

            $('#search-btn').on('click', () => {
                console.log('点击搜索按钮');
                this.search();
            });

            $('#download-btn').on('click', () => this.download());
            $('#print-btn').on('click', () => this.print());

            console.log('事件绑定完成');
            
            $('#editable-drug-list').on('click', 'select', function(){
                console.log("测试绑定selected事件")
            })
        }

        search() {
            console.log('进入搜索方法');
            let prescriptionNo = $('#prescription_no').val();
            let isEseal = $('#is_eseal').is(':checked') ? 1 : 0;
            if (!prescriptionNo) {
                Dcat.warning('请输入处方编号');
                return;
            }

            console.log('开始发送请求，处方编号:', prescriptionNo, '电子印章:', isEseal);
            Dcat.loading();

            $.ajax({
                url: "{{ admin_url('prescription-search') }}",
                type: 'POST',
                dataType: 'json',
                data: {
                    prescription_no: prescriptionNo,
                    is_eseal: isEseal,
                    _token: '{{ csrf_token() }}',
                    dosage_custom: this.getDosageData()
                },
                success: (response) => {
                    console.log('请求成功:', response);
                    Dcat.loading(false);

                    if (response.status) {
                        $('#prescription-image').attr('src', response.data.img_url + '?t=' + new Date().getTime());
                        $('#download-btn').data('url', response.data.img_url);
                        $('#prescription-container').show();

                        this.showEditableForm(response.data.drug_info,response.data.dosage_list);
                    } else {
                        Dcat.error(response.message || '获取处方失败');
                    }
                },
                error: (xhr) => {
                    console.error('请求失败:', xhr);
                    Dcat.loading(false);
                    Dcat.error('请求失败，请稍后重试');
                }
            });
        }

        // 下载处方
        download() {
            let url = $('#download-btn').data('url');
            if (!url) {
                Dcat.error('请先搜索处方');
                return;
            }
            window.open(url, '_blank');
        }

        // 打印处方
        print() {
            let url = $('#download-btn').data('url');
            if (!url) {
                Dcat.error('请先搜索处方');
                return;
            }

            // 打开新的打印页面
            let printUrl = '{{ admin_url('print') }}' + '?url=' + url;
            window.open(printUrl, '_blank');
        }

        // 新增：展示可编辑的药品信息表单
        showEditableForm(drugs, dosage_list) {
            console.log('drugs:', drugs); // 调试信息
            console.log('dosage_list:', dosage_list); // 调试信息

            // 仅在 drugs 有值时生成表单
            // 清空现有的药品信息表单
            $('#editable-drug-list').remove();

            let formHtml = '<div id="editable-drug-list" class="mt-3"  style="max-width:30%">';
            drugs.forEach(drug => {
                formHtml += `
                    <div class="drug-item input-group mb-2">
                        <input type="hidden" name="pharmacy_drug_id[]" value="${drug.pharmacy_drug_id}">
                        <label class="input-group-text">${drug.drug_name} || ${drug.spec} || ${drug.num}${drug.unit}</label>
                        <select class="form-control" name="dosage_id[]">
                            ${Array.isArray(dosage_list) && dosage_list.length > 0 ?
                                (() => {
                                    let options = '';
                                    dosage_list.forEach(dose => {
                                        options += `<option value="${dose.id}" ${drug.dosage_id === dose.id ? 'selected' : ''}>${dose.dosage_desc}</option>`; // 判断是否选中
                                    });
                                    return options;
                                })() :
                                '<option value="">无可用剂量</option>'}
                        </select>
                    </div>
                `;
            });
            formHtml += '</div>';
            // 将表单添加到搜索表单下方
            $('.search-form').after(formHtml);
            $(document).find('#editable-drug-list select').select2();
        }

        // 新增：获取剂量数据的方法
        getDosageData() {
            let dosageData = [];
            $('#editable-drug-list .drug-item').each(function() {
                let drugId = $(this).find('input[name="pharmacy_drug_id[]"]').val();
                let dosageId = $(this).find('select[name="dosage_id[]"]').val();
                dosageData.push({
                    pharmacy_drug_id: parseInt(drugId),
                    dosage_id: parseInt(dosageId)
                });
            });
            return JSON.stringify(dosageData);
        }
    }();  // 注意这里立即实例化类
});
</script>
