<template>
  <d2-container>
    <div class="d2-table-view-full">
      <div class="d2-table-view-header">
        <el-form label-width="90px" labelPosition="center" size="small" :inline="true" :model="filter" @keyup.enter.native="handleList" class="demo-form-inline">
          <el-form-item label="补卡日期">
            <el-date-picker
                    v-model="time"
                    type="datetimerange"
                    value-format="yyyy-MM-dd HH:mm:ss"
										:default-time="['00:00:00', '23:59:59']"
                    @change="dateChange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"> 
            </el-date-picker>
          </el-form-item>
          <el-form-item label="补卡单号">
						<el-input v-model="filter.registrNo" clearable/>
          </el-form-item>
          <el-form-item label="申请人">
            <el-input v-model="filter.userNm" clearable/>
          </el-form-item>
				<!-- 	<el-form-item label="工号">
						<el-input v-model="filter.empCode"/>
					</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  :disabled="isDisabled"  size="small" @click="onMutilDelClick()">批量删除</el-button>
				</div>
        <d2-crud
                title="补卡登记列表"
                ref="d2Crud"
                :loading="loading"
                :columns="columns"
                :data="data"
                :options="tableOptions"
								:rowHandle="rowHandle"
								@delete="handleRowRemove"
								selection-row
								@selection-change="handleSelectionChange">
				</d2-crud>
      </div>
      <div class="d2-table-view-footer">
        <el-pagination
        				@current-change="handleCurrentChange"
        				@size-change="handleSizeChange"
                :current-page.sync="currentPage"
        				:page-size="tableOptions.pageList[0]"
        				:page-sizes="tableOptions.pageList"
        				layout="total,sizes, prev, pager, next,jumper"
        				:total="pagination.total">
        </el-pagination>
      </div>
    </div>
				<el-dialog
								:title="diaLogName"
								:visible.sync="operVisible"
								@close="clearForm"
								width="700px"
								:close-on-click-modal="false">
					<el-form ref="form" :model="form" label-width="80px" labelPosition="right"  :rules="rules" >
						<el-row :gutter="20">
							<el-col :span="24">
							<el-form-item label="" >
							<el-radio change="clear" style="margin-left: 38%;" v-model="form.lsTerm" label="0">学生</el-radio>
							<el-radio change="clear" v-model="form.lsTerm" label="1">教工</el-radio>
							</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="补卡类型" prop="regType">
									<custom-select :value="form.regType"  v-model="form.regType" typeName="补卡类型" placeholder="补卡类型" clearable style="width: 100%;"/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="申请人" prop="empName">
								<!-- 	<saff-tree :str="form.empName" v-model="form.empId" ref="saffTree"/> -->
								<staff-tree  ref="saffTree" :depType="type" :strr="form.userNm" v-model="form.userId" ></staff-tree>
								</el-form-item>
							</el-col>
							<!-- <el-col :span="12">
								<el-form-item label="岗位">
									<el-input disabled v-model="form.work" clearable/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="部门">
									<el-input disabled v-model="form.orgId" clearable/>
								</el-form-item>
							</el-col> -->
							<el-col :span="12">
								<el-form-item label="补卡日期" prop="startTime">
									<el-date-picker
												v-model="form.startTime"
												type="date"
												placeholder="选择日期"
												value-format="yyyy-MM-dd"
											  :picker-options="pickerOptions"
												style="width: 100%;">
											</el-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="24" style="margin-top: 20px;">
								<el-form-item label="补卡原因" prop="remarks">
									<el-input type="textarea" maxlength="30" v-model="form.remarks" clearable/>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
					<div class="time-selects">
					<div v-for="(item,index) in arr" :key="index">
						<span class="time-name">{{item.name}}</span>
							<el-time-select
								style="width: 255px;margin-top: 10px;"
								v-model="item.time"
								:picker-options="{
								start: '00:00',
								step: '00:01',
								end: '23:59'
									}"
							placeholder="选择时间">
							</el-time-select>
					</div>
					</div>
					<span slot="footer" class="dialog-footer">
				<zl-button :loading="regLoading" @click="operInstance()" />   
				</span>
		</el-dialog>
  </d2-container>
