<template>
	<div>
		<common @asynCallBack="asynCallBack"></common>
		<top-header :pageTitle="pageTitle" :rightLink="rightLink" :doRightLink="doRightLink"></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="attendanceTypeName"></button>
						</div>
					</div>
				</form>
			</div>
			<div v-if="tjForm.workAttendanceDate" class="mui-content-padded vongi-wordcard-padded">
				<h5>当前打卡班次</h5>
				<h3>{{tjForm.workAttendanceDate}}<span v-text="tjForm.workAttendanceTime"></span></h3>
			</div>
			<!-- <div class="mui-content-padded">
				<form class="mui-input-group">
					<div class="mui-input-row" @click="selectPerson">
						<label><span class="colorfe616c">*</span>审批人</label>
						<div class="mui-navigate-right">
							<button 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>
				<button class="vongi-yidi-location" @click="getPoint">{{tjForm.address}}<span class="mui-icon mui-icon-location"></span></button>
			</div>
			<div class="mui-content-padded">
				<h5><span class="colorfe616c">*</span>备注</h5>
				<div class="mui-input-row">
					<textarea v-model="tjForm.content" rows="5" placeholder="请输入"></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="vongi-btn">
				<button class="mui-btn mui-btn-primary" type="button" @click="submit">
					提交
				</button>
			</div>
		</div>

		<loading :visible="isLoading"></loading>
	</div>
</template>

