//分页参数
 var page_parameter = {
    index: 1,
    pagerows: 15,
    first: true
};
var myUser=getCookie('user');
if(!myUser){
    layer.msg('无权限进入');
}else{
    myUser=JSON.parse(myUser);
}
//layui初始化
layui.use(['form','laypage','laydate','table','element'], function(){
    laydate = layui.laydate
    ,laypage=layui.laypage
    ,table=layui.table;
    //日期
    laydate.render({
    elem: '#csrq'
    });
    laydate.render({
    elem: '#zkcsrq'
    });
    laydate.render({
    elem: '#zkzlrq'
    });

    initCombox();

    form = layui.form;
    form.render(); //更新全部    
    initbuildingtable();
    initpopulation();
    xqcsh();
});     
//多选下拉框的初始化
function initCombox(){
    //重点人员
    layui.formSelects.data('select_zdry', 'local', {
        arr: zdry_conf.map(item => {
            return {
                name: item.name,
                value: item.marktype
            };
        })
    });
    //重点人员作为人员查询条件
    $('#selected_type_role').attr('valuefield', 'id');
    $('#selected_type_role').attr('textfield', 'name');
    $('#selected_type_role').empty();
    addOption($("#selected_type_role"));
    $('#selected_type_role').selectpicker("val", []);
    $('#selected_type_role').selectpicker('refresh');
   //监听重点人员下拉框
    layui.formSelects.on('select_zdry', function (id, vals, obj, isAdd, isDisabled) {
        xl_rytz.tag.forEach(function (item, idex, arr) {
            if ((obj.val == item.marktype) && (item.extenddata)) {
                item.show = isAdd;
                if (isAdd) {
                    setTimeout(() => {
                        $(".well-xq .nav-tabs li").removeClass("active");
                        $(".well-xq .tab-content div").removeClass("active");
                        $(".well-xq .nav-tabs li").eq(0).addClass("active");
                        $(".well-xq .tab-content div").eq(0).addClass("active");
                    }, 10);
                }
            }
        });
        return true;
    });
   //党员
    layui.formSelects.data('select_tag', 'local', {
        arr: [{name:"党员",value:"1"}]
    });
    //监听党员
    layui.formSelects.on('select_tag', function (id, vals, obj, isAdd, isDisabled) {
        vue_dyxl.tag=isAdd;
        setTimeout(() => {
            $(".well .nav-tabs li").removeClass("active");
            $(".well .tab-content div").removeClass("active");
            $(".well .nav-tabs li").eq(0).addClass("active");
            $(".well .tab-content div").eq(0).addClass("active");
        }, 10);
        return true;
    });
    layui.formSelects.config('select_zdry', {direction: 'up'});
    layui.formSelects.config('select_tag', {direction: 'up'});
}

var viewList={};
zdry_conf.forEach(item=>{
    item.extenddata&&(viewList[item.extenddata]=httpVueLoader("../components/zdry/"+item.extenddata+".vue"));
    item.data={};//用户传递的参数
});
// 重点人员详情
var xl_rytz=new Vue({
    el:"#gjsz",
    data:{
        tag:zdry_conf
          //todo
        // zdrys: [
        //   //残疾
        //     {
        //         marktype: "1",
        //         data: {
        //             zjhm: "",
        //             type: "",
        //             cjlb: "",
        //             cjdj: "",
        //             cjzh: "",
        //             jhr: "",
        //             jtzz: "",
        //             lxdh: "",
        //             bz: ""
        //         },
        //         order: ["zjhm", "type", "cjlb", "cjdj", "cjzh", "jhr", "jtzz", "jhrlxdh", "bz"]
        //     },//老人
        //     {
        //         marktype: "7",
        //         data: {
        //             zjhm: "",
        //             type: "",
        //             jsxm: "",
        //             ylrgx: "",
        //             jsjzdz: "",
        //             jslxfs: "",
        //             sfnrzfgmfw: "",
        //             jzdz: "",
        //             hjdz: ""
        //         },
        //         order: ["zjhm", "type", "jsxm", "ylrgx", "jsjzdz", "jslxfs", "sfnrzfgmfw", "jzdz", "hjdz"]
        //     },
        //     {//涉毒
        //         marktype: "3",
        //         data: {
        //             zjhm: "",
        //             type: "",
        //             sqfzr: "",
        //             mj: "",
        //             fj: "",
        //             bz: "",
        //         },
        //         order: ["zjhm", "type", "sqfzr", "mj", "fj", "bz"]
        //     },
        //     {//摸排稳控
        //         marktype: "4",
        //         data: {
        //             zjhm: "",
        //             type: "",
        //             zywtjmd: "",
        //             fzr: "",
        //             fzrdh: ""
        //         },
        //         order: ["zjhm", "type", "zywtjmd", "fzr", "fzrdh"]
        //     }
        // ]
      
    },
    methods:{
        zdry_gjsz:function(){
            this.tag.forEach(function(item,idex,arr){
                item.show=false;
            });
            var selected_item=layui.formSelects.value("select_zdry");
            for(var i=0;i<selected_item.length;i++){
                this.tag.forEach(function(item,idex,arr){
                    if(selected_item[i].val==item.marktype&& (item.extenddata)){
                        item.show=true;
                    }
                });
            }
            $('#collapseExample').collapse('toggle');
            //打开第一个
            setTimeout(() => {
                $(".well-xq .nav-tabs li").removeClass("active");
                $(".well-xq .tab-content div").removeClass("active");
                $(".well-xq .nav-tabs li").eq(0).addClass("active");
                $(".well-xq .tab-content div").eq(0).addClass("active");
            }, 10);
        },resetZDRYS:function(){
            this.tag.forEach(function(v){
                //v.data={};
                for(var key in v.data){
                    v.data[key]="";
                }
            });
        },setZDRYS:function(result){
            this.tag.forEach(function(v){
                for(var nn =0;nn<result.length;nn++){
                    if(result[nn].key==v.marktype&&result[nn].data){
                            v.data=result[nn].data;
                            for(var kk in v.data){
                                v.data[kk]=result[nn].data[kk];
                            }
                    }
                }
            });
        },getZDRYS:function(keys){
            var  datax=[];
            for(var i=0;i<keys.length;i++){
                this.tag.map(function(v){
                    if(keys[i]==v.marktype){
                        datax.push({marktype:keys[i],data:v.data});
                    }     
                });
            }
            return datax;
        }
    },components:viewList
});

