/* Js for , Version=1777282873 */
 v.lang = {"confirmDelete":"\u60a8\u786e\u5b9a\u8981\u6267\u884c\u5220\u9664\u64cd\u4f5c\u5417\uff1f","deleteing":"\u5220\u9664\u4e2d","doing":"\u5904\u7406\u4e2d","loading":"\u52a0\u8f7d\u4e2d","updating":"\u66f4\u65b0\u4e2d...","timeout":"\u7f51\u7edc\u8d85\u65f6,\u8bf7\u91cd\u8bd5","errorThrown":"<h4>\u6267\u884c\u51fa\u9519\uff1a<\/h4>","continueShopping":"\u7ee7\u7eed\u8d2d\u7269","required":"\u5fc5\u586b","back":"\u8fd4\u56de","continue":"\u7ee7\u7eed","importTip":"\u53ea\u5bfc\u5165\u4e3b\u9898\u7684\u98ce\u683c\u548c\u6837\u5f0f","fullImportTip":"\u5c06\u4f1a\u5bfc\u5165\u6d4b\u8bd5\u6570\u636e\u4ee5\u53ca\u66ff\u6362\u7ad9\u70b9\u6587\u7ae0\u3001\u4ea7\u54c1\u7b49\u6570\u636e"};;v.agreement = "close";;
