<template>
	<div>

		<common @asynCallBack="asynCallBack"></common>
		<top-header :pageTitle="pageTitle"></top-header>

		<div class="mui-content vongi-wordcard">
			<div class="mui-content-padded">
				<form class="mui-input-group">
					<div class="mui-input-row">
						<label><span class="colorfe616c">*</span>请假类型</label>
						<div class="mui-navigate-right" @click="selectType">
							<button class="mui-btn mui-btn-block" type='button' v-text="typeName">请选择</button>
						</div>
					</div>
                    <div class="mui-input-row">
                        <label><span class="colorfe616c">*</span>开始日期</label>
                        <div class="mui-navigate-right" @click="selectStartTime()">
                            <button class="mui-btn mui-btn-block" type='button' v-text="tjForm.startTime+(tjForm.startTimeQuantum!=''?(tjForm.startTimeQuantum=='1'?'下午上班':'上午上班'):'')">请选择</button>
                        </div>
                    </div>
                    <div class="mui-input-row">
                        <label><span class="colorfe616c">*</span>结束日期</label>
                        <div class="mui-navigate-right" @click="selectEndTime()">
                            <button class="mui-btn mui-btn-block" type='button' v-text="tjForm.endTime+(tjForm.endTimeQuantum!=''?(tjForm.endTimeQuantum=='1'?'下午下班':'上午下班'):'')">请选择</button>
                        </div>
                    </div>
				</form>
			</div>
			<div class="mui-content-padded vongi-qingjia-date">
				 <h5 v-if="tjForm.leaveType==4">可调休剩余时长<span class="color4fc5f7">{{workOverTime}}小时</span></h5>
				<form class="mui-input-group">

					<div class="mui-input-row">
						<label><span class="colorfe616c"></span>请假时长</label>
						<div  >
							<button class="mui-btn mui-btn-block" type='button' v-text="daytime?daytime+'天':''" > </button>
 						</div>
					</div>
                    <div class="mui-input-row">
                        <label><span class="colorfe616c">*</span>审批人</label>
                        <div class="mui-navigate-right" @click="selectPerson">
                            <button id='' class="mui-btn mui-btn-block" type='button' v-text="approvalPersonName">请选择</button>
                        </div>
                    </div>
				</form>
			</div>
			<div class="mui-content-padded">
				<h5><span class="colorfe616c">*</span>请假事由</h5>
				<div class="mui-input-row">
					<textarea id="textarea" rows="5" v-model="tjForm.reason" :placeholder="reasonDefault"></textarea>
				</div>
			</div>

			<div class="mui-content-padded">
				<h5>上传照片</h5>
				<div class="fyy-upphoto">
					<div class="mui-col-xs-3 fyy-upphoto-close" v-for="(item,index) in picList">
						<img :src="item" />
						<a class="mui-icon mui-icon-closeempty" @click="delPic(item)"></a>
					</div>
					<div class="mui-col-xs-3" @click="chooseImage">
						<a><span class="mui-icon mui-icon-plusempty"></span></a>
					</div>
				</div>
			</div>

			<div class="mui-content-padded mui-h6">注：1、病假须上传医院证明。2、请假事由中须写明请假去向。</div>
			<div class="vongi-btn">
				<button class="mui-btn mui-btn-primary " type="submit" @click="submit()">
					提交
				</button>
			</div>
		</div>
		<loading :visible="isLoading"></loading>

	</div>
</template>