// 党员详情
var vue_dyxl=new Vue({
    el:'#dy_xl',
    data:{
        tag:false,
        dy_tag:{},
        dz:[]
    },
    methods:{
        dy_gjsz:function(){
            var selected_item=layui.formSelects.value("select_tag");
            if(selected_item.length>0){
               this.tag=true;
            }else{
                this.tag=false;
            }
        }
    }
});

// 地址详情
var vue_rydz=new Vue({
    el:'#personaddress',
    data:{
      datax:[],
      ban:false
    },
    methods:{
        deleteaddress:function(item){
            layer.confirm('确定要删除该成员吗？', {
                btn: ['确定', '取消'] //按钮
            }, function (index) { //确定删除 
                postByAjax("../edit/"+(item.zljzrq?"zkrydata":"czrydata")+"/1",{data:[vue_ryedit.xq],houseid:item.id},result=>{
                    vue_rydz.datax.remove(item);
                    layer.msg("删除成功");
                });
            });
        },
        detailaddress:function(item){
            var bd = {
                    id: item.buildingid,
                    districtname:item.districtname,
                    name: item.name
                },
                hd = {
                    id: item.id,
                    mj: item.mj,
                    name: item.mph
                };
            queryBuildingStructure(bd, hd);
        },
        //楼栋选择（编辑人员信息时）
        btnLDXX:function (){
            layerOpen({
                title: ['楼栋选择', 'font-weight: 700;'],
                area: ['800px', '625px'],
                content: $('.lddzxz-div'),
            });
        }
    }
});

//layui打开
function layerOpen(layui_open_option,callback) {
    layer.open({
        type: 1,
        title: layui_open_option.title,
        area: layui_open_option.area, //宽高
        content: layui_open_option.content,
        offset: ['50px'],
        btn: ["确定","关闭"],
        resize: false,
        shade :0,
        yes: function (index, layero) {
            if(callback){
                callback(index);
            }else{
                layer.close(index);
            }
        }
    });
}

/**
 * 以房管人
 */
//楼栋数据
function initbuildingtable(){
    page_parameter.condition=Object.assign({},vue_buildingdata.condition);
    postByAjax("../rest/querypagebuilding", page_parameter, resultx => {
        vue_buildingdata.totals=resultx.number;
        laypage.render({
            elem: 'demo3',
            limit: 15,
            count: resultx.number,
            theme: '#337ab7',
            jump: function (data, first) {
                if (!first) {
                    postByAjax("../rest/querypagebuilding", {
                        condition:page_parameter.condition,
                        index: data.curr,
                        pagerows: 15,
                        first: false
                    }, result => {
                        vue_buildingdata.datax = result;
                        if(result.length==0){
                            layer.msg("未查找到数据");
                        }
                    });
                } else {
                    vue_buildingdata.datax = resultx.data;
                    if(resultx.data.length==0){
                        layer.msg("未查找到数据");
                    }
                }
            }
        });
    });
}
//楼栋
var vue_buildingdata = new Vue({
    el: '#fwgl',
    data: {
        datax: [],
        condition:{ name:'',districtname:'' },
        selectedHouse:null,
        totals:0
    },
    methods: {
        query:function(){
             initbuildingtable();
        },
        rkfw:function(item,index){                
            queryBuildingStructure(item);
        }
    }
});
//获取房间
function getRoom(data,k,i,j){
    for(var n=0;n<data.length;n++){
        if(data[n].unitorder==k&&data[n].floororder==i&&data[n].roomorder==j)
            return data[n];
    }
    return null;
}
//查询建筑内人和房屋信息
function queryBuildingStructure(data_building,data_house) {
    vue_buildingdata.selectedHouse=null;
    $(".fwjbxx input.districtname").val(data_building.districtname);
    $(".fwjbxx input.building").val(data_building.name);
    $('.tanchu  .right-div').empty(); //清空右侧
    $('#mydiv').html(''); //清空房屋结构
    let layui_open_option = {
        title: '<span class="layer_span6">楼栋信息</span>',
        content: $(".tanchu"),
        area: ['1280px', '660px'], //宽高
    };
    if (data_building.unitnum && data_building.floornum && data_building.roomnum) { //有房屋结构
        $('.tanchu  .right-div').append($('.tanchutable').html());
        getByAjax("../rest/queryfwjg/0/" + data_building.id, data =>{
            var unitnum = data_building.unitnum;
            var pienum = data_building.floornum;
            var roomnum = data_building.roomnum;
            for (var k = 0; k <= unitnum - 1; k++) {
                var div_unit = $('<div class="div_unit"></div>');
                var unit_num = k + 1;
                var addclass = "unit" + k;
                div_unit.addClass(addclass);
                var title_unit = $('<div class="title_unit"><span>第' + unit_num + '单元</span></div>');
                div_unit.append(title_unit);
                for (var i = pienum; i >= 1; i--) {
                    var myPlie = $('<div class="myplienum"></div>');
                    var mypie = "myPie" + i;
                    myPlie.addClass(mypie);
                    for (var j = 1; j < roomnum + 1; j++) {
                        var temp = getRoom(data, k + 1, i, j);
                        var myDiv = $('<div class="myroom"></div>');
                        if (temp != null) {
                            myDiv.append('<p class="roomnum">' + temp.name + '</p>');
                            //房间绑定数据和事件
                            myDiv[0].attributes.tag = temp;
                            myDiv.click(function () {
                                vue_buildingdata.selectedHouse=this.attributes.tag;
                                showRoomMember(this.attributes.tag, () => {});
                            });
                        } else { //不存在此户
                            myDiv.css('background-image', "url('../img/emptyhouse.png')");
                            myDiv.css('cursor', 'default');
                        }
                        //房间加入楼房
                        myPlie.append(myDiv);
                        div_unit.append(myPlie);
                    }
                }
                $('#mydiv').append(div_unit);
            }
        });
        showRoomMember(data_house?data_house:data_building, () => {
            layerOpen(layui_open_option);
        });
    } else { //无房屋结构
        getByAjax("../rest/queryfwjg/0/"+ data_building.id,data=>{
            layui_open_option = {
                title: '<span class="layer_span7">房屋信息</span>',
                content: $(".tanchutable"),
                area: ['803px', '630px'], //宽高
            };
            vue_buildingdata.selectedHouse=data_house;
            var xx=data_house;
            if (!xx) {
                if (data.length > 0) {
                     xx=data[0];
                     vue_buildingdata.selectedHouse=data[0];
                } else {
                     xx=data_building;
                     vue_buildingdata.selectedHouse=null;
                }
                //xx = data;
            }
            showRoomMember(xx, () => {
                layerOpen(layui_open_option);
            });
        });
    }
}
 