$().ready(function()
{
    $('a.btn-oauth').each(function()
    {
        fingerprint = getFingerprint();
        $(this).attr('href', $(this).attr('href').replace('fingerprintval', fingerprint) )
    })
});
;
$(function() {
    let pwd1 = $('#password1');
    let pwd2 = $('#password2');
    let account = $('#account');
    
    // 获取当前申请人类型
    function getApplicantType() {
        return $('input[name="eva_applicant_type"]:checked').val();
    }
    
    // 获取字段值
    function getFieldValue(fieldName) {
        let $element = $(`[name="${fieldName}"]`);
        if ($element.length === 0) return '';
        
        if ($element.is(':radio')) {
            return $element.filter(':checked').val() || '';
        }
        if ($element.is(':checkbox')) {
            let checkedValues = [];
            $element.filter(':checked').each(function() {
                checkedValues.push($(this).val());
            });
            return checkedValues.length > 0 ? checkedValues.join(',') : '';
        }
        return $element.val() || '';
    }
    
    // 清除所有错误
    function clearAllErrors() {
        $('.form-group').removeClass('has-error');
        $('.field-error-tip').remove();
        $('.help-block.text-danger').remove();
    }
    
    // 滚动到元素
    function scrollToElement($element) {
        if ($element.length) {
            $('html, body').animate({
                scrollTop: $element.offset().top - 100
            }, 300);
        }
    }
    
    // 高亮显示错误字段（红色边框+下方文字）
    function highlightError(fieldName, label, isRadioOrCheckbox) {
        let $element = $(`[name="${fieldName}"]`);
        let $formGroup = $element.closest('.form-group');
        
        $formGroup.addClass('has-error');
        
        if (isRadioOrCheckbox || $element.is(':radio') || $element.is(':checkbox')) {
            $formGroup.find('.field-error-tip').remove();
            let $errorTip = $('<span class="field-error-tip text-danger" style="display:block; margin-top:5px; font-size:12px;">请选择' + label + '</span>');
            $formGroup.find('.col-sm-10').append($errorTip);
        } else {
            if ($formGroup.find('.help-block.text-danger').length === 0) {
                let $parent = $formGroup.find('.col-sm-10');
                if ($parent.length) {
                    let $errorTip = $('<span class="help-block text-danger" style="font-size:12px;">' + label + '不能为空</span>');
                    $parent.append($errorTip);
                }
            }
        }
    }
    
    // 按顺序验证所有评估字段
    function validateAssessmentFields() {
        let applicantType = getApplicantType();
        
        // 1. 验证申请人类型
        if (!applicantType) {
            highlightError('eva_applicant_type', '申请人类型', true);
            scrollToElement($('input[name="eva_applicant_type"]').first());
            return false;
        }
        
        // 2. 根据申请人类型验证对应字段
        if (applicantType === 'natural') {
            // 验证自然人字段
            if (!$('#eva_patient_name').val().trim()) {
                highlightError('eva_patient_name', '患者姓名', false);
                scrollToElement($('#eva_patient_name'));
                return false;
            }
            if (!$('input[name="eva_patient_gender"]:checked').val()) {
                highlightError('eva_patient_gender', '性别', true);
                scrollToElement($('input[name="eva_patient_gender"]').first());
                return false;
            }
            if (!$('#eva_patient_nation').val().trim()) {
                highlightError('eva_patient_nation', '民族', false);
                scrollToElement($('#eva_patient_nation'));
                return false;
            }
            if (!$('#eva_patient_birthday').val().trim()) {
                highlightError('eva_patient_birthday', '出生年月', false);
                scrollToElement($('#eva_patient_birthday'));
                return false;
            }
            if (!$('#eva_patient_idnumber').val().trim()) {
                highlightError('eva_patient_idnumber', '身份证号', false);
                scrollToElement($('#eva_patient_idnumber'));
                return false;
            }
            if (!$('#eva_patient_phone').val().trim()) {
                highlightError('eva_patient_phone', '联系方式', false);
                scrollToElement($('#eva_patient_phone'));
                return false;
            }
            if (!$('#eva_patient_email').val().trim()) {
                highlightError('eva_patient_email', '邮箱', false);
                scrollToElement($('#eva_patient_email'));
                return false;
            }
            if (!$('#eva_patient_address').val().trim()) {
                highlightError('eva_patient_address', '住址', false);
                scrollToElement($('#eva_patient_address'));
                return false;
            }
            if (!$('#eva_agent_name').val().trim()) {
                highlightError('eva_agent_name', '委托评估人姓名', false);
                scrollToElement($('#eva_agent_name'));
                return false;
            }
            if (!$('#eva_agent_relation').val().trim()) {
                highlightError('eva_agent_relation', '与患者关系', false);
                scrollToElement($('#eva_agent_relation'));
                return false;
            }
            if (!$('#eva_agent_phone').val().trim()) {
                highlightError('eva_agent_phone', '委托评估人联系方式', false);
                scrollToElement($('#eva_agent_phone'));
                return false;
            }
            
            // 诉讼情况
            let isLawsuit = $('input[name="eva_is_lawsuit"]:checked').val();
            if (!isLawsuit) {
                highlightError('eva_is_lawsuit', '是否已起诉', true);
                scrollToElement($('input[name="eva_is_lawsuit"]').first());
                return false;
            }
            if (isLawsuit === 'yes') {
                if (!$('#eva_court_name').val().trim()) {
                    highlightError('eva_court_name', '相关法院', false);
                    scrollToElement($('#eva_court_name'));
                    return false;
                }
            }
            
            let needMediation = $('input[name="eva_need_mediation"]:checked').val();
            if (!needMediation) {
                highlightError('eva_need_mediation', '是否需要协助调解', true);
                scrollToElement($('input[name="eva_need_mediation"]').first());
                return false;
            }
        } 
        else if (applicantType === 'unit') {
            // 验证单位字段
            if (!$('#eva_unit_name').val().trim()) {
                highlightError('eva_unit_name', '单位名称', false);
                scrollToElement($('#eva_unit_name'));
                return false;
            }
            if (!$('#eva_unit_phone').val().trim()) {
                highlightError('eva_unit_phone', '联系方式', false);
                scrollToElement($('#eva_unit_phone'));
                return false;
            }
            if (!$('#eva_legal_representative').val().trim()) {
                highlightError('eva_legal_representative', '法定代表人', false);
                scrollToElement($('#eva_legal_representative'));
                return false;
            }
            if (!$('#eva_social_credit_code').val().trim()) {
                highlightError('eva_social_credit_code', '统一社会信用代码', false);
                scrollToElement($('#eva_social_credit_code'));
                return false;
            }
            if (!$('#eva_unit_address').val().trim()) {
                highlightError('eva_unit_address', '地址', false);
                scrollToElement($('#eva_unit_address'));
                return false;
            }
            if (!$('#eva_unit_email').val().trim()) {
                highlightError('eva_unit_email', '邮箱', false);
                scrollToElement($('#eva_unit_email'));
                return false;
            }
            if (!$('#eva_unit_patient_name').val().trim()) {
                highlightError('eva_unit_patient_name', '患者姓名', false);
                scrollToElement($('#eva_unit_patient_name'));
                return false;
            }
            if (!$('input[name="eva_unit_patient_gender"]:checked').val()) {
                highlightError('eva_unit_patient_gender', '性别', true);
                scrollToElement($('input[name="eva_unit_patient_gender"]').first());
                return false;
            }
            if (!$('#eva_unit_patient_nation').val().trim()) {
                highlightError('eva_unit_patient_nation', '民族', false);
                scrollToElement($('#eva_unit_patient_nation'));
                return false;
            }
            if (!$('#eva_unit_patient_birthday').val().trim()) {
                highlightError('eva_unit_patient_birthday', '出生年月', false);
                scrollToElement($('#eva_unit_patient_birthday'));
                return false;
            }
            if (!$('#eva_unit_patient_idnumber').val().trim()) {
                highlightError('eva_unit_patient_idnumber', '身份证号', false);
                scrollToElement($('#eva_unit_patient_idnumber'));
                return false;
            }
            if (!$('#eva_unit_patient_phone').val().trim()) {
                highlightError('eva_unit_patient_phone', '联系方式', false);
                scrollToElement($('#eva_unit_patient_phone'));
                return false;
            }
            if (!$('#eva_unit_patient_address').val().trim()) {
                highlightError('eva_unit_patient_address', '住址', false);
                scrollToElement($('#eva_unit_patient_address'));
                return false;
            }
        }
        
        // 3. 验证评估事项（多选）
        let evaluationItems = $('input[name="eva_evaluation_items[]"]:checked');
        if (evaluationItems.length === 0) {
            let $formGroup = $('#evaluation_items').closest('.form-group');
            $formGroup.addClass('has-error');
            $formGroup.find('.field-error-tip').remove();
            let $errorTip = $('<span class="field-error-tip text-danger" style="display:block; margin-top:5px; font-size:12px;">请选择评估事项</span>');
            $formGroup.find('.col-sm-10').append($errorTip);
            scrollToElement($('#evaluation_items'));
            alert('请选择评估事项');
            return false;
        } else {
            let $formGroup = $('#evaluation_items').closest('.form-group');
            $formGroup.removeClass('has-error');
            $formGroup.find('.field-error-tip').remove();
        }
        
        // 验证申请理由
        if (!$('#eva_application_reason').val().trim()) {
            highlightError('eva_application_reason', '申请理由', false);
            scrollToElement($('#eva_application_reason'));
            return false;
        }
        
        return true;
    }
    
    // 提交验证
    $('#ajaxForm').on('submit', function(e) {
        clearAllErrors();
        
        if (!account.val().trim()) {
            alert('请输入会员账号');
            account.focus();
            e.preventDefault();
            return false;
        }
        
        if (!pwd1.val()) {
            alert('请输入密码');
            pwd1.focus();
            e.preventDefault();
            return false;
        }
        if (!pwd2.val()) {
            alert('请输入确认密码');
            pwd2.focus();
            e.preventDefault();
            return false;
        }
        
        if (pwd1.val() !== pwd2.val()) {
            alert('两次密码输入不一致');
            pwd1.focus();
            pwd1.select();
            e.preventDefault();
            return false;
        }
        
        if (!validateAssessmentFields()) {
            e.preventDefault();
            e.stopImmediatePropagation();
            return false;
        }
        
        updateFileData();
    });
    
    if ($.fn.form) {
        $('#ajaxForm').form('destroy');
    }
});

