<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增弹框配置')" />
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: bootstrap-select-css" />
    <th:block th:include="include :: cropbox-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-configuration-add">
        <div class="form-group">
            <label class="col-sm-3 control-label">弹框标题：</label>
            <div class="col-sm-8">
                <input id="alertTitle" name="alertTitle" class="form-control" type="text" required>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">弹框类型：</label>
            <div class="col-sm-3">
                <select style="margin-bottom: 10px;" title="请选择" id="alertType" name="alertType" class="form-control m-b selectpicker" th:with="type=${@dict.getType('alert_configuration_type')}">
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                </select>
                <span style="font-size: 12px;color: #999999;">切换类型后需要重新配置信息</span>
            </div>
        </div>
        <div class="form-group" id="alertImageItem">
            <label class="col-sm-3 control-label">弹框图片：</label>
            <div class="col-sm-8">
                <div id="div-bgUrl"></div>
                <div class="action">
                    <input type="file" class="" name="avatar" id="avatar" accept="image/*" value="上传"/>
                </div>
                <span style="font-size: 12px;color: #999999">建议图片宽度260px,高度300px,宽高比5:8</span>
            </div>
        </div>
        <div class="form-group" id="alertContentItem">
            <label class="col-sm-3 control-label">弹框内容：</label>
            <div class="col-sm-8">
                <textarea id="alertContent" name="alertContent" class="form-control"></textarea>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">弹框开始时间：</label>
            <div class="col-sm-8">
                <input id="alertStartTime" name="alertStartTime" class="form-control" type="datetime-local">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">弹框结束时间：</label>
            <div class="col-sm-8">
                <input id="alertEndTime" name="alertEndTime" class="form-control" type="datetime-local">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">弹框每日可弹次数：</label>
            <div class="col-sm-8">
                <input id="alertNum" name="alertNum" class="form-control" type="number">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">用户类型：</label>
            <div class="col-sm-8">
                <select title="请选择" id="userType" name="userType" class="form-control m-b selectpicker" th:with="type=${@dict.getType('sys_alert_permission')}" multiple>
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                </select>
                <span class="help-block m-b-none"><i class="fa fa-info-circle"></i> 默认为全部人员</span>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">部门类型：</label>
            <div class="col-sm-3">
                <select title="请选择公司" id="deptType1" class="form-control m-b selectpicker">
                </select>
            </div>
            <div class="col-sm-3">
                <select title="请选择大区" id="deptType2" class="form-control m-b selectpicker">
                </select>
            </div>
            <div class="col-sm-3">
                <select title="请选择销售部" id="deptType3" class="form-control m-b selectpicker">
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label"></label>
            <div class="col-sm-3">
                <a class="btn btn-primary btn-rounded btn-sm" id="clearSelect">清空部门类型</a>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: datetimepicker-js" />