//显示选中房间信息
function showRoomMember(data_house, callback) {
    $(".housejbxx .house").val(data_house.name);
    $(".housejbxx .housemj").val(data_house.mj);
    var table = layui.table;
    //展示家庭成员已知数据
    getByAjax("../rest/queryczrk/" + data_house.id, data => {
        table.render({
            elem: '#tbx',
            height: 190,
            cellMinWidth: 50,
            cols: [
                [ //标题栏
                    {
                        field: 'yhzgx',
                        title: '关系',
                        width: 70,
                        align: 'center',
                        edit: 'text'
                    },
                    {
                        field: 'bz',
                        title: '备注',
                        width: 100,
                        align: 'center',
                        edit: 'text'
                    },
                    {
                        field: 'name',
                        title: '姓名',
                        width: 80,
                        align: 'center'
                    },
                    {
                        field: 'zjhm',
                        title: '身份证号码',
                        width: 175,
                        align: 'center'
                    },
                    {
                        field: 'lxdh',
                        title: '联系电话',
                        width: 120,
                        align: 'center'
                    },
                    {
                        field: 'csny',
                        title: '出生年月',
                        width: 100,
                        align: 'center'
                    },  
                    {
                        field: '',
                        title: '操作',
                        align: 'center',
                        width: 65,
                        templet: '<div><img src="../img/delete.png" title="删除" style="width:15px;height:17px;margin-left: 5px;cursor:pointer;" lay-event="deletejtcy"></div>'
                    }
                ]
            ],
            data: data,
            id: "tbx_data"
        });
         // 表格工具栏
        table.on('tool(demoEvent)', function (obj) {
            // 编辑家庭成员数据
            layer.confirm('确定要删除该成员吗？', {
                btn: ['确定', '取消'] //按钮
            }, function (index) { //确定删除 
                postByAjax("../edit/czrydata/1",{data:[obj.data],houseid:data_house.id},result=>{
                    obj.del();
                    postByAjax("../rest/querydyxq", {//重新更新地址信息
                        zjhm: obj.data.zjhm
                    }, result1 => {
                        vue_rydz.datax=result1.data2;
                    });
                    layer.msg("删除成功");
                });
            });
        });
        //展示租客已知数据
        getByAjax("../rest/queryldrk/" + data_house.id, data1 => {
            table.render({
                elem: '#tbx1',
                height: 190,
                cellMinWidth: 50,
                cols: [
                    [ //标题栏     
                        {
                            field: 'zlksrq',
                            title: '租赁开始日期',
                            width: 120,
                            align: 'center',
                            edit: 'text'
                        },
                        {
                            field: 'zljzrq',
                            title: '租赁到期日期',
                            width: 120,
                            align: 'center',
                            edit: 'text'
                        },
                        {
                            field: 'bz',
                            title: '备注',
                            width: 100,
                            align: 'center',
                            edit: 'text'
                        },
                        {
                            field: 'name',
                            title: '姓名',
                            width: 90,
                            align: 'center'
                        },
                        {
                            field: 'zjhm',
                            title: '身份证号码',
                            width: 174,
                            align: 'center'
                        },
                        {
                            field: '',
                            title: '操作',
                            align: 'center',
                            width: 70,
                            templet: '<div><img src="../img/delete.png" title="删除" style="width:16px;height:17px;margin-left: 5px;cursor:pointer;" lay-event="deletezk"></div>'
                        }
                    ]
                ],
                data: data1,
                id: "tbx1_data"
            });
            table.on('tool(demoEventzk)', function (obj) {
                layer.confirm('确定要删除该租客吗？', {
                    btn: ['确定', '取消'] //按钮
                }, function (index) { //确定删除 
                    postByAjax("../edit/zkrydata/1",{data:[obj.data],houseid:data_house.id},result=>{
                        obj.del();
                        postByAjax("../rest/querydyxq", {//重新更新地址信息
                            zjhm: obj.data.zjhm
                        }, result1 => {
                            vue_rydz.datax=result1.data2;
                        });
                        layer.msg("删除成功");
                    });
                });
            });
        });
        callback();
    });
}