<script>
	require('$project/assets/js/mui.picker.min.js');
	import * as API_Leave from '@/apis/Master/leave'
	import Common from '$project/components/Common.vue'
	import Loading from '$project/components/Loading.vue'
	import TopHeader from '$project/components/TopHeader.vue'
	import {
		mapGetters,
		mapMutations
	} from 'vuex'
	import * as WxJsApi from '$project/utils/wxJsApi'
	import * as types from '$project/store/mutation-types'
    import {
        daysDistance
    } from '$project/utils'

	export default {
		name: 'MasterAttendanceLeaveForm',
		components: {
			Common,
			Loading,
			TopHeader
		},
		data() {
			return {
				pageTitle: '请假',
				daytime:'',
				isLoading: false,
				leaveTypeList: [],
 				approvedList: [],
                workOverTime:0,
				typeName: '请选择',
				approvalPersonName: '请选择',
				tjForm: {
					startTime: '请选择',
					endTime: '请选择',
                    startTimeQuantum: '',
                    endTimeQuantum: '',
					leaveType: '',

					imageUrl: '',
					reason: '',
					personId: '',

                    approvedPersonPopedomId: '',
					remark: '',
				},
				reasonDefault: '请假申请',
				picList: [],
			}
		},
		created() {

		},
		methods: {
			//审批类型
			getLeaveTypeList() {
				API_Leave.leaveTypeList().then(response => {

					for (var i in response) {
						var mod = response[i]
						mod.text = mod.name
						this.leaveTypeList.push(mod)
					}
				}).catch(error => {
					mui.toast(error);
				})
			},
			//获取审核人列表
			getPsersonList() {
				this.isLoading = true;
                //补卡1，外出2，出差3 ，请假4
                var p={type:4};

				API_Leave.approvedList(p).then(response => {
                   this.workOverTime=response.workOverTime;
                    var sz=[];
					for (var i in response.data) {
						var mod = response.data[i]
						mod.text = mod.personName
						mod.value = mod.id;
                        sz.push(mod)
					}
                    this.approvedList=sz;

					this.isLoading = false;
                    //设置默认审核人
                    this.setDefaultExaminePerson();
				}).catch(error => {
					this.isLoading = false;
					mui.toast(error);
				})
			},
			//微信选择图片
			chooseImage() {
				WxJsApi.chooseImage().then(res => {
					var localData = res.localData;

					if (localData.indexOf('data:image') != 0) {
						//判断是否有这样的头部
						localData = 'data:image/jpeg;base64,' + localData
					}
					localData = localData.replace(/\r|\n/g, '').replace('data:image/jgp', 'data:image/jpeg')
					this.imgBase64 = localData;
					//显示裁剪图片
					//_this.showCropper(field);
					this.uploadpic();
				}).catch(error => {
					mui.toast(error);
				})
			},
			//上传图片
			uploadpic() {
				this.isLoading = true;
				WxJsApi.uploadPic(this.imgBase64).then(response => {
					this.isLoading = false;

					this.picList.push(response);
				}).catch(error => {
					this.isLoading = false;
					mui.toast(error);
				})
			},
			//选择审核人
			selectPerson() {
				var _this = this;

				var picker = new mui.PopPicker();

				picker.setData(_this.approvedList);
				if (this.default_examine_person) {
					picker.pickers[0].setSelectedValue(this.default_examine_person);
				}
				picker.show(function(selectItems) {
					_this.tjForm.approvedPersonPopedomId = selectItems[0].value;
					_this.approvalPersonName = selectItems[0].text;
					_this.set_default_examine_person(selectItems[0].value);
				})
			},
			//设置默认审核人
			setDefaultExaminePerson() {
				if (this.default_examine_person) {
					for (var i = 0; i < this.approvedList.length; i++) {
						if (this.approvedList[i].value == this.default_examine_person) {
							this.tjForm.approvedPersonPopedomId = this.default_examine_person;
							this.approvalPersonName = this.approvedList[i].text;
						}
					}
				}
			},
			//选择时间
			selectStartTime() {
				var _this = this;

				var startTime = _this.tjForm.startTime == '请选择' ? null : _this.tjForm.startTime;

				var endDate = null;

				if (_this.tjForm.endTime != '请选择') {
					endDate = new Date(_this.tjForm.endTime);
				}

				var picker = new mui.DtPicker({
					"type": "hour",
					"beginYear": 2020,
					"endYear": 2040,
					"endDate": endDate,
                    "value": startTime,

                    "customData":{"h":[{"text":"上午","value":"0"},{"text":"下午","value":"1"}]}


                });
				var _mui=mui;
				picker.show(function(selectItems) {
                    var year = selectItems.y.value;
                    var month = selectItems.m.value;
                    var day = selectItems.d.value;
                    var curDate = year + "-" + month + "-" + day;

                    if(curDate==_this.tjForm.endTime&&_this.tjForm.endTimeQuantum=='0'&&selectItems.h.value=='1'){
                        //debugger
                        _mui.alert('开始日期必须大于结束日期');
                        return false;
                    }

					_this.tjForm.startTime = curDate;

                    _this.tjForm.startTimeQuantum =  selectItems.h.value;
                    _this.updatePersonByTime();
                });
			},
			//选择时间
			selectEndTime() {

				var _this = this;

				if (_this.tjForm.startTime == '请选择') {
					mui.toast('请选择开始日期');
					return;
				}
				var beginDate = new Date(_this.tjForm.startTime);
                var endTime = _this.tjForm.endTime == '请选择' ? null : _this.tjForm.endTime;

				var picker = new mui.DtPicker({
					"type": "hour",
					"beginYear": 2020,
					"endYear": 2040,
					"beginDate": beginDate,
                    "value":endTime,

                    "customData":{"h":[{"text":"上午","value":"0"},{"text":"下午","value":"1"}]}
                });
                var _mui=mui;
				picker.show(function(selectItems) {

                    var year = selectItems.y.value;
                    var month = selectItems.m.value;
                    var day = selectItems.d.value;
                    var curDate = year + "-" + month + "-" + day;

                    if(curDate==_this.tjForm.startTime&&_this.tjForm.startTimeQuantum=='1'&&selectItems.h.value=='0'){
                        //debugger
                        _mui.alert('结束日期不能小于开始日期');
                        return false;
                    }

                    _this.tjForm.endTime = curDate;
                    _this.tjForm.endTimeQuantum =  selectItems.h.value;
                    _this.updatePersonByTime();
 				});
			},
			//根据时间 -调整审批人
			updatePersonByTime(){
			    if(this.tjForm.startTime=='请选择'||this.tjForm.endTime=='请选择'){
			        return;
				}
              var i=  daysDistance(this.tjForm.startTime,this.tjForm.endTime);
              var day=i+(this.tjForm.endTimeQuantum-this.tjForm.startTimeQuantum)*0.5+0.5
				this.daytime=day;



			},
			//类型选择
			selectType() {
				var picker = new mui.PopPicker();

				picker.setData(this.leaveTypeList);
				var _this = this;
				picker.show(function(selectItems) {
					_this.tjForm.leaveType = selectItems[0].value;
					_this.typeName = selectItems[0].text;
				})
			},
            checkWorkOverTime(){
               return this.daytime*8 <this.workOverTime;
			},
			//表单检测
			checkFrom() {
				if (!this.tjForm.leaveType) {
					mui.toast('请选择请假类型');
					return false;
				} else if (!this.tjForm.approvedPersonPopedomId) {
					mui.toast('请选择审批人');
					return false;
				} else if (this.tjForm.startTime== '请选择') {
					mui.toast('请选择开始日期');
					return false;
				} else if (!this.tjForm.endTime== '请选择') {
					mui.toast('请选择结束日期');
					return false;
				}else if (this.tjForm.leaveType==4&&!this.checkWorkOverTime()) {
                    mui.toast("调休剩余时长小于请假时长");
                    return false;
                }

				else if (!this.tjForm.reason) {
					mui.toast('请输入请假理由');
					return false;
				} else {
					return true;
				}
			},
			//删除图片
			delPic(item) {
				let picList = this.picList;
				let index = picList.indexOf(item);
				if (index > -1) {
					picList.splice(index, 1);
				}
				this.picList = picList;
			},
			//提交
			submit() {
				this.tjForm.reason = this.tjForm.reason ? this.tjForm.reason : this.reasonDefault;
				if (this.checkFrom()) {
					this.tjForm.imageUrl = this.picList.join(',');
					this.isLoading = true;
					this.tjForm.days=this.daytime;
					API_Leave.save(this.tjForm).then(response => {
						this.isLoading = false;
						mui.toast("提交成功");
						this.$router.go(-1);
					}).catch(error => {
						this.isLoading = false;
						mui.toast(error);
					})
				}
			},
			asynCallBack() {

			},
			...mapMutations({
				set_default_examine_person: types.SET_DEFAULT_EXAMINE_PERSON,
			})
		},
		mounted() {
			//获取微信配置
			WxJsApi.getWxConfig();
            this.getPsersonList();

			this.getLeaveTypeList();


		},
		destroyed() {},
		computed: {
			...mapGetters({
				openId: 'wx_openid',
				token: 'token',
				default_examine_person: 'default_examine_person'
			})
		}
	}
</script>

<style scoped src="$project/assets/css/xpwyfyy.css"></style>
<style src="$project/assets/css/iconfont.css"></style>
<style src="$project/assets/css/mui.picker.min.css"></style>

<style>
</style>