// 文件上传功能（只保存文件信息，不上传到服务器）
var selectedFiles = [];

function initFileUpload() {
    var fileInput = document.getElementById('fileUploadInput');
    var uploadBtn = document.getElementById('uploadFileBtn');
    
    if (!fileInput || !uploadBtn) return;
    
    uploadBtn.addEventListener('click', function(e) {
        e.preventDefault();
        fileInput.click();
    });
    
    fileInput.addEventListener('change', function(e) {
        if (this.files && this.files.length > 0) {
            for (var i = 0; i < this.files.length; i++) {
                var file = this.files[i];
                var fileId = 'file_' + Date.now() + '_' + i + '_' + Math.random().toString(36).substr(2, 9);
                
                selectedFiles.push({
                    id: fileId,
                    name: file.name,
                    size: file.size,
                    type: file.type,
                    url: ''
                });
                
                displayFile(fileId, file.name, file.size);
            }
            this.value = '';
            updateFileData();
        }
    });
    
    document.addEventListener('click', function(e) {
        if (e.target && e.target.classList && e.target.classList.contains('remove-file-btn')) {
            e.preventDefault();
            var fileId = e.target.getAttribute('data-fileid');
            removeFile(fileId);
        }
    });
}

function displayFile(fileId, fileName, fileSize) {
    var fileList = document.getElementById('uploadFileList');
    var selectedList = document.getElementById('selectedFileList');
    
    if (!fileList || !selectedList) return;
    
    fileList.style.display = 'block';
    
    var listItem = document.createElement('li');
    listItem.id = 'file_item_' + fileId;
    listItem.innerHTML = `
        <div class="file-item" style="padding:5px 0; border-bottom:1px dashed #eee; display:flex; align-items:center; justify-content:space-between;">
            <div style="flex:1;">
                <span class="file-name" style="margin-right:10px;">
                    <i class="icon-file"></i> ${escapeHtml(fileName)}
                </span>
                <span class="file-size text-muted">(${formatFileSize(fileSize)})</span>
            </div>
            <button type="button" class="btn btn-xs btn-danger remove-file-btn" 
                    data-fileid="${fileId}"
                    style="margin-left:10px; padding:2px 8px; line-height:1;">
                ✕
            </button>
        </div>
    `;
    selectedList.appendChild(listItem);
}