//添加常住人口和暂住人员
function xz_ry(type) {
    $(".tab-content >div").each(function(){
        if($(this).hasClass('active')&&this.id=="profile"){//人员管理操作此按钮是添加特定人
            addPerson(type,[Object.assign({},vue_ryedit.xq)]);
        }else if($(this).hasClass('active')&&this.id=="home"){//以房管人操作此按钮是添加搜索的人
            var  layui_open_option = {
                title: ['新增成员信息', 'font-weight: 700;'],
                area: ['700px', '435px'],
                content: $('.xzcy-div')
            };
            table.render({
                elem: '#ryxxid'
                ,cellMinWidth: 80 
                ,cols: [[
                 {checkbox:true}
                ,{field:'name', width:80, title: '姓名',align:'center'}
                ,{field:'zjhm', width:180, title: '身份证号码',align:'center'}
                ,{field:'csny', width:120, title: '出生年月',align:'center'}
                ,{field:'xb', width:120, title: '性别',align:'center'}
                ]],
                height: 220
                ,data:[]
                ,id:'idTest'
            });
            layerOpen(layui_open_option,(layerindex)=>{
                    var checkStatus = table.checkStatus('idTest'), data= checkStatus.data;   
                    if(data.length !=0){
                        addPerson(type,data,layerindex);
                    }else{
                        layer.msg('未选择要添加的人员!', {
                            area: ['250px', '70px'],
                            icon: 5,
                            anim: 6
                        });
                    }
            });
        }
    });
}
//添加常住人口和暂住人口详细操作
function addPerson(type,data,layerindex){
    //现有人员添加进来
    var option={url:(type=="yhzgx"?"czrydata":"zkrydata"),tbname:(type=="yhzgx"?"tbx_data":"tbx1_data")};
    var dataAll= table.cache[option.tbname];
    var oldnum=dataAll.length;
    dataAll.distinctconcat(data,"zjhm");  
    var newnum=dataAll.length;
    if(oldnum==newnum){
        layer.msg("人员已存在");
        return;
    }if(!vue_buildingdata.selectedHouse){
        layer.msg("尚未选中房间");
        return;
    }
    layerindex&&layer.close(layerindex);
    postByAjax('../edit/'+option.url+'/0', {data:data,houseid:vue_buildingdata.selectedHouse.id}, result => {
        postByAjax("../rest/querydyxq", {
            zjhm: data[0].zjhm
        }, result => {
            vue_rydz.datax=result.data2;
        });
        table.reload(option.tbname,{
            data:dataAll
        });
        layer.msg("成功添加"+(newnum-oldnum)+"条");
    });        
}
//人员查找
$("#rkmhcx").click(function(){
    postByAjax("../rest/queryrk",{condition:{name:$("#cxryxxid").val()}},result=>{
        table.reload("idTest",{
            data:result
        });
    });
});
//人员查找
$("#cxryxxid").keydown(function(){
    if(event.keyCode==13){
        postByAjax("../rest/queryrk",{condition:{name:$("#cxryxxid").val()}},result=>{
            table.reload("idTest",{
                data:result
            });
        });
    }
});

//更新常住人口和暂住人员
function gx_ry(type) {
    var option={url:(type=="yhzgx"?"czrydata":"zkrydata"),tbname:(type=="yhzgx"?"tbx_data":"tbx1_data")};
    var dataAll= table.cache[option.tbname];
    if(!vue_buildingdata.selectedHouse){
        layer.msg("尚未选中房间");
        return;
    }
    postByAjax('../edit/'+option.url+'/2', {data:dataAll,houseid:vue_buildingdata.selectedHouse.id}, result => {
        layer.msg("更新成功");
    });        
}
 
/**
 * 人员管理
 */