<script>
	require('$project/assets/js/mui.picker.min.js');
	import * as API_Attendance from '@/apis/Master/attendance'
	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 MapLoader from '$project/utils/AMap'
	import * as types from '$project/store/mutation-types'
	export default {
		name: 'MasterAttendanceSign',
		components: {
			Common,
			Loading,
			TopHeader
		},
		data() {
			return {
				pageTitle: '外勤打卡',

				isLoading: false,

				subForm: {
					workAttendanceId: '',
					attendanceType: '',
				},
				attendanceType: '3',
				tjForm: {
					alarmConfigId: '',
					workAttendanceDate: '',
					workAttendanceTime: '',
					type: '1', //外勤打卡/补卡（1/2）
					content: '外勤打卡申请',
					approvalPersonId: '',
					workAttendanceId: '',
					photoFile: '',
					longitude: 112.276527,
					latitude: 30.306427,
					address: '定位中……',
					attendanceType: ''
				},
				//typeName: '',
				approvalPersonName: '',
				personList: [],
				picList: [],

				rightLink: {
					show: true,
					icon: 'icon-shijian',
					style: 'font-size:14px;color:#000;',
					title: '考勤记录'
				},

				typeStatusList: [{
						value: '2',
						text: '外出'
					},
					{
						value: '3',
						text: '出差'
					}
				],
			}
		},
		created() {},
		methods: {
			//获取详情
			getTime() {
				this.subForm.attendanceType = this.attendanceType;
				this.isLoading = true;
				API_Attendance.patchCard(this.subForm).then(response => {

					this.tjForm.workAttendanceDate = response.workAttendanceDate;
					this.tjForm.workAttendanceTime = response.workAttendanceTime;
					this.tjForm.alarmConfigId = response.alarmConfigId;

					this.isLoading = false;
				}).catch(error => {

					this.tjForm.workAttendanceDate = '';
					this.tjForm.workAttendanceTime = '';
					this.tjForm.alarmConfigId = '';

					this.isLoading = false;
					mui.toast(error);
				})
			},
			//获取审核人列表
			getPsersonList() {
				this.isLoading = true;
                //补卡1，外出2，出差3 ，请假4
                var parameter={type:this.attendanceType};
				API_Attendance.getApprovalList(parameter).then(response => {

					this.personList = response.data;

					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.syPersonList);
				if (this.default_examine_person) {
					picker.pickers[0].setSelectedValue(this.default_examine_person);
				}
				picker.show(function(selectItems) {
					_this.tjForm.approvalPersonId = 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.syPersonList.length; i++) {
						if (this.syPersonList[i].value == this.default_examine_person) {
							this.tjForm.approvalPersonId = this.default_examine_person;
							this.approvalPersonName = this.syPersonList[i].text;
						}
					}
				}
			},
			//表单检测
			checkFrom() {
				if (!this.tjForm.alarmConfigId) {
					mui.toast('无考勤配置');
					return false;
				} else if (!this.tjForm.type) {
					mui.toast('请选择打卡类型');
					return false;
				}
				/* else if (!this.tjForm.approvalPersonId) {
					mui.toast('请选择审批人');
					return false;
				} */
				else if (!this.tjForm.content) {
					mui.toast('请输入申请内容');
					return false;
				} else if (!this.tjForm.address) {
					mui.toast('暂未获取到您的位置');
					return false;
				} else {
					return true;
				}
			},
			//提交
			submit() {
				this.tjForm.attendanceType = this.attendanceType;
				this.tjForm.photoFile = this.picList.join(',');
				if (this.tjForm.address == '定位中……') {
					this.tjForm.address = '';
				}
				if (this.checkFrom()) {
					this.isLoading = true;
					API_Attendance.postPatchCard(this.tjForm).then(response => {
						this.isLoading = false;

						mui.toast('提交成功');
						this.$router.push({
							name: 'Master',
							query: {}
						})
					}).catch(error => {
						this.isLoading = false;
						mui.toast(error);
					})
				}
			},
			//删除图片
			delPic(item) {
				let picList = this.picList;
				let index = picList.indexOf(item);
				if (index > -1) {
					picList.splice(index, 1);
				}
				this.picList = picList;
			},
			//获取经纬度
			getPoint() {
				this.isLoading = true;
				WxJsApi.getLocation().then((res) => {
					this.isLoading = false;
					this.tjForm.latitude = parseFloat(res.latitude);
					this.tjForm.longitude = parseFloat(res.longitude);

					console.log(this.tjForm)

					//获取定位地址
					this.getPositionByLonLats()
				}).catch(error => {

                    this.isLoading = false;
                    console.log(error)
                    WxJsApi.addSysLog(error)
                })
			},
			//获取定位地址
			getPositionByLonLats() {
				var _this = this;
				MapLoader().then(AMap => {
					var lnglatXY = [_this.tjForm.longitude, _this.tjForm.latitude];
					AMap.service('AMap.Geocoder', function() {
						let geocoder = new AMap.Geocoder({});
						geocoder.getAddress(lnglatXY, function(status, result) {
							console.log(lnglatXY);
							console.log(status, result);
							if (status === 'complete' && result.info === 'OK') {
								var address = result.regeocode.formattedAddress;
								console.log(address);
								_this.tjForm.address = address;
							} else {
								_this.tjForm.address = '无法获取定位';
							}
						});
					});
				}).catch(error => {
					console.log(error)
				})
			},
			//选择考勤类型
			selectType() {
				var _this = this;
				var picker = new mui.PopPicker();
				picker.setData(_this.typeStatusList);
				picker.pickers[0].setSelectedValue(this.attendanceType);
				picker.show(function(selectItems) {
					_this.attendanceType = selectItems[0].value;
					//_this.approvalPersonName = selectItems[0].text;
					_this.getTime();
				})
			},
			//右上角点击事件
			doRightLink() {
				this.$router.push({
					name: 'MasterAttendanceList'
				})
			},
			asynCallBack() {

			},
			...mapMutations({
				set_default_examine_person: types.SET_DEFAULT_EXAMINE_PERSON,
			})
		},
		mounted() {
			if (['2', '3'].indexOf(this.person_data.workStatus) == -1) {
				mui.toast('您当前工作状态无法进行外勤打卡');
				this.$router.go(-1);
			} else {
				//获取微信配置
				WxJsApi.getWxConfig(['chooseImage', 'getLocalImgData', 'getLocation']);
				//获取经纬度
				this.getPoint();
				this.getTime();
				//this.getPsersonList();
			}
		},
		destroyed() {},
		computed: {
			syPersonList: {
				// getter
				get: function() {
					let list = [];
					this.personList.forEach(function(item, index) {
						list.push({
							value: item.id,
							text: item.personName
						});
					})
					return list;
				},
				// setter
				set: function(newValue) {
					console.log(newValue)
				}
			},
			typeName: {
				// getter
				get: function() {
					if (this.tjForm.type == '1') {
						return '外勤打卡';
					} else if (this.tjForm.type == '2') {
						return '补卡';
					} else {
						return '无';
					}
				},
				// setter
				set: function(newValue) {
					console.log(newValue)
				}
			},
			attendanceTypeName: {
				// getter
				get: function() {
					for (var i = 0; i < this.typeStatusList.length; i++) {
						if (this.typeStatusList[i]['value'] == this.attendanceType) {
							return this.typeStatusList[i]['text'];
						}
					}
					return '';
				},
				// setter
				set: function(newValue) {
					console.log(newValue)
				}
			},
			...mapGetters({
				openId: 'wx_openid',
				token: 'token',
				default_examine_person: 'default_examine_person',
				person_data: 'person_data',
			})
		}
	}
</script>

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