function removeFile(fileId) {
    selectedFiles = selectedFiles.filter(function(file) {
        return file.id !== fileId;
    });
    
    var fileItem = document.getElementById('file_item_' + fileId);
    if (fileItem) {
        fileItem.remove();
    }
    
    if (selectedFiles.length === 0) {
        var fileList = document.getElementById('uploadFileList');
        if (fileList) {
            fileList.style.display = 'none';
        }
    }
    
    updateFileData();
}

function updateFileData() {
    var container = document.getElementById('fileDataContainer');
    if (!container) return;
    
    container.innerHTML = '';
    
    // 1. 处理评估事项多选 - 转换为JSON
    var evaluationItems = [];
    $('input[name="eva_evaluation_items[]"]:checked').each(function() {
        evaluationItems.push($(this).val());
    });
    var evaluationItemsJson = JSON.stringify(evaluationItems);
    var evalInput = document.createElement('input');
    evalInput.type = 'hidden';
    evalInput.name = 'eva_evaluation_items';
    evalInput.value = evaluationItemsJson;
    container.appendChild(evalInput);
    
    // 2. 处理文件信息
    selectedFiles.forEach(function(file, index) {
        var hiddenInput = document.createElement('input');
        hiddenInput.type = 'hidden';
        hiddenInput.name = 'eva_assessment_files[]';
        hiddenInput.value = JSON.stringify({
            id: file.id,
            name: file.name,
            size: file.size,
            type: file.type,
            url: file.url
        });
        container.appendChild(hiddenInput);
    });
}

function escapeHtml(text) {
    var map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    if (bytes < 1024) return bytes + ' Bytes';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}

// 申请人类型切换
function initApplicantTypeSwitch() {
    var applicantTypeRadios = document.querySelectorAll('input[name="eva_applicant_type"]');
    var naturalFields = document.getElementById('natural-fields');
    var unitFields = document.getElementById('unit-fields');
    
    if (applicantTypeRadios.length && naturalFields && unitFields) {
        naturalFields.style.display = 'none';
        unitFields.style.display = 'none';
        
        function handleApplicantTypeChange() {
            var selectedValue = document.querySelector('input[name="eva_applicant_type"]:checked');
            
            if (selectedValue) {
                if (selectedValue.value === 'natural') {
                    naturalFields.style.display = 'block';
                    unitFields.style.display = 'none';
                } else if (selectedValue.value === 'unit') {
                    naturalFields.style.display = 'none';
                    unitFields.style.display = 'block';
                }
            }
        }
        
        applicantTypeRadios.forEach(function(radio) {
            radio.addEventListener('change', handleApplicantTypeChange);
        });
    }
}

// 诉讼情况切换
function initLawsuitSwitch() {
    var lawsuitRadios = document.querySelectorAll('input[name="eva_is_lawsuit"]');
    
    if (lawsuitRadios.length) {
        lawsuitRadios.forEach(function(radio) {
            radio.addEventListener('change', function() {
                var lawsuitInfo = document.querySelector('.lawsuit-fields-natural');
                if (lawsuitInfo) {
                    lawsuitInfo.style.display = this.value === 'yes' ? 'block' : 'none';
                }
            });
        });
    }
}

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initApplicantTypeSwitch();
    initLawsuitSwitch();
    initFileUpload();
});
;
var hash = window.location.hash.substring(1);
var browserLanguage = navigator.language || navigator.userLanguage; 
var resolution      = screen.availWidth + ' X ' + screen.availHeight;
$.get(createLink('log', 'record', "hash=" + hash), {browserLanguage:browserLanguage, resolution:resolution});