//人员数据查询
function initpopulation(){
    if ($('#selected_type_role').val()) {
        vue_rydata.condition.zdry = $('#selected_type_role').val().join(",");
    } else {
        vue_rydata.condition.zdry = null;
    }
    page_parameter.condition=Object.assign({},vue_rydata.condition);
    postByAjax("../rest/queryrkpage", page_parameter, resultx => {
        vue_rydata.totals=resultx.number;
        laypage.render({
            elem: 'demo4',
            limit: 15,
            count: resultx.number,
            theme: '#337ab7',
            jump: function (data, first) {
                if (!first) {
                    postByAjax("../rest/queryrkpage", {
                        condition:page_parameter.condition,
                        index: data.curr,
                        pagerows: 15,
                        first: false
                    }, result => {
                        vue_rydata.datax = result;
                        if(result.length==0){
                            layer.msg("未查找到数据");
                        }
                    });
                } else {
                    vue_rydata.datax = resultx.data;
                    if(resultx.data.length==0){
                        layer.msg("未查找到数据");
                    }
                }
            }
        });
    });
}
//人员管理列表
var vue_rydata = new Vue({
    el: '#rygl',
    data: {
        datax: [],
        disabled:(myUser.gridid?true:false),
        condition: {
            name: '',
            xb: '',
            zjhm: '',
            unrelation: false,
            temporary: false,
            party: false,
            expire: false
        },
        totals: 0
    },
    methods: {
        query:function(){
            initpopulation();
        },
        insert: function () {
            var layui_open_option = {
                title: ['新增人员', 'font-weight: 700;'],
                content: $('.rybjtcc-div'),
                area: ['900px', '810px'], //宽高
            };
            //清空重点人员和党员多选框
            layui.formSelects.value("select_zdry", []);
            layui.formSelects.value("select_tag", []);
            //清除上一个的重点人员详情todo
            xl_rytz.resetZDRYS();
            //关闭
            $('#collapseExample').collapse('hide');
            //都不显示
            xl_rytz.tag.forEach(function (item, idex, arr) {
                item.show = false;
            });
            //清除上一个的党员详情todo
            for (var i in vue_dyxl.dy_tag) {
                vue_dyxl.dy_tag[i] = "";
            }
            //清除上一个地址todo
            vue_rydz.datax = [];
            vue_ryedit.xq = Object.assign({}, vue_ryedit.xq);
            for (var index in vue_ryedit.xq) {
                vue_ryedit.xq[index] = null;
            }
            //人员编辑的时候;身份证不只读,不启用楼栋选中功能
            vue_ryedit.isReadOnly = false;
            vue_rydz.ban = true;
            //打开
            layerOpen(layui_open_option, (layerindex) => {
                layer.confirm('是否确定要保存？', {
                    btn: ['确定', '取消'] //按钮
                }, function (layerindex1) { //确定删除 
                    layer.close(layerindex1);
                    //性别
                    vue_ryedit.xq.xb = $("input[name=sex][type='radio']:checked").val();

                    //重点人员
                    var temp_zdry= layui.formSelects.value("select_zdry").map(item => {
                        return item.val
                    });
                    vue_ryedit.xq.zdry =temp_zdry.join(",");
                    vue_ryedit.xq.zdrys=xl_rytz.getZDRYS(temp_zdry);
                  
                    //党员
                    vue_ryedit.xq.tag = (layui.formSelects.value("select_tag").map(item => {
                        return item.val;
                    })).join(",");
                    //党员详情
                    vue_ryedit.xq.tags = vue_dyxl.dy_tag;
                    if (!vue_ryedit.xq.zjhm) {
                        layer.msg('身份证为空!', {
                            area: ['250px', '70px'],
                            icon: 5,
                            anim: 6
                        });
                        return;
                    }

                    layer.close(layerindex);
                    postByAjax('../edit/population/0', vue_ryedit.xq, result => {
                        if (result==1) {
                            vue_rydata.datax.push(vue_ryedit.xq);
                            layer.confirm('添加成功,是否添加到房屋中？', {
                                btn: ['确定', '取消'] //按钮
                            }, function (layerindex2) {
                                layer.close(layerindex2);
                                vue_rydz.btnLDXX();
                            });
                        } else {
                            layer.msg("添加失败,人员存在");
                        }
                    });
                });
            });
        },
        edit: function (item, index) {
            var layui_open_option = {
                title: ['编辑人员信息', 'font-weight: 700;'],
                content: $('.rybjtcc-div'),
                area: ['900px', '810px'], //宽高
            };
            //清除上一个的重点人员详情todo
            xl_rytz.resetZDRYS();
            //关闭
            $('#collapseExample').collapse('hide');
            //设置重点人员
            if (item.zdry) {
                var temp_zdry=item.zdry.split(",");;
                layui.formSelects.value("select_zdry", temp_zdry);
                //设置重点人员详情
                postByAjax("../rest/queryzdryxq", { zjhm: item.zjhm, type: temp_zdry}, result => {
                    if (result.length != 0) {
                        xl_rytz.setZDRYS(result);
                    }
                });
            } else {
                layui.formSelects.value("select_zdry", []);
            }
            //设置党员
            if (item.tag) {
                layui.formSelects.value("select_tag", item.tag.split(","));
            } else {
                layui.formSelects.value("select_tag", []);
            }
            //设置党员详情以及地址
            postByAjax("../rest/querydyxq", {
                zjhm: item.zjhm
            }, result => {
                //清除之前的党员详情
                if (result.data1[0]) {
                    vue_dyxl.dy_tag = result.data1[0];
                } else {
                    for (var i in vue_dyxl.dy_tag) {
                        vue_dyxl.dy_tag[i] = "";
                    }
                }
                //清除之前的地址信息
                if (result.data2[0]) {
                    vue_rydz.datax = result.data2;
                } else {
                    vue_rydz.datax = [];
                }
            });
            //设置性别
            $("input[name=sex][value='男']").prop("checked", item.xb == '男' ? true : false);
            $("input[name=sex][value='女']").prop("checked", item.xb == '女' ? true : false);

            form.render();
            vue_ryedit.xq = Object.assign({}, item);
            //人员编辑的时候;身份证只读,启用楼栋选中功能
            vue_ryedit.isReadOnly = true;
            vue_rydz.ban = false;
            //打开
            layerOpen(layui_open_option, (layerindex) => {
                layer.confirm('是否确定要保存？', {
                    btn: ['确定', '取消'] //按钮
                }, function (layerindex1) { //确定删除 
                    layer.close(layerindex);
                    //性别
                    vue_ryedit.xq.xb = $("input[name=sex][type='radio']:checked").val();

                    //重点人员
                    var temp_zdry= layui.formSelects.value("select_zdry").map(item => {
                        return item.val
                    });
                    vue_ryedit.xq.zdry =temp_zdry.join(",");
                    vue_ryedit.xq.zdrys=xl_rytz.getZDRYS(temp_zdry);
                    
                    //党员概况
                    vue_ryedit.xq.tag = (layui.formSelects.value("select_tag").map(item => {
                        return item.val
                    })).join(",");
                    //党员详情
                    vue_ryedit.xq.tags = vue_dyxl.dy_tag;
                    postByAjax('../edit/population/2', vue_ryedit.xq, result => {
                        if (result) {
                            layer.msg("修改成功");
                            Vue.set(vue_rydata.datax, index, vue_ryedit.xq)
                        } else {
                            layer.msg("修改失败");
                        }
                    });
                    layer.close(layerindex1);
                });
            });
        },
        deletex: function (item, index) {
            layer.confirm('确定要删除吗？不可恢复!', {
                btn: ['确定', '取消'] //按钮
            }, function (layerindex) { //确定删除 
                postByAjax('../edit/population/1', item, result => {
                    if(result){
                        layer.msg("删除成功");
                        vue_rydata.datax.splice(index, 1);
                        initpopulation();
                     }else{
                        layer.msg("删除失败");
                     }
                 });
                layer.close(layerindex);
            });
        }
    }
});
//人员新增修改
var vue_ryedit=new Vue({
    el:'#person_edit',
    data:{
        xq:{name:'',zjhm:'',lxdh:'',xb:'',csny:'',hkdjd:'',xjzd:'',mz:'',dy:""},
        isReadOnly:false
    }
});

//楼栋查询界面
var vue_ldxz = new Vue({
    el: '#ldxzid',
    data: {
        datax: [],
        condition: { name: "", districtname: "" }
    },
    methods: {
        ldxzquery: function () {  //查询
            postByAjax("../rest/querypagebuilding", { index: 1, first: false, pagerows: 15, condition: this.condition }, resultx => {
                this.datax = resultx;
            });
        },
        queryld:function(item){//打开房屋结构
            queryBuildingStructure(item);
        },
    },
});

function addOption(x) {
    x.empty();
    $.each(zdry_conf, function (i, item) {
        var option = $('<option></option>');
        option.attr('value', item.marktype);
        option.text(item.name);
        x.append(option);
    });
}
 //初始化类型
 function xqcsh(){
    getByAjax("../rest/typesquery",function(data){
        vue_dyxl.dz=data.dzxs;
    });
}

