<template>
    <d2-container>
        <div class="d2-table-view-full">
            <div class="d2-table-view-header">
                <el-form size="small" :inline="true" :model="filter" @keyup.enter.native="handleList" class="demo-form-inline">
                    <el-form-item label="卡号">
                        <el-input v-model="filter.cardNo" clearable/>
                    </el-form-item>
                    <el-form-item label="姓名">
                        <el-input v-model="filter.visitorName" clearable/>
                    </el-form-item>
                    <el-form-item label="访客类型">
                        <el-select v-model="filter.typeId" filterable placeholder="请选择" clearable>
                            <el-option
                                    v-for="item in options"
                                    :key="item.typeId"
                                    :label="item.typeName"
                                    :value="item.typeNo">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="卡状态">
                        <el-select :isAll="true" v-model="filter.cardState" clearable>
                            <el-option label="有效" value="1"></el-option>
                            <el-option label="失效" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="使用状态">
                        <el-select :isAll="true" v-model="filter.useState" clearable>
                            <el-option label="未使用" value="1"></el-option>
                            <el-option label="使用中" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleList('1')">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="d2-table-view-content">
                <div class="d2-table-view-handle">
                    <el-button @click="operVisible = !operVisible" size="small" icon="el-icon-plus">新增</el-button>
                    <el-button size="small" @click="onMutilSendClick">批量发卡</el-button>
                    <el-button size="small" @click="onMutilDelClick">批量删除</el-button>
                </div>
                <d2-crud
                        title="访客卡权限"
                        ref="d2Crud"
                        :columns="columns"
                        :data="data"
                        :options="tableOptions"
                        :loading="loading"
                        :rowHandle="rowHandle"
                        @send="handleRowSendcard"
                        @edit="handleRowEdit"
                        @delete="handleRowDelete"
                        selection-row
                        @selection-change="handleSelectionChange"
                ></d2-crud>
            </div>
            <div class="d2-table-view-footer">
                <el-pagination
                        @current-change="handleCurrentChange"
                        @size-change="handleSizeChange"
                        :page-size="tableOptions.pageList[0]"
                        :page-sizes="tableOptions.pageList"
                        :current-page.sync="currentPage"
                        layout="total,sizes, prev, pager, next,jumper"
                        :total="pagination.total"
                ></el-pagination>
            </div>
        </div>
        <el-dialog
                :title="diaLogName"
                :visible.sync="operVisible"
                width="60%"
                @close="clearForm"
                :close-on-click-modal="false">
            <el-form ref="form" :model="form" label-width="90px" labelPosition="right" :rules="rules">
                <el-row :gutter="16">
                    <el-col :span="11">
                        <el-form-item label="卡号">
                            <el-input v-model="form.cardNo" disabled/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="序列号">
                            <el-input v-model="form.cardSequence"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="访客姓名" prop="visitorName">
                            <el-autocomplete
                                    v-model="form.visitorName"
                                    :fetch-suggestions="querySearchName"
                                    @select="handleSelect"
                                    placeholder="请输入内容"
                                    style="width: 100%">
                            </el-autocomplete>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="证件号">
                            <el-input v-model="form.visitorNo" disabled/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="失效时间" prop="expirationDate">
                            <el-date-picker
                                    type="datetime"
                                    v-model="form.expirationDate"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    :picker-options="expireTimeOption"
                                    style="width: 100%;"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="访客类型" prop="typeId">
                            <el-select v-model="form.typeId" filterable placeholder="请选择" style="width: 100%;"
                                       clearable>
                                <el-option
                                        v-for="item in options"
                                        :key="item.typeId"
                                        :label="item.typeName"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="起始时间" prop="bgTm">
                            <el-time-select
                                    placeholder="起始时间"
                                    v-model="form.bgTm"
                                    :picker-options="{
                                        start: '07:30',
                                        step: '00:15',
                                        end: '18:30'}"
                                    style="width: 100%;">
                            </el-time-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="结束时间" prop="endTm">
                            <el-time-select
                                    placeholder="结束时间"
                                    v-model="form.endTm"
                                    :picker-options="{
                                        start: '07:30',
                                        step: '00:15',
                                        end: '18:30',
                                        minTime: form.bgTm}"
                                    style="width: 100%;">
                            </el-time-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="卡状态">
                            <el-select disabled v-model="form.cardState" style="width: 100%;" clearable>
                                <el-option label="有效" value="1"></el-option>
                                <el-option label="失效" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="所属区域" prop="resId">
                            <el-select v-model="form.resId" filterable placeholder="请选择" style="width: 100%;"
                                       clearable>
                                <el-option
                                        v-for="item in areaoptions"
                                        :key="item.resId"
                                        :label="item.resName"
                                        :value="item.resId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-table
                    ref="multipleTable"
                    :data="equdata"
                    tooltip-effect="dark"
                    style="width: 100%"
                    @selection-change="handleSelectionEquChange">
                <el-table-column
                        type="selection"
                        width="60">
                </el-table-column>
                <el-table-column
                        prop="equ"
                        label="区域/设备"
                        show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span>{{scope.row.resName }}/{{scope.row.doorNm}}/{{scope.row.eqpNm}}</span>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
     		    <zl-button :loading="staLoading" @click="operInstanceEqu('form')"/>
            </span>
        </el-dialog>
    </d2-container>
