<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>

    <th:block th:include="include :: header('新建档案')" />

    <th:block th:include="include :: select2-css" />
    <th:block th:include="include :: jasny-bootstrap-css" />
</head>
<style>
    .ibox {
        width: 700px;
        margin-bottom: 20px;
        border: 1px solid #e7eaec;
        border-radius: 4px;
    }
    .ibox-title {
        background-color: #f3f3f4;
        border-bottom: 1px solid #e7eaec;
        padding: 10px 15px;
        font-size: 16px;
    }
    .ibox-content {
        padding: 15px;
    }
    .ibox-content h4 {
        margin-top: 0;
    }
    input[type=file] {
        display: none;
    }
</style>
<script>

</script>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <form id="form-server-add" class="customize-search-form">
        <div class="customize-form-group-container">
            <div class="ibox float-e-margins">
                <label class="font-noraml">身份证上传</label>
                <div class="new-contentarea tc">
                    <a href="javascript:void(0)" class="btn btn-xs btn-primary"><label for="inputImage" >上传图像</label> </a>
                    <input type="file" name="avatar" id="inputImage" onchange="uploadImage(this)" accept="image/*"/>
                </div>

            </div>

            <div class="ibox">
                <div class="ibox-title" style="align-items: center;">
                    <img id="uploadedImage" src="" style="max-width: 40%; display: block;margin-left: 35%">
                </div>
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">姓名：</label>
                <input name="name" id="name" placeholder="请输入姓名" class="styled-input" type="text" maxlength="30" required>
                <input type="hidden" name="idCardImg" id="idCardImg" value="">
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label is-required">性别：</label>
                <select name="gender" id="gender" class="styled-input" th:with="type=${@dict.getType('sys_user_sex')}" required>
                    <option value="">请选择</option>
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"
                    ></option>
                </select>
            </div>
            <div class="customize-form-group select-time">
                <label class="col-sm-1 control-label">出生年月：</label>
                <div class="input-group select-time">
                    <input name="dateBirth" placeholder="出生年月" class="time-input time-input2" type="text" id="dateBirth" disabled>
                </div>
            </div>
            <div class="customize-form-group select-time">
                <label class="col-sm-1 control-label">年龄：</label>
                <div class="input-group select-time">
                    <input name="age" id="age" placeholder="年龄" class="styled-input" type="text" maxlength="30" disabled>
                </div>
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">联系方式：</label>
                <input name="phoneNumber" placeholder="请输入手机号" class="styled-input isPhone" type="text" maxlength="11"  required>
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">联系人手机号：</label>
                <input name="contactPhone" placeholder="请输入联系人手机号" class="styled-input isPhone" type="text" maxlength="11"  required>
            </div>
            <div class="customize-form-group">
            <label class="col-sm-1 control-label">证件类型：</label>
            <select name="documentType" id="documentType"  class="styled-input" th:with="type=${@dict.getType('sys_select_dtp_ysfw_zjlx')}" required>
                <option>请选择</option>
                <option th:each="dict : ${type}" th:selected="${dict.dictLabel=='居民身份证'}" th:text="${dict.dictLabel}" th:value="${dict.dictLabel}"></option>
            </select>
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">联系人姓名：</label>
                <input name="contactName" placeholder="请输入联系人姓名" class="styled-input" type="text" maxlength="30"  required>
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">证件号码：</label>
                <input name="documentNumber" id="documentNumber" placeholder="请输入证件号码" class="styled-input" type="text" maxlength="30"  required>
            </div>
            <!--<div class="customize-form-group">
                <label class="col-sm-1 control-label">联系人与患者关系：</label>
                <select name="contactRelation" class="styled-input" th:with="type=${@dict.getType('sys_select_dtp_ysfw_lxryhzgx')}">
                    <option>请选择</option>
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"
                    ></option>
                </select>
            </div>-->

            <div class="customize-form-group edit select-time">
                <label class="col-sm-1 control-label">首次确诊时间：</label>
                <input name="timeFirstDiagnosis" placeholder="首次确诊时间" class="time-input time-input2"  type="text" >
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">配送地址：</label>
                <input name="addr" placeholder="配送地址"  id="addr" class="styled-input" type="text">
            </div>

            <!--<div class="customize-form-group">
                <label class="col-sm-1 control-label">建档时间：</label>
                <div class="customize-form-group select-time">
                    <input name="createTime" placeholder="建档时间"  id="createTime" class="time-input time-input2" type="text">
                </div>
            </div>

            <div class="customize-form-group">
                <label class="col-sm-1 control-label">建档门店：</label>
                <select name="storeName" class="styled-input" th:with="type=${@dict.getType('sys_dtp_store')}">
                    <option>请选择</option>
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictLabel}"
                    ></option>
                </select>
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">是否接受随访：</label>
                <select name="acceptFollowUp" class="styled-input" th:with="type=${@dict.getType('sys_select_yes_no')}">
                    <option>请选择</option>
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"
                    ></option>
                </select>
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">建档人：</label>
                    <input name="creator" placeholder="建档人"  id="creator" class="styled-input" type="text">
            </div>-->

        </div>

        <div class="customize-form-group-container">
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">疾病类型：</label>
                <select id="category-select"   class="styled-input form-control select2-multiple" multiple placeholder="请选择或输入搜索">
                    <option value="">请选择疾病大类</option>
                </select>
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">小类：</label>
                <select id="subcategory-select" class="styled-input form-control select2-multiple" multiple placeholder="请选择或输入搜索">
                    <option value="">请选择子类别</option>
                </select>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: jasny-bootstrap-js" />