//以下全部为人口批量导入==============================================================================================================================================

var title=null;

function getValue(array){
    var temp=[];
    for (var i=0;i<array.length;i++) {
        temp.push(array[i].field);
    }
    return temp;
}

function getColumn(array){
    var temp=[];
    for (var i=0;i<array.length;i++) {
        temp.push({title:array[i].title,field:array[i].field,width:100,align: 'center'});
    }
    return temp;
}

//暂住人口------------------------------------------------------------------------------
        var vue_zkryfile=new Vue({
        el:'#zzrkid',
        data:{
            zdry:zdry_conf,
            zkry:{
                head:[//表头(租客_基本信息模板||重点人员)
                    {title:'小区名',field:'xqm'},
                    {title:'楼栋号',field:'ldh'},
                    {title:'门牌号',field:'mph'},
                    {title:'租客身份证',field:'zjhm'},
                    {title:'租客姓名',field:'name'},
                    {title:'联系电话',field:'lxdh'},
                    {title:'证件类型',field:'zjlx'},
                    {title:'租客性别',field:'xb'},
                    {title:'租客民族',field:'mz'},
                    {title:'出生年月',field:'csny'},
                    {title:'户口登记地',field:'hkdjd'},
                    {title:'现居住地',field:'xjzd'},
                    {title:'婚姻状况',field:'hyzk'},
                    {title:'租赁开始日期',field:'zlksrq'},
                    {title:'租赁截止日期',field:'zljzrq'},
                    {title:'证件签发日期',field:'zjhmqfrq'},
                    {title:'曾用名',field:'cym'},
                    {title:'出生地',field:'csd'},
                    {title:'籍贯',field:'jg'},
                    {title:'身高',field:'sg'},
                    {title:'血型',field:'xx'},
                    {title:'政治面貌',field:'zzmm'},
                    {title:'文化程度',field:'whcd'},
                    {title:'是否死亡',field:'sfsw'},
                    {title:'工作单位',field:'gzdw'},
                    {title:'备注',field:'bz'},
                    {title:'操作状态',field:'msg'}
                ],
                body:[],//表数据
            },
            zzdydata:{
                head:[//表头(租客_党员)
                    {title:'小区名',field:'xqm'},
                    {title:'楼栋号',field:'ldh'},
                    {title:'门牌号',field:'mph'},
                    {title:'身份证',field:'zjhm'},
                    {title:'姓名',field:'name'},
                    {title:'联系电话',field:'lxdh'},
                    {title:'证件类型',field:'zjlx'},
                    {title:'性别',field:'xb'},
                    {title:'民族',field:'mz'},
                    {title:'出生年月',field:'csny'},
                    {title:'户口登记地',field:'hkdjd'},
                    {title:'现居住地',field:'xjzd'},
                    {title:'婚姻状况',field:'hyzk'},
                    {title:'租赁开始日期',field:'zlksrq'},
                    {title:'租赁截止日期',field:'zljzrq'},
                    {title:'入党日期',field:'rdrq'},
                    {title:'所属党组',field:'ssdz'},
                    {title:'住址',field:'zz'},
                    {title:'所属党支部',field:'szdzb'},
                    {title:'证件签发日期',field:'zjhmqfrq'},
                    {title:'曾用名',field:'cym'},
                    {title:'出生地',field:'csd'},
                    {title:'籍贯',field:'jg'},
                    {title:'身高',field:'sg'},
                    {title:'血型',field:'xx'},
                    {title:'政治面貌',field:'zzmm'},
                    {title:'文化程度',field:'whcd'},
                    {title:'是否死亡',field:'sfsw'},
                    {title:'工作单位',field:'gzdw'},
                    {title:'备注',field:'bz'},
                    {title:'操作状态',field:'msg'},
                ],
                body:[], //表数据             
            },
            czlx:"",
            czlxName:""
        },
        methods:{
            //模板切换
            xzlxchange:function(event){
                this.czlx=event.target.value
                this.czlxName=event.target.options[event.target.selectedIndex].innerText;
                this.zkry.body=[];
                this.zzdydata.body=[];
                $('.zzdyshow').text("");
                $('.zkshow').text("");
                if(this.czlx=="dy"){ 
                    $("#zzdyid").css("display","block");
                    $("#zzdrid").css("display","none");
                    $("#zzmbid").text(this.czlxName);
                }else{
                    $("#zzdrid").css("display","block");
                    $("#zzdyid").css("display","none");
                    $("#zzmbid").text(this.czlxName);                  
                }
            },
            //暂住人口以及重点人员数据表格读取
            zkchange:function(event){
                var that = this;
                var file = event.target.files[0];
                $('.zkshow').text(file.name);
                var reader = new FileReader();
                reader.onload = function (e) {
                    var data = e.target.result;
                    that.zkry.body = readfilefromExcel(data, that.zkry.head, that.czlxName);
                };
                reader.readAsBinaryString(file);
                //刷新file的change事件
                var object = this;
                $('#zzfile').replaceWith('<input type="file" class="myzkFileUpload" id="zzfile" accept=".xls,.xlsx">');
                $('#zzfile').on('change', function () {
                    object.zkchange({target:this});
                });    
            },
            //暂住人口以及重点人员数据表格导入
            zkinsert:function(){
                if(this.czlx==""){
                    layer.msg("请选择导入类型");
                }else if(this.czlx=="zk"){
                    postData('../edit/insertByBatch_zzrk',this.zkry.body,{data:this.zkry.body});
                }else{
                    postData('../edit/insertByBatch_zdry',this.zkry.body,{data:this.zkry.body,type:{zdry:{key:this.czlx},rk:"zk"}})
                }
            },
            //暂住人口以及重点人员数据表格导出
            export_Excel:function(){
                if (!this.czlxName) {
                    layer.msg("请选择生成的数据类型");
                }else if(this.czlx=="zk"){
                    exportExcel("../export/excel_zzrk",{filename:this.czlxName,head:this.zkry.head.slice(0,this.zkry.head.length-1)});
                }else{
                    exportExcel("../export/excel_zdry",{type:{zdry:{key:this.czlx},rk:"zk"},filename:this.czlxName,head:this.zkry.head.slice(0,this.zkry.head.length-1)});
                }
            },
            //暂住党员数据读取
            zzdychange:function(event){
                var that = this;
                var file = event.target.files[0];
                $('.zzdyshow').text(file.name);
                var reader = new FileReader();
                reader.onload = function (e) {
                    var data = e.target.result;
                    that.zzdydata.body = readfilefromExcel(data, that.zzdydata.head, that.czlxName);
                };
                reader.readAsBinaryString(file);
                //刷新file的change事件
                var object = this;
                $('#zzdyfile').replaceWith('<input type="file" class="myzkFileUpload" id="zzdyfile" accept=".xls,.xlsx">');
                $('#zzdyfile').on('change', function () {
                    object.zzdychange({ target: this });
                });    
            },
            //暂住党员导入
            zzdydr:function(){
                if(this.czlx=="dy"){
                    var index = layer.load(1, {
                    shade: [0.1,'#fff'] //0.1透明度的白色背景
                    });
                    postData('../edit/insertByBatch_dy',this.zzdydata.body,{data:this.zzdydata.body,type:"1"});
                }
            },
             //暂住党员导出
            export_Excel_dy:function(){
                if (!this.czlxName) {
                    layer.msg("请选择生成的数据类型");
                    return;
                }
                exportExcel("../export/excel_dy",{type:"1",filename:this.czlxName,head:this.zzdydata.head.slice(0,this.zzdydata.head.length-1)});
            },
            //暂住模板下载
            zzrkdowlond:function(){   
                var sd=$("#zzmbid").text();
                window.location.href="../file/"+sd+".xlsx" ;         
            },
        },
    });

