<!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 is-required">姓名：</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 is-required">联系方式：</label>
                <input name="phoneNumber" id="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 edit select-time">
                <label class="col-sm-1 control-label is-required">首次确诊时间：</label>
                <input name="timeFirstDiagnosis" id="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>

        <div class="customize-form-group-container">
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">肿瘤发病部位疾病：</label>
                <select id="category-select1"   class="styled-input form-control select2-multiple" multiple placeholder="请选择或输入搜索">
                </select>
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">肿瘤治疗并发症与合并症：</label>
                <select id="category-select2" class="styled-input form-control select2-multiple" multiple placeholder="请选择或输入搜索">
                </select>
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">风湿免疫疾病名称：</label>
                <select id="category-select3"   class="styled-input form-control select2-multiple" multiple placeholder="请选择或输入搜索">
                </select>
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">罕见病疾病：</label>
                <select id="category-select4" class="styled-input form-control select2-multiple" multiple placeholder="请选择或输入搜索">
                </select>
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">感染类疾病：</label>
                <select id="category-select5"   class="styled-input form-control select2-multiple" multiple placeholder="请选择或输入搜索">
                </select>
            </div>
            <div class="customize-form-group">
                <label class="col-sm-1 control-label">临时慢病：</label>
                <select id="category-select6"   class="styled-input form-control select2-multiple" multiple placeholder="请选择或输入搜索">
                </select>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: select2-js" />
</body>
</html>
<script>
    var prefix = ctx + "dtp/pmService";
    var smName;
    $(document).ready(function() {
        $('#documentNumber').on('input', function() {
            idCard();
        });

        for (var i = 1; i < 7; i++) {
            // 初始化 Select2 插件
            $('#category-select'+i).select2({
                placeholder: "请选择或直接输入搜索",
                //allowClear: true //在输入框最后 有一个 删除所有的X 但是会出现 第一个删除出现问题有空格
            });
        }

        // 肿瘤发病部位疾病名称 1
        // 肿瘤治疗并发症与合并症名称 2
        // 风湿免疫疾病名称库 3
        // 罕见病疾病名称  4
        // 感染类疾病名称 5
        // 临时慢病名称 6
        // 发送 AJAX 请求获取疾病大类数据
        $.ajax({
            url: ctx + 'sp/sp/typeDate',
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                var options1 = $('#category-select1');
                var options2 = $('#category-select2');
                var options3 = $('#category-select3');
                var options4 = $('#category-select4');
                var options5 = $('#category-select5');
                var options6 = $('#category-select6');
                // 清空已有选项（除了第一个默认选项）
                options1.find('option').not(':first').remove();
                options2.find('option').not(':first').remove();
                options3.find('option').not(':first').remove();
                options4.find('option').not(':first').remove();
                options5.find('option').not(':first').remove();
                options6.find('option').not(':first').remove();
                $('<option>', {
                    value: '',
                    text : '请选择疾病'
                }).appendTo(options1);
                $('<option>', {
                    value: '',
                    text : '请选择疾病'
                }).appendTo(options2);
                $('<option>', {
                    value: '',
                    text : '请选择疾病'
                }).appendTo(options3);
                $('<option>', {
                    value: '',
                    text : '请选择疾病'
                }).appendTo(options4);
                $('<option>', {
                    value: '',
                    text : '请选择疾病'
                }).appendTo(options5);
                $('<option>', {
                    value: '',
                    text : '请选择疾病'
                }).appendTo(options6);
                // 遍历返回的数据并添加选项
                $.each(data.value, function(index, item) {
                    if(item.dict_key==1){
                        $('<option>', {
                            value: item.id,
                            text : item.categoryName
                        }).appendTo(options1);
                    }
                    if(item.dict_key==2){
                        $('<option>', {
                            value: item.id,
                            text : item.categoryName
                        }).appendTo(options2);
                    }
                    if(item.dict_key==3){
                        $('<option>', {
                            value: item.id,
                            text : item.categoryName
                        }).appendTo(options3);
                    }
                    if(item.dict_key==4){
                        $('<option>', {
                            value: item.id,
                            text : item.categoryName
                        }).appendTo(options4);
                    }
                    if(item.dict_key==5){
                        $('<option>', {
                            value: item.id,
                            text : item.categoryName
                        }).appendTo(options5);
                    }
                    if(item.dict_key==6){
                        $('<option>', {
                            value: item.id,
                            text : item.categoryName
                        }).appendTo(options6);
                    }
                });

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


    });

    // 示例使用
    function submitHandler() {
            debugger
            var documentType= $("#documentType").val()
            if(documentType=="居民身份证") {
               var IDCard= $("#documentNumber").val()
                if (IDCard == null || IDCard == "" || IDCard == undefined){
                    $.modal.alert("请输入身份证号码")
                    return false
                }
                if (validateIDCard(IDCard)==false) {
                    $.modal.alert("身份证号码格式不正确，请重新输入！")
                    return false
                }
            }
            var gender= $("#gender").val()
            if (gender==null || gender=="" || gender==undefined) {
                $.modal.alert("请选择性别")
                return false
            }
            var timeFirstDiagnosis= $("#timeFirstDiagnosis").val()
            if (timeFirstDiagnosis==null || timeFirstDiagnosis=="" || timeFirstDiagnosis==undefined) {
                $.modal.alert("请选择首次确诊时间")
                return false
            }
        var phoneNumber= $("#phoneNumber").val()
        if (phoneNumber==null || phoneNumber=="" || phoneNumber==undefined) {
            $.modal.alert("请输入联系方式")
            return false
        }

            add();
    }

    function add() {
        var data = $("#form-server-add").serializeArray();
        // 获取所有选中的选项并处理数据
            var selectedDataDL = [];
            for (let i = 1; i <= 6; i++) {
                var selectedOptionsDL = $(`#category-select${i} option:selected`);
                if (selectedOptionsDL.length > 0) {
                    selectedOptionsDL.each(function() {
                        selectedDataDL.push({
                            id: $(this).val(),
                            name: $(this).text(),
                        });
                    });
                }
            }
           var hasSelection = false;
            if (selectedDataDL.length > 0) {
                hasSelection = true;
            }

            const DL = JSON.stringify(selectedDataDL);
            if (!hasSelection) {
                $.modal.alert('请至少选择一个疾病选项！');
                return;
            }
        if($.common.isNotEmpty(smName)){
            data.push({name: "smName", value: smName});
        }
        data.push({name: "dl", value: DL});
        data.push({name: "age", value: $("#age").val()});
        data.push({name: "dateBirth", value: $("#dateBirth").val()});
        console.log("data2"+data);
        $.ajax({
            cache : true,
            type : "POST",
            url : ctx + "dtp/pmService/addArchivesCallback",
            data : data,
            async : false,
            error : function(request) {
                $.modal.alertError("系统错误");
            },
            success : function(responseData) {
                if(data.code==500){
                    $.modal.alertError(data.msg);
                    return ;
                }else{
                    $.operate.successCallback1(responseData);
                    $.modal.msg("保存成功");
                    // 关闭模态窗口
                    $.modal.close();
                    $.modal.msgSuccessReload();
                }
            }
        });
    }

    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");
                    }
                    smName=name;
                    // 将提取的信息填充到表单中
                    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>