</template>

<script>
    import {getPageList, typePullDown,RegPulldown,getList,saveOrUpdataList,deleteList,areaPullDown,equipmentList,registerById,sendCard} from "../../../../api/visitor/set/card";
    import endTm from "./components/endTm"
    import {tableOptions} from "../../../../assets/options";

    export default {
        name: "visitor-manage",
        components:{
            endTm
        },
        data() {
            let checkName =(rule, value, callback)=>{
                let reg = /^[\u4e00-\u9fa5]{1,15}$/
                if(!reg.test(value)){
                    return callback(new Error("访客类型名称不能超过15位"))
                }else {
                    callback()
                }
            }
            return {
                // allname:[],
                // list: [],
                staLoading:false,
                diaLogName: '新增',
                areaoptions:[],
                nameoptions:[],
                options: [],
                time: [],
                loading: false,
                tableOptions,
                operVisible: false,
                isEdit: false,
                selection: [],
                multipleSelection: [],
                currentPage: 1,
                pagination: {
                    total: 0
                },
                filter: {
                    id: '',
                    cardNo: '',
                    visitorName: '',
                    typeName: '',
                    typeId: '',
                    cardState: '',
                    useState: '',
                    pageSize: 10,
                    pageNum: 1,
                },
                data: [],
                equdata:[],
                columns: [
                    {
                        title: '卡号',
                        key: 'cardNo',
                        minWidth: '100',
                        showOverflowTooltip: true
                    },
                    {
                        title: '序列号',
                        key: 'cardSequence',
                        minWidth: '100',
                        showOverflowTooltip: true
                    },
                    {
                        title: '访客姓名',
                        key: 'visitorName',
                        minWidth: '100',
                        showOverflowTooltip: true
                    },
                    {
                        title: '访客类型',
                        key: 'typeName',
                        minWidth: '100',
                        showOverflowTooltip: true
                    },
                    {
                        title: '卡状态',
                        key: 'cardState',
                        minWidth: '100',
                        showOverflowTooltip: true,
                        formatter(row, column, cellValue, index) {
                            if (cellValue === '1') {
                                return '有效'
                            } else if (cellValue === '2') {
                                return '失效'
                            }
                        }
                    },
                    {
                        title: '失效时间',
                        key: 'expirationDate',
                        minWidth: '100',
                        showOverflowTooltip: true
                    },
                    {
                        title: '权限信息',
                        key: 'areaId',
                        minWidth: '200',
                        showOverflowTooltip: true
                    },
                    {
                        title: '通行时段',
                        key: 'bgTm',
                        minWidth: '100',
                        showOverflowTooltip: true,
                        component: {
                            name: endTm
                        }
                    },
                    {
                        title: '使用状态',
                        key: 'useState',
                        minWidth: '100',
                        showOverflowTooltip: true,
                        formatter(row, column, cellValue, index) {
                            if (cellValue === '1') {
                                return '未使用'
                            } else if (cellValue === '2') {
                                return '使用中'
                            }
                        }
                    },
                ],
                rowHandle: {
                    columnHeader: '操作',
                    minWidth: '250',
                    align: 'left',
                    custom: [
                        {
                            text: '发卡',
                            type: 'primary',
                            size: 'small',
                            emit: 'send',
                            show(index, row) {
                                if (row.useState === '1' && row.cardState === '1') {
                                    return true
                                } else
                                    return false
                            }
                        },
                        {
                            text: '编辑',
                            type: 'primary',
                            size: 'small',
                            emit: 'edit',
                            show(index, row) {
                                if (row.useState === '1') {
                                    return true
                                } else
                                    return false
                            }
                        },
                        {
                            text: '删除',
                            type: 'danger',
                            size: 'small',
                            emit: 'delete',
                            show(index,row){
                                if (row.useState === '1') {
                                    return true
                                } else
                                    return false
                            }
                        }
                    ]
                },
                id: [],
                form: {
                    visitorName: '',
                    typeId: '',
                    expirationDate: '',
                    cardState: '',
                    bgTm: '',
                    endTm: '',
                    areaId: '',
                    cardSequence: '',
                    visitorNo: '',
                    cardNo: '',
                    id:'',
                    resId:'',
                    visitorId:'',
                },
                serialNo:[],
                expireTimeOption: {
                    disabledDate(date) {
                        return date.getTime() < Date.now() - 8.64e7;
                    }
                },
                rules: {
                    visitorName:[{ required: true,validator:checkName, trigger: 'blur' }],
                    expirationDate:[{ required: true, message: '请选择失效时间', trigger: 'change' }],
                    typeId:[{ required: true, message: '请选择访客类型', trigger: 'change' }],
                    bgTm:[{ required: true, message: '请选择起始时间', trigger: 'change' }],
                    endTm:[{ required: true, message: '请选择结束时间', trigger: 'change' }],
                    resId:[{ required: true, message: '请选择所属区域', trigger: 'change' }]
                },
            }
        },
        methods: {
            handleList(val) {
                if (val) {
                    this.filter.pageNum = 1
                    this.currentPage = 1
                }
                this.loading = true
                getPageList(this.filter).then(res => {
                    this.loading = false
                    this.data = res.page.list
                    this.pagination.total = res.page.total
                }).catch(err => {
                    this.loading = false
                })
            },
            onMutilSendClick() {
                if(!this.selection.length){
                    this.$message({
                        message:'请选择记录',
                        type:'success'
                    })
                }
                this.selection.forEach((item,index)=>{
                    this.id.push(item.id)
                })
                this.id=this.id.join(",")
                this.sendcard(this.id)
            },
            handleRowSendcard({index,row}) {
                this.sendcard(row.id)
            },
            sendcard(id){
                this.$confirm(`确认发出对应访客卡`, '确认操作', {
                    confirmButtonText: '确定',
                    cancelButtonText: '放弃',
                    type: 'warning'
                }).then(() => {
                    sendCard({id}).then(res=>{
                        this.$message({
                            message: '发卡成功',
                            type: 'success'
                        })
                        this.handleList()
                    })
                })
            },
            onMutilDelClick() {
                if(!this.selection.length){
                    this.$message({
                        message:'请选择记录',
                        type:'success'
                    })
                }
                this.selection.forEach((item,index)=>{
                    this.id.push(item.id)
                })
                this.id=this.id.join(",")
                this.delete(this.id)
            },
            handleRowDelete({index,row}){
                this.delete(row.id)
            },
            delete(id) {
                this.$confirm(`确定要删除吗?`, '确认操作', {
                    confirmButtonText: '确定',
                    cancelButtonText: '放弃',
                    type: 'warning'
                }).then(() => {
                    deleteList({id}).then(res=>{
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                        this.handleList()
                    })
                })
            },
            handleRowEdit({index,row}) {
                this.isEdit=true
                this.diaLogName='编辑'
                let id=row.id
                getList({id}).then(res=>{
                    this.form=res.visitorCardVO
                    this.form.resId=res.visitorCardVO.resId
                    this.equdata=res.visitorCardVO.list
                    this.form.resId = res.visitorCardVO.list[0].resId
                    this.$nextTick(()=>{
                        let rows=res.visitorCardVO.list
                        rows.forEach(row => {
                            this.$refs.multipleTable.toggleRowSelection(row);
                        });
                    })
                    this.operVisible=true
                })
            },
            handleSelectionEquChange(selection){
                this.multipleSelection = selection
            },
            handleSelectionChange(selection) {
                this.selection = selection
            },
            handleCurrentChange(val) {
                this.filter.pageNum = val
                this.handleList()
            },
            handleSizeChange(val) {
                this.filter.pageNum = 1
                this.filter.pageSize = val
                this.handleList()
            },
            type() {
                typePullDown().then(res => {
                    this.options = res.list
                })
            },
            area(){
                areaPullDown().then(res=>{
                    this.areaoptions=res.listPullDown
                })
            },
            clearForm() {
                this.form={
                    visitorName: '',
                    typeId: '',
                    expirationDate: '',
                    cardState: '',
                    bgTm: '',
                    endTm: '',
                    areaId: '',
                    cardSequence: '',
                    visitorNo: '',
                    cardNo: '',
                    resId:'',
                    equdata:[],
                    visitorId:'',
                }
                this.serialNo=[]
                this.isEdit = false
                this.diaLogName = '新增'
            },
            operInstanceEqu(){
                if(!this.multipleSelection.length){
                    this.$message({
                        message:'请选择记录',
                        type:'success'
                    })
                }else {
                    this.multipleSelection.forEach((item,index)=>{
                        this.serialNo.push(item.serialNo)
                    })
                    this.serialNo=this.serialNo.join(",")
                    this.form.areaId=this.serialNo
                    this.$refs['form'].validate((valid)=>{
                        if (valid){
                            this.staLoading=true
                            saveOrUpdataList(this.form).then(res=>{
                                this.staLoading=false
                                this.operVisible=false
                                this.$message({
                                    message: this.form.id ? '编辑成功':'新增成功',
                                    type: 'success'
                                })
                                this.handleList()
                            }).catch(err=>{
                                this.staLoading=false
                            })
                        }
                    })
                }
            },
            //queryString 为在框中输入的值
            //callback 回调函数,将处理好的数据推回
            querySearchName(queryString, callback){
                this.form.visitorNo='';
                var list = [{}];
                //从后台获取到对象数组
                RegPulldown({queryString}).then((res)=>{
                    //在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
                    for(let i of res.list){
                        i.value =i.visitorName;  //将想要展示的数据作为value
                    }
                    list = res.list;
                    callback(list);
                }).catch((error)=>{
                    console.log(error);
                });
            },
            handleSelect(item) {
                let id=item.id
                this.form.visitorId = item.id
                registerById({id}).then(res=>{
                    this.form.visitorNo=res.visitorRegisterVO.identityNo
                })
            }
        },
        watch: {
             // 'form.visitorName': function (val) {
            //    let id=this.list[0].id
            //    registerById({id}).then(res=>{
            //        this.form.visitorNo=res.visitorRegister.identityNo
            //    })
            // },
            'form.resId': function (val) {
                 if(this.form.resId === ''){
                     this.equdata=[]
                 }
                if(this.form.resId != '' && this.form.resId !=undefined){
                    equipmentList({resId: this.form.resId}).then(res => {
                        this.equdata = res.list
                    })
                }
            },
            'form.expirationDate':function (val) {
                var date = new Date(val)
                let start = Date.now();
                if ( date > start ) {
                    this.form.cardState = '1'
                }

            }
        },
        mounted() {
            this.filter.pageSize = this.tableOptions.pageList[0]
            this.tableOptions = this.$calcTableHeight(tableOptions, 88)
            this.handleList()
            this.type()
            this.area()
        }
    }
</script>

<style scoped>

</style>