//常住人口------------------------------------------------------------------------------
    var vue_czrkfile=new Vue({
        el:'#czrkid',
        data:{
            zdry:zdry_conf,
            czrk:{
                head:[//表头_基本信息模板||重点人员
                    {title:'小区名',field:'xqm'},
                    {title:'楼栋号',field:'ldh'},
                    {title:'门牌号',field:'mph'},
                    {title:'身份证',field:'zjhm'},
                    {title:'姓名',field:'name'},
                    {title:'联系电话',field:'lxdh'},
                    {title:'证件类型',field:'zjlx'},
                    {title:'性别',field:'xb'},
                    {title:'民族',field:'mz'},
                    {title:'出生年月',field:'csny'},
                    {title:'户口登记地',field:'hkdjd'},
                    {title:'现居住地',field:'xjzd'},
                    {title:'婚姻状况',field:'hyzk'},
                    {title:'与户主关系',field:'yhzgx'},
                    {title:'证件签发日期',field:'zjhmqfrq'},
                    {title:'曾用名',field:'cym'},
                    {title:'出生地',field:'csd'},
                    {title:'籍贯',field:'jg'},
                    {title:'身高',field:'sg'},
                    {title:'血型',field:'xx'},
                    {title:'政治面貌',field:'zzmm'},
                    {title:'文化程度',field:'whcd'},
                    {title:'是否死亡',field:'sfsw'},
                    {title:'工作单位',field:'gzdw'},
                    {title:'备注',field:'bz'},                  
                    {title:'操作状态',field:'msg'},
                ],
                body:[]
            },
            czdydata:{
                head:[//表头_党员
                    {title:'小区名',field:'xqm'},
                    {title:'楼栋号',field:'ldh'},
                    {title:'门牌号',field:'mph'},
                    {title:'身份证',field:'zjhm'},
                    {title:'姓名',field:'name'},
                    {title:'联系电话',field:'lxdh'},
                    {title:'证件类型',field:'zjlx'},
                    {title:'性别',field:'xb'},
                    {title:'民族',field:'mz'},
                    {title:'出生年月',field:'csny'},
                    {title:'户口登记地',field:'hkdjd'},
                    {title:'现居住地',field:'xjzd'},
                    {title:'婚姻状况',field:'hyzk'},
                    {title:'与户主关系',field:'yhzgx'},
                    {title:'入党日期',field:'rdrq'},
                    {title:'所属党组',field:'ssdz'},
                    {title:'住址',field:'zz'},
                    {title:'所属党支部',field:'szdzb'},
                    {title:'证件签发日期',field:'zjhmqfrq'},
                    {title:'曾用名',field:'cym'},
                    {title:'出生地',field:'csd'},
                    {title:'籍贯',field:'jg'},
                    {title:'身高',field:'sg'},
                    {title:'血型',field:'xx'},
                    {title:'政治面貌',field:'zzmm'},
                    {title:'文化程度',field:'whcd'},
                    {title:'是否死亡',field:'sfsw'},
                    {title:'工作单位',field:'gzdw'},
                    {title:'备注',field:'bz'},
                    {title:'操作状态',field:'msg'},
                ],
                body:[],
            },
            czczlx:"",
            czczlxName:"",
        },
        methods:{
            //模板切换
            czqhchange:function(event){
                this.czczlx=event.target.value;
                this.czczlxName=event.target.options[event.target.selectedIndex].innerText;   
                this.czrk.body=[];
                this.czdydata.body=[];    
                $('.czshow').text("");
                $('.czdyshow').text("");
                if(this.czczlx=="dy"){
                    $("#czdymbid").css("display","block");
                    $("#czrkzdid").css("display","none");
                    $("#czmbid").text(this.czczlxName);                 
                }else{
                    $("#czrkzdid").css("display","block");
                    $("#czdymbid").css("display","none");
                    $("#czmbid").text(this.czczlxName);
                }
            },
            //常住人口以及重点人员数据读取
            czchange:function(){
                var that=this;
                var czfile = event.target.files[0];
                $('.czshow').text(czfile.name);
                var reader=new FileReader();
                reader.onload=function (e) {
                    var data=e.target.result;
                    that.czrk.body=readfilefromExcel(data,that.czrk.head,that.czczlxName);
                };
                reader.readAsBinaryString(czfile);
                //刷新file的change事件
                var object = this;
                $('#czfile').replaceWith('<input type="file" class="myzkFileUpload" id="czfile" accept=".xls,.xlsx">');
                $('#czfile').on('change', function () {
                    object.czchange({ target: this });
                });    
            },
            //常住人口以及重点人员导入
            czinsert:function(){
                var czdata = this.czrk.body;
                if (this.czczlx == "") {
                    layer.msg("请选择导入类型");
                } else if (this.czczlx == "cz") {
                    postData('../edit/insertByBatch_czrk', czdata, { data: czdata });
                } else {
                    postData('../edit/insertByBatch_zdry', czdata, { data: czdata, type: { zdry: { key: this.czczlx }, rk: "cz" } });
                }
            },
            //常住人口以及重点人员导出
            export_Excel:function(){
                if (!this.czczlxName) {
                    layer.msg("请选择生成的数据类型");
                }else if(this.czczlx=="cz"){
                    exportExcel("../export/excel_czrk",{filename:this.czczlxName,head:this.czrk.head.slice(0,this.czrk.head.length-1)});
                }else{
                    exportExcel("../export/excel_zdry",{type:{zdry:{key:this.czczlx},rk:"cz"},filename:this.czczlxName,head:this.czrk.head.slice(0,this.czrk.head.length-1)});
                }
            },
            //常住党员数据读取
            czdychange:function(event){
                var that=this;
                var czfile=event.target.files[0];
                $('.czdyshow').text(czfile.name);
                var reader=new FileReader();
                reader.onload=function (e) {
                    var data=e.target.result;
                    that.czdydata.body=readfilefromExcel(data,that.czdydata.head,that.czczlxName);
                };
                reader.readAsBinaryString(czfile);
                //刷新file的change事件
                var object = this;
                $('#czdyfile').replaceWith('<input type="file" class="myzkFileUpload" id="czdyfile" accept=".xls,.xlsx">');
                $('#czdyfile').on('change', function () {
                    object.czdychange({ target: this });
                });    
            },
            //常住党员导入
            czdyinsert:function(){
                if(this.czczlx=="dy"){
                    var data=this.czdydata.body;
                    var index = layer.load(1, {
                        shade: [0.1,'#fff'] //0.1透明度的白色背景
                    });
                    postData('../edit/insertByBatch_dy',data,{data:data,type:"2"});
                }
            },
            //常住党员导出
            export_Excel_dy:function(){
                if (!this.czczlxName) {
                    layer.msg("请选择生成的数据类型");
                    return;
                }
                exportExcel("../export/excel_dy",{type:"2",filename:this.czczlxName,head:this.czdydata.head.slice(0,this.czdydata.head.length-1)});
            },
            //常住人口下载
            czrkdowlond:function(){
                var sb=$("#czmbid").text();
                window.location.href="../file/"+sb+".xlsx" ;         
            }
        }
    });

 //读取excel数据
 function readfilefromExcel(data,head,modulename){
    var persons=[];
    var workbook = XLSX.read(data, {
            type: 'binary'
        }); // 以二进制流方式读取得到整份excel表格对象 
    for (var sheet in workbook.Sheets) {
        //var arrs = file_jq.val().split('\\');
        //var filename = arrs[arrs.length - 1];
        if (workbook.Sheets.hasOwnProperty(sheet) && workbook.SheetNames[0] == modulename) {
            persons = XLSX.utils.sheet_to_json(workbook.Sheets[sheet], { header: getValue(head) });
            title = persons[0];
            persons.splice(0, 1);
            break; // 如果只取第一张表，就取消注释这行
        }else{
            layer.msg("模板加载失败");
        }
    }
    return persons;
}
//批量导入请求
function postData(url,body,post_data){
    var index = layer.load(1, {
        shade: [0.1,'#fff'] //0.1透明度的白色背景
    });
    postDataRecursion(index, url, body,post_data, 0, { total: { total_sb: 0, total_xz: 0, total_gx: 0 }, errdata: [] });
}
//递归批量导入请求
function postDataRecursion(index,url,body,post_data,start,all_result){
    var data = [];
    for (var i = start; i < (start + 100); i++) {
        if (i < body.length) {
            data.push(body[i]);
        } else {
            break;
        }
    }
    post_data.data = data;
    postByAjax(url, post_data, result => {
        result_calculate(all_result, result);
        if (data.length == 100) {
            postDataRecursion(index, url, body, post_data, start + 100, all_result);
        } else {
            layer.alert("新增：" + all_result.total.total_xz + "条,更新：" + all_result.total.total_gx + "条,失败：" + all_result.total.total_sb + "条", {
                skin: 'layui-layer-lan'
                ,closeBtn: 0
                ,anim: 0 //动画类型
              });
            // layer.msg();
            var result_errdata = result.errdata;
            layer.close(index);
            for (var i = 0; i < body.length; i++) {
                for (var j = 0; j < all_result.errdata.length; j++) {
                    if (body[i].zjhm == all_result.errdata[j].zjhm) {
                        body[i].msg = all_result.errdata[j].msg;
                        Vue.set(body, i, body[i]);
                    }
                }
            }
        }
    });
}
//计算结果
function result_calculate(all_result,result){
    all_result.errdata.distinctconcat(result.errdata,"zjhm");
    all_result.total.total_sb+=result.total.total_sb;
    all_result.total.total_xz+=result.total.total_xz;
    all_result.total.total_gx+=result.total.total_gx;
}
//d导出下载
function exportExcel(url, PARAMTERS) {
    var form = document.createElement("form");
    form.method = "POST";
    form.action = url;
    var opt = document.createElement("textarea");
    opt.name="data";
    opt.value=JSON.stringify(PARAMTERS);
    form.appendChild(opt);
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}
