<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.shiftsCode" placeholder="班次编号" clearable/>
		  </el-form-item>
		  <el-form-item label="班次名称">
			<el-input v-model="filter.shiftsName" placeholder="班次名称" clearable/>
		  </el-form-item>
		  <el-form-item label="班次性质">
			 <custom-select typeName="班次类型" v-model="filter.shiftsType" :isAll="true" :value="filter.shiftsType"></custom-select>
		  </el-form-item>
			<el-form-item label="部门">
			 <department-tree v-model="filter.depId" @clearInput="clear"></department-tree>
			</el-form-item>
		  <el-form-item>
			<el-form-item label="是否套用" prop="cover">
			  <el-select v-model="filter.cover" placeholder="请选择" clearable>
				<el-option label="是" value="0"></el-option>
				<el-option label="否" value="1"></el-option>
			  </el-select>
			</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" :disabled="isDisabled" @click="onMutilDelClick">批量删除</el-button>
			</div>
		<d2-crud
				title="班次列表"
				ref="d2Crud"
				:loading="loading"
				:columns="columns"
				:data="data"
				:rowHandle="rowHandle"
				@edit="handleRowEdit"
				@delete="handleRowRemove"
				:options="tableOptions"
				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="935px"
			: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="8">
		<el-form-item label="班次编号" prop="shiftsCode">
		  <el-input v-model="form.shiftsCode" placeholder="班次编号" clearable :disabled="falg" maxlength="6"/>
		</el-form-item>
		</el-col>
		<el-col :span="8">
		<el-form-item label="班次名称" prop="shiftsName">
		  <el-input maxlength="30" v-model="form.shiftsName" placeholder="班次名称" clearable/>
		</el-form-item>
		</el-col>
		<el-col :span="8">
		<el-form-item label="实际工时"  >
		  <el-input v-model="form.numHrs" placeholder="实际工时" clearable :disabled="true"/>
		</el-form-item>
		</el-col>
			<el-col :span="8">
		<el-form-item label="班次性质" prop="shiftsType">
		 <custom-select typeName="班次类型" v-model="form.shiftsType"  :value="form.shiftsType"></custom-select>
		</el-form-item>
		</el-col>
		<el-col :span="8">
		<el-form-item label="计划工时" prop="workHrs"  >
		  <el-input v-model.number="form.workHrs" placeholder="计划工时" maxlength="4" clearable />
		</el-form-item>
		</el-col>
		<el-col :span="8">
		<el-form-item label="要求工时" prop="needHrs"  >
		  <el-input v-model.number="form.needHrs" placeholder="要求工时" maxlength="4" clearable />
		</el-form-item>
		</el-col>
		<el-col :span="8">
		<el-form-item label="是否套用" prop="cover">
		  <el-select v-model="form.cover" placeholder="请选择" clearable>
			<el-option label="否" value="0"></el-option>
			<el-option label="是" value="1"></el-option>
		  </el-select>
		</el-form-item>
		</el-col>
		<el-col :span="8">
		<el-form-item label="部门" prop="cover">
		 <department-tree v-model="form.depId" :str="form.depNm" @clearInput="clear" :isClear="true"></department-tree>
		</el-form-item>
		</el-col>
		<!-- <el-form-item label="班组选择" prop="teamId">
		<el-select v-model="form.teamId" placeholder="请选择" clearable> 
		<el-option v-for="item in list" :key="item.teamName" :label="item.teamName" :value="item.teamId">
		</el-option> 
		</el-select>
		</el-form-item> -->
		</el-row>
		</el-form>
		<el-table
				:data="form.shiftsDetailList"
				style="width: 100%">
				<el-table-column label="">
				<el-table-column
						prop="seq"
						label="序号"
						width="60">
					<template slot-scope="scope">
					<el-input  size="small" v-model="scope.row.seq" />
					</template>
				</el-table-column>
				</el-table-column>
				<el-table-column label="">
				<el-table-column
						prop="seq"
						label="加班"
						width="90">
					<template slot-scope="scope">
					<el-select size="small" v-model="scope.row.isOvertime" placeholder="请选择" clearable>
						<el-option label="是" value="0"></el-option>
						<el-option label="否" value="1"></el-option>
					</el-select>
					</template>
				</el-table-column>
				</el-table-column>
		  <el-table-column label="上班卡" align="center">
			<el-table-column
					prop="workBefore"
					label="提前"
					width="120">
			  <template slot-scope="scope">
				<el-input size="small" v-model="scope.row.workBefore" placeholder="提前时间(分钟)"></el-input>
			  </template>
			</el-table-column>
			<el-table-column
					prop="workSignon"
					label="签到"
					width="150">
			  <template slot-scope="scope">
				<el-time-select
				size="small"
        v-model="scope.row.workSignon"
       :picker-options="{
         start: '00:00',
         step: '00:01',
         end: '23:59'
        }"
     placeholder="选择时间" >