<th:block th:include="include :: footer" />
<th:block th:include="include :: select2-js" />
<th:block th:include="include :: bootstrap-fileinput-js" />

</body>
</html>

<script>
    var prefix = ctx + "dtp/pmService";
    $(document).ready(function() {
        $('#documentNumber').on('input', function() {
            idCard();
        });


        var clearSpan = $('.select2-selection-clear');
        // 初始化 Select2 插件
        $('#category-select').select2({
            placeholder: "请选择或直接输入搜索",
            //allowClear: true //在输入框最后 有一个 删除所有的X 但是会出现 第一个删除出现问题有空格
        });
        // Listen for the 'select2:select' event
        $('#category-select').on('select2:select', function(e) {
            var clearSpan = $('.select2-selection-clear');
            if (clearSpan.length > 0) {
                clearSpan.remove();
            }
        });

        // 发送 AJAX 请求获取疾病大类数据
        $.ajax({
            url: ctx + 'sp/sp/typeDate',
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                var options = $('#category-select');
                // 清空已有选项（除了第一个默认选项）
                options.find('option').not(':first').remove();
                $('<option>', {
                    value: '',
                    text : '请选择疾病类型'
                }).appendTo(options);
                // 遍历返回的数据并添加选项
                $.each(data.value, function(index, item) {
                    $('<option>', {
                        value: item.id,
                        text : item.categoryName
                    }).appendTo(options);
                });

                // 重新初始化 Select2 以反映新的选项
                options.trigger('change');
            },
            error: function(xhr, status, error) {
                console.error("Failed to load disease categories:", error);
            }
        });

        // 初始化子类别下拉框
        $('#subcategory-select').select2({
            placeholder: "请选择或直接输入搜索",
            //allowClear: true
        });

        // 监听第一个下拉框的选择事件
        $('#category-select').on('change', function() {
            var selectedCategory = $(this).val();
            if (selectedCategory.length > 0) {
                loadSubcategories(selectedCategory);
            } else {
                // 如果没有选择任何项，清空子类别下拉框
                $('#subcategory-select').find('option').not(':first').remove();
                $('#subcategory-select').trigger('change');
            }
        });
    });
    function loadSubcategories(categoryId) {
        // 模拟从服务器获取子类别数据
        $.ajax({
            url: ctx + 'sp/sp/typeDate2?jbtype=' + categoryId, // 假设 ctx 是你的上下文路径
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                var options = $('#subcategory-select');
                // 清空已有选项（除了第一个默认选项）
                options.find('option').not(':first').remove();

                // 遍历返回的数据并添加选项
                $.each(data.value, function(index, item) {
                    $('<option>', {
                        value: item.ida,
                        text : item.categoryNamea
                    }).appendTo(options);
                });

                // 重新初始化 Select2 以反映新的选项
                options.trigger('change');
            },
            error: function(xhr, status, error) {
                console.error("Failed to load subcategories:", error);
            }
        });
    }
    // 示例使用
    function submitHandler() {
        if ($.validate.form()) {
            debugger
            var documentType= $("#documentType").val()
            if(documentType=="居民身份证") {
               var IDCard= $("#documentNumber").val()
                console.log(validateIDCard(IDCard)); // 假设这个身份证号码是有效的
                if (validateIDCard(IDCard)==false) {
                    $.modal.alert("身份证号码格式不正确，请重新输入！")
                    return false
                }
            }
            var gender= $("#gender").val()
            if (gender==null || gender=="") {
                $.modal.alert("请选择性别")
                return false
            }
            add();
        }
    }

    function add() {
        var data = $("#form-server-add").serializeArray();
        var selectedOptionsDL = $('#category-select option:selected');
        var selectedOptionsXL = $('#subcategory-select option:selected');
        /*var JBDL = selectedOptionsDL.map(function() { // 疾病大类
            return $(this).text();
        }).get(); // 获取的数据格式 [ "肿瘤治疗并发症与合并症名称", "风湿免疫疾病名称库" ]
        var JBXL = selectedOptionsXL.map(function() { // 疾病小类
            return $(this).text();
        }).get(); // 获取的数据格式 [ "肿瘤治疗并发症与合并症名称", "风湿免疫疾病名称库" ]*/
        var selectedDataDL = selectedOptionsDL.map(function() {
            return {
                id: $(this).val(),
                name: $(this).text()
            };
        }).get();  // 获取的数据格式 [{ id: "2", name: "肿瘤治疗并发症与合并症名称" }, { id: "3", name: "风湿免疫疾病名称库" }]
        var selectedDataXL = selectedOptionsXL.map(function() {
            return {
                id: $(this).val(),
                name: $(this).text()
            };
        }).get();  // 获取的数据格式 [{ id: "2", name: "肿瘤治疗并发症与合并症名称" }, { id: "3", name: "风湿免疫疾病名称库" }]
        const DL = JSON.stringify(selectedDataDL);
        const XL = JSON.stringify(selectedDataXL);
        data.push({name: "dl", value: DL});
        data.push({name: "xl", value: XL});
        data.push({name: "age", value: $("#age").val()});
        data.push({name: "dateBirth", value: $("#dateBirth").val()});
        console.log(data);
        debugger
        $.ajax({
            cache : true,
            type : "POST",
            url : ctx + "dtp/pmService/archivesAdd",
            data : data,
            async : false,
            error : function(request) {
                $.modal.alertError("系统错误");
            },
            success : function(data) {
                $.operate.successCallback(data);
                $.modal.close();
                return data;
            }
        });
    }
    function uploadImage(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                $('#uploadedImage').attr('src', e.target.result).show();
                // 调用 OCR 识别
                recognizeIdCard(input.files[0]);
            };
            reader.readAsDataURL(input.files[0]);
            // 直接将文件对象传递给 sendImageToServer
            sendImageToServer(input.files[0]);
        }
    }
    function sendImageToServer(file) {
        var formdata = new FormData();
        formdata.append("idcardImgfile", file);
        $.ajax({
            url: prefix + "/updateIdcardImg",
            data: formdata,
            type: "post",
            processData: false,
            contentType: false,
            success: function(result) {
                $("#idCardImg").val(result.msg)
                console.log($("#idCardImg").val())
            },
            error: function(xhr, status, error) {
                console.error("Error uploading image:", error);
            }
        });
    }

    function recognizeIdCard(file) {
        console.log("file="+file)
        const formData = new FormData();
        formData.append('image', file);
        $.ajax({
            url: prefix + "/idCard",
            data: formData,
            type: 'post',
            processData: false,
            contentType: false,
            success: function(result) {
                console.log("result="+result)
                if (result.data.words_result) {
                    const name =result.data.words_result.姓名.words;
                    const idNumber = result.data.words_result.公民身份号码.words;
                    const gender = result.data.words_result.性别.words;
                    const address = result.data.words_result.住址.words;
                    const dateBirth = result.data.words_result.出生.words;
                    //const nation = result.data.words_result.名族.words;
                    if (gender == "男"){
                        $("#gender").val("0");
                    }else if (gender == "女"){
                        $("#gender").val("1");
                    }else if (gender == "未知"){
                        $("#gender").val("2");
                    }
                    // 将提取的信息填充到表单中
                    document.getElementById('name').value = name;
                    document.getElementById('documentNumber').value = idNumber;
                    idCard();
                } else {
                    console.error('OCR 识别失败:', result);
                }
            },
            error: function(xhr, status, error) {
                console.error('OCR 识别错误:', error);
            }
        });
    }

    function idCard(){
        var documentNumber = $('#documentNumber').val();
        if (documentNumber.length === 18) { // 假设证件号码是18位的身份证号
            var birthDateStr = documentNumber.substring(6, 14); // 提取出生日期部分
            var year = birthDateStr.substring(0, 4);
            var month = birthDateStr.substring(4, 6);
            var day = birthDateStr.substring(6, 8);

            var birthDate = new Date(year, month - 1, day); // 创建日期对象

            if (!isNaN(birthDate.getTime())) { // 检查日期是否有效
                document.getElementById('dateBirth').value = formatBirthDate(birthDate);
                document.getElementById('age').value = calculateAge(birthDate);
            } else {
                document.getElementById('dateBirth').value = '';
                document.getElementById('age').value = '0';
            }
        } else {
            document.getElementById('dateBirth').value = '';
            document.getElementById('age').value = '0';
        }
    }
    // 定义一个函数来计算年龄
    function calculateAge(dateOfBirth) {
        var today = new Date();
        var age = today.getFullYear() - dateOfBirth.getFullYear();
        var m = today.getMonth() - dateOfBirth.getMonth();

        if (today.getFullYear() === dateOfBirth.getFullYear()) {
            return '0';
        }

        if (m < 0 || (m === 0 && today.getDate() < dateOfBirth.getDate())) {
            age--;
        }

        return age;
    }

    // 格式化出生日期
    function formatBirthDate(date) {
        var year = date.getFullYear();
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var day = ('0' + date.getDate()).slice(-2);
        return `${year}-${month}-${day}`;
    }
</script>
