window.I = {
    personModal:$("#personModal"),
    addPerson: $("#addPerson"),
    sxBtn: $("#sxBtn"),
    tempVehicleSaveBtn:$("#tempVehicleSaveBtn"),
    businessNo: $("#businessNo").val(),
    vehicleId: $("#vehicleId").val(),
}

var Obj = {
    id: null,
    businessNo: I.businessNo,
    vehicleId: I.vehicleId,
    userName: null,
    idCard: '',
    phone: '',
    province: '',
    city: '',
    area: '',
    street: '',
    provinceCityArea: '',
}

// 星期一待做 1: 城市选择器 2、验证数据  3、配车后提示人员添加-车辆任务人员添加  4、发卡页面添加人员 5、做一个统一查询页面 6、业务单页面弹出展示
var ViewModel = function() {
    var self = this;
    self.list = ko.observableArray();
    self.o = ko.observable(ko.mapping.fromJS(Obj));
    self.toAddPersons  = function () {
        var o = ko.mapping.fromJS(Obj)
        vm.o(o)
        I.personModal.modal("show");
    }
    self.showPerson  = function (item) {
        getById(item);
    }
    self.delPerson  = function (item) {
        delPerson(item);
    }
}

$(function () {
    window.vm = new ViewModel();
    ko.applyBindings(vm);
    autoHeight();
    getVehiclePersonList();
    pageInit();
});
function isIdCardNo(value) {
 return  /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value);
}
function  pageInit() {
    jQuery.validator.addMethod("isIdCardNo", function (value, element){
        return this.optional(element) || isIdCardNo(value);
    },"请正确输入您的身份证号码");
    I.tempVehicleSaveBtn.on("click",function (e){
        e.preventDefault();
        if (valid()) {
            var o = ko.mapping.toJS(vm.o());
            if (o.id) update(o);
            else add(o);
        }
    })
    I.sxBtn.on("click",function(e){
        getVehiclePersonList();
        let $this =  $(this)
        $this.attr("disabled","");
        setTimeout(function (){ $this.removeAttr("disabled")},5000);
    })
    window.address_picker = new addressPicker({
        id: "city", level: 3, data: cityData3,
        btnConfig: [{
            text: '清除数据', click: function () {
                address_picker.clearSelectedData();
                $("#city").val('');
            }
        }]
        });
    address_picker.on("click",function () {
        var obj = address_picker.getCurrentObject();
        if(obj.level === 3) {
            var val = address_picker.getTotalValueAsText();
            $("#city").val(val);
            setProvinceCityArea(val);
        }
    })
    I.personModal.on('hidden.bs.modal', function (e) {
        $("#city").val('');
        clearError();
    });
    $("#city").on("click",function(event){
        var display = $(".adp-wraper").css("display");
        setTimeout(function () {
                $(document).one("click",
                    function () {
                        // $(".adp-wraper").hide();
                        address_picker.hide();
                    });
        },300);
        event.stopPropagation(); //阻止事件向上冒泡
    })

}
function setProvinceCityArea(val){
    if(!val || val.trim()=='')  {
        vm.o().province('');
        vm.o().city('');
        vm.o().area('');
        return;
    }
    var arr = val.split("/")
    for(var i=0,len=arr.length;i<len;i++) {
        if(i==0) vm.o().province(arr[i].trim());
        if(i==1) vm.o().city(arr[i].trim());
        if(i==2) vm.o().area(arr[i].trim());
    }
}
function getVehiclePersonList () {
    $.post("/businessVehiclePerson/list.htm", {vehicleId: I.vehicleId, businessNo: I.businessNo},
        function (data, textStatus, jqXHR) {
            if (data.code >= 1) {
                swal({title: '', text: data.errmsg, type: 'error', confirmButtonText: '确定'});
                return;
            }
            if (data.code == 0) {
                vm.list.removeAll()
                data.list.forEach(l=>{
                    l.provinceCityArea = l.province + l.city + l.area + " " + l.street
                });
                if(isList(data.list))  vm.list.push(...data.list);
            }
        })
}