</template>
<script>
  import {getCardRegistrByPage,saveCardRegistr,delCardRegistrById} from '../../../api/att/registr'
  import { tableOptions } from '../../../assets/options'
	//import SaffTree from './components/saffTree'
	import leaveTimeDel from './components/leaveTimeDel'
  export default {
    name: 'attendance-registr',
		components:{
			//SaffTree,
			leaveTimeDel
		},
    data () {
      return {
				isDisabled:false,
				regLoading:false,
				func:{
					select:false,
					add:false,
					delete:false
				},
				  pickerOptions: {
            disabledDate(time) {
							 return time.getTime() > Date.now()
							}
        },
				diaLogName:'申请补卡',
				operVisible:false,
        time: '',
				time_1: '',
        loading: false,
        tableOptions,
        currentPage:1,
        filter: {
					userNm:'',	
					registrNo:'',	
					startTime:'',	
					endTime:'',
          pageSize: 10,
          pageNum: 1
        },
				selection:[],
				registrId:[],
				registrNo:[],
				type:'student',
				form:{
					lsTerm:'0',
					registrNo:'',
					regType:'',
					registrId:'',
					startTime:'',
					endTime:'',
					remarks:'',
					work:'',
					orgId:'',
					empName:'',
					id:'',
					userId:'',
					transTime:'',
				},
				arr:[{name:'开始时间:',time:''},{name:'结束时间:',time:''},{name:'开始时间:',time:''},{name:'结束时间:',time:''},
				{name:'开始时间:',time:''},{name:'结束时间:',time:''}],
        pagination: {
          total: 0
        },
        columns: [
          {
            title: '序号',
            key: 'index',
            minWidth: '50',
            formatter (row, column, cellValue, index) {
              return index+1
            }
          },
          {
            title: '补卡单号',
            key: 'registrNo',
            minWidth: '150',
					  showOverflowTooltip: true
          },
          {
            title: '申请人',
            key: 'userNm',
            minWidth: '100',
          },
					/* {
					  title: '工号',
					  key: 'empCode',
					  minWidth: '100',
					}, */
          {
            title: '所属部门',
            key: 'depNm',
            minWidth: '120',
          },
          {
            title: '补卡类别',
            key: 'typeName',
            minWidth: '90'
          },
          {
            title: '补卡日期',
            key: 'startTime',
            minWidth: '180',
						/* component: { 
							name: leaveTimeDel,
						 }, */
						 showOverflowTooltip: true
          },
					/* {
					  title: '补卡时段',
					  key: 'transTimes',
					  minWidth: '180',
						showOverflowTooltip: true
					}, */
					/* {
					  title: '登记日期',
					  key: 'createDate',
					  minWidth: '180'
					}, */
					{
						title: '登记人',
						key: 'creatorNm',
						minWidth: '150',
						showOverflowTooltip: true
					}
        ],
				rowHandle: {
					columnHeader: '操作',
					minWidth: '90',
					align: 'center',
					custom: [
						{
							text: '删除',
							type: 'danger',
							size: 'small',
							emit: 'delete'
						}
					],
        },
        data: [],
				 
						rules: {
							regType:[{ required: true, message: '请选择补卡类型', trigger: 'change' }],
							startTime:[{ required: true, message: '请选择补卡日期', trigger: 'change' }]
					}
 
      }
    },
		watch: {
			'form.empId':function(val){
				if(val !='' && val != undefined){
					this.form.empId=val
					getPortionByEmpId(this.form).then(res => {
						/* this.form.work=res.data.postName
						this.form.orgId=res.data.orgName */
					})
				}
			},
			 'operVisible':function(val){
			 	this.form.startTime=new Date()
			 	this.form.startTime=this.form.startTime.format('yyyy-MM-dd')
			 },
			  'form.lsTerm':function(val){
			  	this.$nextTick(() => {
			  	this.$refs.saffTree.cleanName()
			  	});
			  	if(val === '1'){
			  		this.type = 'teacher'
			  	}else if(val === '0'){
			  		this.type = 'student'
			  	}
			  }
		},
    methods: {
      handleList (val) {
        if(val){this.filter.pageNum=1
        this.currentPage = 1}
      this.loading = true
        getCardRegistrByPage(this.filter).then(res => {
          this.loading = false
          this.data = res.page.list
          this.pagination.total = res.page.total
        }).catch(err => {
          this.loading = false
        })
      },
      handleCurrentChange (val) {
        this.filter.pageNum = val
        this.handleList()
      },
			handleSizeChange (val) {
			this.filter.pageNum = 1
			this.filter.pageSize = val
			this.handleList()
			},
      dateChange (val) {
       if(val == null){
       	this.filter.startTime = ''
       	this.filter.endTime = ''
       }else{
       	this.filter.startTime = val[0] 
       	this.filter.endTime = val[1]
       }
      },
			operInstance(){
				 if(this.isRepeat(this.arr)){
						this.$message({
							message: '不能有重复的时间段',
							type: 'error'
						})
						return false
					}else{
					  for(var i=0;i<this.arr.length;i++){
					  	if(this.arr[i].time == null){
					  		this.arr[i].time =''
					  	} 
							if(this.arr[i].time !=''){
								this.form.transTime=this.form.transTime+","+this.arr[i].time
							}
					  }
					  this.form.transTime=this.form.transTime.substring(1,this.form.transTime.length)
					  this.$refs['form'].validate((valid) => {
					  	if (valid) {
					  		if(this.form.userId == '' || this.form.transTime == ''){
					  			this.$message({
					  				message: this.form.userId == ''? '请选择申请人':'请选择开始时间',
					  				type: 'error'
					  			})
					  			return false
					  		}else{
									this.regLoading=true
					  			saveCardRegistr(this.form).then(res => {
					  				this.operVisible = false
										this.regLoading=false
					  				this.$message({
					  					message: this.form.id == ''?'新增成功':'编辑成功',
					  					type: 'success'
					  				})
					  				 this.loading=false
					  				this.handleList()
					  			}).catch(err => {
											 this.regLoading=false
										})
					  		}
					  	}
					  	})	
					}
				    
					
			},
			//判断数组是否有重复数据
	  isRepeat(arr){
    var arrList=[]
		for(var i=0;i<arr.length;i++){
			if(arr[i].time != ""){
				arrList.push(arr[i].time)
			}
		}
		var s = arrList.join(",")+",";
  for(var i=0;i<arrList.length;i++) {
    if(s.replace(arrList[i]+",","").indexOf(arrList[i]+",")>-1) {
        return true
    }else{
			  return false
		}
}
		},
			handleRowRemove({row,index}){
				this.delete(row.registrId,row.registrNo)
			},
				handleSelectionChange (selection) {
			  this.selection = selection
			},
			 onMutilDelClick(){
				 	this.isDisabled = true
				 setTimeout(() => {
				   this.isDisabled = false
				 }, 2000)
			  if(!this.selection.length){
			    this.$message({
			      message: '请选择记录',
			      type: 'success'
			    })
					return false
			  } 
				this.registrId=[]
				this.registrNo =[]
				 this.selection.forEach((item,index)=>{
				 this.registrId.push(item.registrId)
				 this.registrNo.push(item.registrNo)
			 })
			 this.registrId=this.registrId.join(",")
			 this.registrNo = this.registrNo.join(",")
			 this.delete(this.registrId,this.registrNo)
			},
			delete(registrIds,registrNos){
				this.$confirm('确定删除此记录?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'error'
				}).then(() => {
					delCardRegistrById({
						registrIds,registrNos
					}).then(res=>{
						this.$message({
							message: '删除成功',
							type: 'success'
						})
						this.handleList()
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});          
				});
			},
			clearForm(){
				this.regLoading=false
				this.diaLogName='申请补卡'
				/* this.$nextTick(() => {
				this.$refs.saffTree.cleanName()
				}); */
				this.form={
					lsTerm:'0',
					registrNo:'',
					regType:'',
					registrId:'',
					startTime:'',
					endTime:'',
					remarks:'',
					work:'',
					orgId:'',
					empName:'',
					id:'',
					userId:'',
					transTime:'',
				},
				this.arr=[{name:'开始时间:',time:''},{name:'结束时间:',time:''},{name:'开始时间:',time:''},{name:'结束时间:',time:''},
				{name:'开始时间:',time:''},{name:'结束时间:',time:''}]
			},
				/* getFunction () {
			  this.$GetFunction({
			    menuUrl:this.$route.path
			  }).then(res=>{
			    res.data.forEach(item=>{
			      if (item.functionType === 'add') {
			        if (item.remarks === 'true') {
			          this.func.add = true
			        } else {
			          this.func.add = false
			        }
			      } else if(item.functionType === 'select') {
			        if (item.remarks === 'true') {
			          this.func.select = true
			        } else {
			          this.func.select = false
			        }
			      } else if(item.functionType === 'delete') {
			        if (item.remarks === 'true') {
			          this.$set(this.rowHandle,'custom',[
			            {
			              text: '删除',
			              type: 'danger',
			              size: 'small',
			              emit: 'delete'
			            }
			          ])
			        }
			      }
			    })
			  })
			} */
			
    },
    mounted () {
			//this.getFunction()
      this.time = this.$setInitTime()
			this.form.startTime=new Date()
			this.form.startTime=this.form.startTime.format('yyyy-MM-dd')
      this.filter.startTime = this.time[0].format('yyyy-MM-dd hh:mm:ss')
      this.filter.endTime = this.time[1].format('yyyy-MM-dd hh:mm:ss')
			this.filter.pageSize = this.tableOptions.pageList[0]
      this.tableOptions = this.$calcTableHeight(tableOptions,102)
      this.handleList()
    }
  }
</script>
<style>
	.time-selects {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: flex-start;
		align-items: center;
		width: 100%;
	}
	.time-name{
	  display: inline-block;
		width: 60px;
		margin:20px 0px 0px 15px;
	}
	 
</style>