<th:block th:include="include :: bootstrap-select-js" />
<th:block th:include="include :: cropbox-js"/>
<script type="text/javascript">
    var prefix = ctx + "system/configuration"
    var domain = window.location.host;
    var ht = domain.indexOf('localhost') != -1 ? 'http://' : 'https://';
    var getCompanyListPrefix = ht + domain + "/wxportal-api/sysuser/searchOrg";

    var photoUrl;
    var options = {
        thumbBox: '.thumbBox',
        spinner: '.spinner',
        imgSrc: ctx + 'img/profile.jpg'
    }

    $(document).ready(function () {
        var obj = {
            parType: "diy_level",
            parValue: ""
        }
        $("#alertContentItem").hide();
        $("#alertImageItem").hide();
        getCompanyList(obj);
        $('#avatar').on('change', function () {
            var reader = new FileReader();
            reader.onload = function (e) {
                options.imgSrc = e.target.result;
                //根据MIME判断上传的文件是不是图片类型
                if ((options.imgSrc).indexOf("image/") == -1) {
                    $.modal.alertWarning("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
                }
            }
            reader.readAsDataURL(this.files[0]);
            upBg(this.files[0]);
        })
    })

    $("#alertStartTime").on('change',function () {
        if ($(this).val() != -1){
            var startTimeChange1 = $('#alertStartTime').val().replace('T',' ');
            var endTimeChange1 = $('#alertEndTime').val().replace('T',' ');
            if (new Date(startTimeChange1).getTime() - new Date(endTimeChange1).getTime() >= 0){
                $.modal.alertWarning("弹框结束时间不能小于开始时间");
            }
        }
    })

    $("#alertEndTime").on('change',function () {
        if ($(this).val() != -1){
            var startTimeChange2 = $('#alertStartTime').val().replace('T',' ');
            var endTimeChange2 = $('#alertEndTime').val().replace('T',' ');
            if (new Date(startTimeChange2).getTime() - new Date(endTimeChange2).getTime() >= 0){
                $.modal.alertWarning("弹框结束时间不能小于开始时间");
            }
        }
    })

    $("#alertType").on('change',function () {
        if ($(this).val() != -1){
            if ($(this).val() == 0){
                $("#alertContentItem").show();
                $("#alertImageItem").hide();
                $("#div-bgUrl").html("<div></div>");
                photoUrl = "";
            }
            if ($(this).val() == 1){
                $("#alertImageItem").show();
                $("#alertContentItem").hide();
                $('#alertContent').val('');
            }
        }
    })

    $("#deptType1").on('change',function () {
        if ($(this).val() != -1){
            var obj1 = {
                parType: "company_level",
                parValue: $(this).val()
            }
            $("#deptType2").empty().append("");
            $("#deptType2").selectpicker('refresh');
            $("#deptType3").empty().append("");
            $("#deptType3").selectpicker('refresh');
            getCompanyList(obj1);
        }
    })

    $("#deptType2").on('change',function () {
        if ($(this).val() != -1){
            var obj2 = {
                parType: "office_level",
                parValue: $(this).val()
            }
            $("#deptType3").empty().append("");
            $("#deptType3").selectpicker('refresh');
            getCompanyList(obj2);
        }
    })

    $("#clearSelect").on('click',function () {
        var obj3 = {
            parType: "diy_level",
            parValue: ""
        }
        $("#deptType1").empty().append("");
        $("#deptType1").selectpicker('refresh');
        $("#deptType2").empty().append("");
        $("#deptType2").selectpicker('refresh');
        $("#deptType3").empty().append("");
        $("#deptType3").selectpicker('refresh');
        getCompanyList(obj3,"");
    })

    $("#form-configuration-add").validate({
        focusCleanup: true,
        rules:{
            alertContent:{
                required:true
            },
            alertStartTime:{
                required:true
            },
            alertEndTime:{
                required:true
            },
            alertNum: {
                required:true
            }
        },
    });

    function upBg(imgFile) {
        var formdata = new FormData();
        formdata.append("file", imgFile);
        $.ajax({
            url: ctx + "common/upload",
            data: formdata,
            type: "post",
            processData: false,
            contentType: false,
            success: function (result) {
                if (result.code == 0) {
                    photoUrl = result.data.url;
                    $("#div-bgUrl").html("<img src='" + result.data.url + "' style='width:300px;margin-bottom: 5px;'>");
                } else {
                    $.modal.alertWarning(result.msg);
                }
            }
        })
    }

    function submitHandler() {
        if ($.validate.form()) {
            var alertTitle = $('#alertTitle').val();
            var alertType = $('#alertType').val();
            var contentVal = $('#alertContent').val();
            var startTime = $('#alertStartTime').val().replace('T',' ');
            var endTime = $('#alertEndTime').val().replace('T',' ');
            var alertNum = $('#alertNum').val();
            var userType;
            if ($('#userType').val()) {
                userType = $('#userType').val().join(',');
            }else {
                userType = '';
            }
            if (new Date(startTime).getTime() - new Date(endTime).getTime() >= 0){
                $.modal.alertWarning("弹框结束时间不能小于开始时间");
            } else {
                var objSubmit = {
                    alertTitle:alertTitle,
                    alertType:alertType,
                    photoUrl:photoUrl,
                    alertContent:contentVal,
                    alertStartTime:startTime,
                    alertEndTime:endTime,
                    alertNum:alertNum,
                    userType:userType,
                    alertStatus:'0'
                }
                if ($('#deptType3').val() != "") {
                    objSubmit.salesLevel = 'suboffice_level';
                    objSubmit.orgCode = $('#deptType3').val();
                    objSubmit.orgName = $('#deptType3').find("option:selected")[0].label
                }
                if ($('#deptType2').val() != "" && $('#deptType3').val() == "") {
                    objSubmit.salesLevel = 'office_level';
                    objSubmit.orgCode = $('#deptType2').val();
                    objSubmit.orgName = $('#deptType2').find("option:selected")[0].label
                }
                if ($('#deptType1').val() != "" && $('#deptType2').val() == "" && $('#deptType3').val() == "") {
                    objSubmit.salesLevel = 'company_level';
                    objSubmit.orgCode = $('#deptType1').val();
                    objSubmit.orgName = $('#deptType1').find("option:selected")[0].label
                }
                if ($('#deptType1').val() == "" && $('#deptType2').val() == "" && $('#deptType3').val() == "") {
                    objSubmit.salesLevel = 'diy_level';
                }
                console.log('objSubmit', objSubmit);
                var configSubmit = {
                    url: prefix + "/add",
                    type: "post",
                    dataType: "json",
                    data: objSubmit,
                    beforeSend: function () {
                        $.modal.loading("正在处理中，请稍后...");
                    },
                    success:function (result) {
                        $.modal.closeLoading();
                        $.operate.successCallback(result);
                    }
                }
                $.ajax(configSubmit)
            }
        }
    }

    /* 获取公司列表 */
    function getCompanyList(obj) {
        var config = {
            url: getCompanyListPrefix,
            type: "post",
            dataType: "json",
            data: obj,
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                $.modal.closeLoading();
                var companyList = result.dataList;
                if (companyList && companyList.length != 0){
                    var options = '';
                    if (obj.parType == 'diy_level'){
                        companyList.forEach(item=>{
                            options += "<option value='" + item.company_code + "'>" + item.company_name + "</option>"
                        })
                        $("#deptType1").append(options);
                        $("#deptType1").selectpicker('refresh');
                        $("#deptType1").selectpicker('render');
                    } else if (obj.parType == 'company_level') {
                        companyList.forEach(item=>{
                            options += "<option value='" + item.office_code + "'>" + item.office_name + "</option>"
                        })
                        $("#deptType2").append(options);
                        $("#deptType2").selectpicker('refresh');
                        $("#deptType2").selectpicker('render');
                    }else {
                        companyList.forEach(item=>{
                            options += "<option value='" + item.suboffice_code + "'>" + item.suboffice_name + "</option>"
                        })
                        $("#deptType3").append(options);
                        $("#deptType3").selectpicker('refresh');
                        $("#deptType3").selectpicker('render');
                    }
                }
            }
        };
        $.ajax(config)
    }
</script>
</body>
</html>