function  getById(item){
    $.post("/businessVehiclePerson/get.htm", {id: item.id},
        function (data, textStatus, jqXHR) {
            if (data.code >= 1) {
                swal({title: '', text: data.errmsg, type: 'error', confirmButtonText: '确定'});
                return;
            }
            if (data.code == 0) {
                I.personModal.modal("show");
                var item = data.item;
                $("#city").val(item.province + " / " + item.city + " / " + item.area)
                var arr = getProvinceCityArea(item.province,item.city,item.area);
                address_picker.setSelectedData(arr);
                console.log(arr)
                var  newItem = ko.mapping.fromJS(item)
                vm.o(newItem);
                getVehiclePersonList();
            }
        })
}

function delPerson(item) {
    swal({
        title: "是否确认删除?", text: "",  type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#1c84c6",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnConfirm: true,
        closeOnCancel: true,
    }, function (isConfirm) {
        if (isConfirm) {
            $.post("/businessVehiclePerson/del.htm", {id: item.id},
                function (data, textStatus, jqXHR) {
                    if (data.code >= 1) {
                        swal({title: '', text: data.errmsg, type: 'error', confirmButtonText: '确定'});
                        return;
                    }
                    if (data.code == 0) {
                        parent.showErrmsg("删除成功!");
                        getVehiclePersonList();
                    }
                })
        }
    });
}
function update() {
    var o = ko.mapping.toJS(vm.o());
    $.post("/businessVehiclePerson/update.htm", o,
        function (data, textStatus, jqXHR) {
            if (data.code >= 1) {
                swal({title: '', text: data.errmsg, type: 'error', confirmButtonText: '确定'});
                return;
            }
            if (data.code == 0) {
                parent.showErrmsg("更新成功!");
                I.personModal.modal("hide");
                getVehiclePersonList();
            }
        })
}

function getProvinceCityArea(province,city,area){
    let array = []
    cityData3.forEach(({text,value,children}) =>{
        if(text === province) { array[0] = value;
            children.forEach(({text,value,children}) => {
                if(text === city) { array[1] = value;
                    children.forEach(({text,value}) => {
                        if(text === area) { array[2] = value;}
                    });
                }
            });
        }
    })
    return array;
}

function add(item) {
    $.post("/businessVehiclePerson/add.htm", item,
        function (data, textStatus, jqXHR) {
            if (data.code >= 1) {
                swal({title: '', text: data.errmsg, type: 'error', confirmButtonText: '确定'});
                return;
            }
            if (data.code == 0) {
                parent.showErrmsg("新增成功!");
                I.personModal.modal("hide");
                getVehiclePersonList();
            }
        })
}


function valid(){
    var isValid = false;
    var iF = $('#form');
    iF.validate({
        rules: {
            'userName': {
                required: true,
               // isPlateNumber: true
            },
            'idCard': {
                required: true,
                isIdCardNo: true,
            },
            'dataPhone': {
                required: true,
                isPhone: true
            },
            'street': {
                required: true,
            },
            'city': {
                required: true,
            }
        },
        messages: {
            'userName': {
                required: '不能为空!',
            },
            'idCard': {
                required: '不能为空!',
                isIdCardNo: '身份证号码不正确'
            },
            'dataPhone': {
                required: '不能为空!',
                isPhone: '手机号不正确!'
            },
            'street': {
                required: '不能为空!',
            },
            'city': {
                required: '不能为空!',
            }
        },
        errorPlacement: function (err, element) {
            var p = element.parents('.form-group').eq(0);
            var d = p.find('.text-error').eq(0);
            d.css('color', '#D9534F');
            err.appendTo(d);
        }
    })
    isValid = iF.valid();
    return isValid;
}


function clearError() {
    $('#form input').removeClass('error');
    $('#form .text-error').html('');
}

function autoHeight() {
    $('.page-content').css('min-height', $(parent.window).height() - 117);
    $('.table-responsive').css('height', $(parent.window).height() - 275);
    $('.split').css('left', $('.table-vehicleId').width() + 12);
}