</el-time-select>
			  </template>
		  </el-table-column>
		</el-table-column>
		  <el-table-column label="下班卡" align="center">
			<el-table-column
					prop="workSignoff"
					label="签退"
					width="150">
			  <template slot-scope="scope">
				<el-time-select
				        size="small"
				        v-model="scope.row.workSignoff"
				       :picker-options="{
				         start: '00:00',
				         step: '00:01',
				         end: '23:59'
				        }"
				     placeholder="选择时间" >
				</el-time-select>
			  </template>
			</el-table-column>
			<el-table-column
					prop="workWait"
					label="推迟"
					width="120">
			  <template slot-scope="scope">
				<el-input size="small" v-model="scope.row.workWait" placeholder="推迟时间(分钟)"/>
			  </template>
			</el-table-column>
		  </el-table-column>
		  <el-table-column label="计算">
			<el-table-column
					prop="detailWorkHrs"
					label="工时"
					width="100">
			  <template slot-scope="scope">
				<el-input size="small" v-model="scope.row.detailWorkHrs" placeholder="工时" @focus="workhrs"/>
			  </template>
			</el-table-column>
			<el-table-column
					prop="detailNeedHrs"
					label="要求工时"
					width="105">
			  <template slot-scope="scope">
				<el-input size="small" v-model="scope.row.detailNeedHrs" placeholder="要求工时" @focus="workhrs"/>
			  </template>
			</el-table-column>
		  </el-table-column>
		</el-table>
	  <span slot="footer" class="dialog-footer">
			<zl-button :loading="shiftLoading" @click="operInstance('form')"/> 
		</span>
	</el-dialog>
  </d2-container>
</template>
<script>
  import { tableOptions } from '../../../assets/options'
  import {getShiftsList,delShiftsById,saveOrUpdataShifts,getShiftsById,findShiftsByCode} from '../../../api/att/shift'
  export default {
    name: 'attendance-shift',
    data () {
			 let checkUserNo = (rule, value, callback) => {
			  let reg = /^\w+$/;
			  if (!reg.test(value)) {
			    return callback(new Error("请输入由数字或字母组成的正确编号"));
			  } else {
			    callback();
			  }
			};
			let checkWorkHrs = (rule, value, callback) => {
			let reg = /^[+]?\d+(\.\d+)?$/
			 if(!reg.test(value)){
				return callback(new Error('由4位以下数字组成'))
			}else{
				callback ()
			}
			}
      return {
				isDisabled:false,
				shiftLoading:false,
				func:{
					select:false,
					update:false,
					add:false,
					delete:false
				},
				selection:[],
				shiftsId:[],
				list:[],
				count:0,
				falg:false,
        operVisible: false,
        diaLogName: '新增',
        data: [],
        currentPage:1,
        tableOptions,
        loading: false,
				sum:0,
        filter: {
          shiftsCode: '',
          shiftsName: '',
          shiftsType:null,
          workHrs: '',
					depId:'',
					needHrs:'',
					cover:'',
          pageSize: 10,
          pageNum: 1
        },
        pagination: {
          total: 0
        },
        columns: [
						{
						   title: '序号',
						key: 'index',
						minWidth: '50',
						formatter (row, column, cellValue, index) {
						  return index+1
						}
					},
          {
            title: '班次编号',
            key: 'shiftsCode',
            minWidth: '150'
          },
          {
            title: '班次名称',
            key: 'shiftsName',
            minWidth: '150'
          },
					 {
					  title: '所属部门',
					  key: 'depNm',
					  minWidth: '150'
					},
          {
            title: '班次性质',
            key: 'typeNm',
            minWidth: '150',
					/* 	formatter(row, column, cellValue, index) {
							 if(cellValue ===0){
								 return '0次打卡'
							 }else if(cellValue ===1){
								 return '1次打卡'
							 }else if(cellValue === 2){
								 return '2次打卡'
							 }else if(cellValue === 4){
								 return '4次打卡'
							 }else if(cellValue ===6){
								 return '6次打卡'
							 }
						} */
          },
						{
					  title: '工时',
					  key: 'workHrs',
					  minWidth: '100'
					},
          {
            title: '要求工时',
            key: 'needHrs',
            minWidth: '100'
          },
					{
					  title: '是否套用',
					  key: 'cover',
					  minWidth: '100',
						formatter(row, column, cellValue, index) {
							 if(cellValue ==='0'){
								 return '是'
							 }else if(cellValue ==='1'){
								 return '否'
							 }
						}
					},
					{
					  title: '时间段',
					  key: 'timeSlot',
					  minWidth: '200'
					}
        ],
        form: {
					shiftsCode:'',
					shiftsName:'',	
					shiftsType:'',	
					workHrs:'',	
					numHrs:'10',	
					needHrs:'',	
					sffd:'',
					depId:'',
					depNm:'',
					shiftsId:'',
					teamId:'',
          shiftsDetailList: [
            {
							seq:'1',
							isOvertime:'1',
              workBefore: '60',
              workSignon: '08:00',
              workSignoff: '18:00',
              detailWorkHrs: '10',
              workWait: '60',
							detailId:'',
							detailNeedHrs:'8'
            },
            {
						 seq:'2',
						 isOvertime:'1',
             workBefore: '',
             workSignon: '',
             workSignoff: '',
             detailWorkHrs: '',
             workWait: '',
						 detailId:'',
						 detailNeedHrs:''
            },
            {
						 seq:'3',
						 isOvertime:'1',
             workBefore: '',
             workSignon: '',
             workSignoff: '',
             detailWorkHrs: '',
             workWait: '',
						 detailId:'',
						 detailNeedHrs:''
            }
          ]
        },
        rowHandle: {
          columnHeader: '操作',
          minWidth: '250',
          align: 'center',
           custom: [
            {
              text: '编辑',
              type: 'primary',
              size: 'small',
              emit: 'edit'
            },
            {
              text: '删除',
              type: 'danger',
              size: 'small',
              emit: 'delete'
            }
          ], 

        },
				  rules: {
				    shiftsCode: [{ validator:checkUserNo,required: true, trigger: 'blur' }],
						shiftsType: [{ required: true, message: '请输入班次性质', trigger: 'change' }],
						shiftsName:[{ required: true, message: '请输入班次名称', trigger: 'blur' }],
			      workHrs:[{ validator:checkWorkHrs, required: true, trigger: 'blur' }],
						needHrs:[{validator:checkWorkHrs, required: true, trigger: 'blur'}]
				  },
      }
    },
    methods: {
      handleList (val) {
        if(val){this.filter.pageNum=1
        this.currentPage = 1}
        this.loading = true
        getShiftsList(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()
			 },
			 clear(){
				 this.filter.depId = ''
			 },
      //新增，修改班次
      operInstance (formName) {
				this.$refs[formName].validate((valid) => {
						if (valid) {
						for (var i = 0; i < this.form.shiftsDetailList.length; i++) {
							if(this.form.shiftsDetailList[i].workSignon == null){
								this.form.shiftsDetailList[i].workSignon=''
							}
							if(this.form.shiftsDetailList[i].workSignoff == null){
								this.form.shiftsDetailList[i].workSignoff=''
							} 
							if(this.form.shiftsDetailList[i].workSignon == '' && this.form.shiftsDetailList[i].workSignoff != ''){
									this.$message({
										message: '请打上班卡',
										type: 'success'
									})
									return false
							}
							if(this.form.shiftsDetailList[i].workSignon != '' && this.form.shiftsDetailList[i].workSignoff != ''){
								if(this.form.shiftsDetailList[i].detailWorkHrs == ''){
									this.$message({
										message: '请点击获取计算工时',
										type: 'success'
									})
									return false
								}
							}
						}
							this.shiftLoading=true
							let shiftsCode = this.form.shiftsCode
							let shiftsId = this.form.shiftsId
								findShiftsByCode({shiftsCode,shiftsId}).then(res => {
									 if(res.msgCd === '1'){
										 this.$message({
										 	message:res.msgDat,
										 	type: 'error'
										 })
										 return false
									 }else{
										 saveOrUpdataShifts(this.form).then(res => {
										 	this.operVisible = false
										 	this.shiftLoading=false
										 	this.$message({
										 		message:this.form.shiftsId == ''?'新增成功':'编辑成功',
										 		type: 'success'
										 	})
										 	this.handleList()
										 }).catch(err => {
										  this.shiftLoading=false
										 })
									 }
									}).catch(err => {
							     this.shiftLoading=false
							})
						
						} else {
							console.log('error submit!!');
							return false;
						}
					});
      },
			//计算工时
			workhrs(){
					this.form.numHrs=0
					for (var i = 0; i < this.form.shiftsDetailList.length; i++) {
							if (this.form.shiftsDetailList[i].workSignon != '' && this.form.shiftsDetailList[i].workSignoff != '') {
								var str = this.form.shiftsDetailList[i].workSignon.split(':')
								var str1 = this.form.shiftsDetailList[i].workSignoff.split(':')
								if(str1[0]<str[0]){
									 var h = parseFloat(str1[0])+24-parseFloat(str[0])
									 var m = str1[1] - str[1]
								}else{
									var h = str1[0]-str[0]
									var m = str1[1] - str[1]
								}
								if(m<0){
									m=m+60
									h=h-1
								}
								m=m/60+''
								console.log(m)
								if(m.length>4){
									m=m.substring(2,4)
								}else{
									m=m.substring(2,m.length)
								}
								if(m==''){
									this.form.shiftsDetailList[i].detailWorkHrs=h
								}else{
									this.form.shiftsDetailList[i].detailWorkHrs=h+"."+m
								}
								this.form.numHrs=this.form.numHrs+parseFloat(this.form.shiftsDetailList[i].detailWorkHrs)
							}
						
					}
			},
      handleRowEdit ({index, row}) {
				this.diaLogName='编辑'
				 this.falg=true
				 let shiftsId = row.shiftsId
				 getShiftsById({shiftsId}).then(res => {
					  this.operVisible=true
						//this.form = res.shifts
						this.form.shiftsId=res.shifts.shiftsId
						this.form.shiftsCode=res.shifts.shiftsCode
						this.form.shiftsName=res.shifts.shiftsName
						this.form.shiftsType=res.shifts.shiftsType
						this.form.workHrs=res.shifts.workHrs
						this.form.numHrs=res.shifts.numHrs
						this.form.needHrs=res.shifts.needHrs
						this.form.sffd=res.shifts.sffd
						this.form.depId=res.shifts.depId
						this.form.depNm=res.shifts.depNm
						this.form.cover = res.shifts.cover
					 let count=0
						 for(var i=0;i<this.form.shiftsDetailList.length;i++){
								 if(res.shiftsDetail[i]){
									 count=res.shiftsDetail[i].seq-1
									 this.form.shiftsDetailList[count].isOvertime=res.shiftsDetail[i].isOvertime
									 this.form.shiftsDetailList[count].workBefore=res.shiftsDetail[i].workBefore
									 this.form.shiftsDetailList[count].workSignon=res.shiftsDetail[i].workSignon
									 this.form.shiftsDetailList[count].workSignoff=res.shiftsDetail[i].workSignoff
									 this.form.shiftsDetailList[count].detailWorkHrs=res.shiftsDetail[i].detailWorkHrs
									  this.form.shiftsDetailList[count].detailNeedHrs=res.shiftsDetail[i].detailNeedHrs
									 this.form.shiftsDetailList[count].workWait=res.shiftsDetail[i].workWait
									 this.form.shiftsDetailList[count].detailId=res.shiftsDetail[i].detailId
								 }
						 }
				 })
      },
			handleSelectionChange (selection) {
			  this.selection = selection
			},
			 handleRowRemove ({index, row}) {
						this.delete(row.shiftsId)
			  },
			 onMutilDelClick(){
				 	this.isDisabled = true
				 setTimeout(() => {
				   this.isDisabled = false
				 }, 2000)
			  if(!this.selection.length){
			    this.$message({
			      message: '请选择记录',
			      type: 'success'
			    })
					return false
			  } 
				this.shiftsId=[]
				 this.selection.forEach((item,index)=>{
				 this.shiftsId.push(item.shiftsId)
					})
				 this.shiftsId=this.shiftsId.join(",")
				 this.delete(this.shiftsId)
			},
			delete(shiftsIds){
					 this.$confirm(`确定要删除吗?`, '确认操作', {
					 confirmButtonText: '确定',
					 cancelButtonText: '放弃',
					 type: 'warning'
				 }).then(() => {
					 delShiftsById({shiftsIds}).then(res=>{
						 this.$message({
							 message: '删除成功',
							 type: 'success'
						 })
						this.handleList()
						this.$nextTick(()=>{
							this.$refs.Tree.handleTreeNode() 
					 })
					 })
				 })
			},
      clearForm () {
				this.shiftLoading=false
				this.diaLogName='新增'
				this.falg=false
        this.form = {
						shiftsCode:'',
					shiftsName:'',	
					shiftsType:'',	
					workHrs:'',	
					numHrs:'10',	
					needHrs:'',	
					sffd:'',
					depId:'',
					depNm:'',
					shiftsId:'',
					teamId:'',
					shiftsDetailList: [
					  {
							seq:'1',
							isOvertime:'1',
							workBefore: '60',
							workSignon: '08:00',
							workSignoff: '18:00',
							detailWorkHrs: '10',
							workWait: '60',
							detailId:'',
							detailNeedHrs:'8'
					  },
					  {
						 seq:'2',
						 isOvertime:'1',
					   workBefore: '',
					   workSignon: '',
					   workSignoff: '',
					   detailWorkHrs: '',
					   workWait: '',
						 detailId:'',
						 detailNeedHrs:''
					  },
					  {
						 seq:'3',
						 isOvertime:'1',
					   workBefore: '',
					   workSignon: '',
					   workSignoff: '',
					   detailWorkHrs: '',
					   workWait: '',
						 detailId:'',
						 detailNeedHrs:''
					  }
					]
        }
      },
			//查询班组
			getTNInfoList () {
				/* findTeamByList().then(res => {
					this.list = res.data
				}).catch(err => {
				}) */
			},
			/* 	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 === 'update') {
			        if (item.remarks === 'true') {
			          this.$set(this.rowHandle.custom,0,
			            {
			              text: '编辑',
			              type: 'primary',
			              size: 'small',
			              emit: 'edit'
			            },
			          )
			
			        }
			      }else if(item.functionType === 'delete') {
			        if (item.remarks === 'true') {
			          this.$set(this.rowHandle.custom,this.rowHandle.custom.length,
			            {
			              text: '删除',
			              type: 'danger',
			              size: 'small',
			              emit: 'delete'
			            }
			          )
			        }
			      }
			    })
			  })
			} */
    },
    mounted () {
			//this.getFunction () 
			this.filter.pageSize = this.tableOptions.pageList[0]
      this.tableOptions = this.$calcTableHeight(tableOptions,115)
      this.handleList()
			this.getTNInfoList ()
    }
  }
</script>

<style lang="scss" scoped>
	.el-date-editor{
		width: 120px
	}
</style>