<template>
	<div class="form-submit">
		<Card :bordered="false" dis-hover class="ivu-mt">
			<Form :model="formData" :label-width="100">
				<FormItem label="规则名称" required>
					<Input v-model="formData.groupname" v-width="320"></Input>
				</FormItem>
				<FormItem label="打卡员工" required>
					<template v-for="(item,ind) in checkedStaff">
						<Badge class="right-tip">
							<Tag>{{item.name}}(ID:{{item.id}})</Tag>
							<template #count>
								<Icon @click="checkedStaff.splice(ind,1)" size='20' type="ios-close-circle-outline" />
							</template>
						</Badge>
					</template>
					<Button type="primary" @click="chooseSatff">选择员工</Button>
				</FormItem>
				<card class="day_box" v-for="(itemx,indexx) in formData.checkindate">
					<FormItem label="工作日" required>
						<TagSelect @on-change='changeWordkey($event,itemx,indexx)' v-model="itemx.workdays"
							hide-check-all>
							<TagSelectOption v-for="(item,ind) in tageList" :name="ind">
								{{item.name}}
							</TagSelectOption>
						</TagSelect>
					</FormItem>
					<card class="time_box" v-for="(item,index) in itemx.checkintime">
						<FormItem label="上班时间" required>
							<TimePicker :steps="[1, 5]" placeholder="" v-width="320" format="HH:mm"
								v-model="item.work_sec" @on-change="changeWordSec($event,item)" />
						</FormItem>
						<FormItem label="上班打卡奖励" required>
							<Input type="number" v-model="item.start_price" v-width="320"></Input>
						</FormItem>
						<FormItem label="下班时间" required>
							<TimePicker :steps="[1, 5]" placeholder="" v-width="320" format="HH:mm"
								v-model="item.off_work_sec" @on-change="changeWordSecEnd($event,item)" />
						</FormItem>
						<FormItem label="下班打卡奖励" required>
							<Input type="number" v-model="item.end_price" v-width="320"></Input>
						</FormItem>
						<Button type="primary" style="margin-left: 20px;" @click="delNewDk(itemx.checkintime,index)"
							v-if="itemx.checkintime.length>1">删除</Button>
					</card>
					<Button type="primary" @click="addNewDk(itemx)">添加新上班时段</Button>
					<Button type="primary" style="margin-left: 20px;" @click="delNewDkTime(indexx)"
						v-if="indexx>0">删除当前组</Button>
				</card>
				<FormItem :label-width="0">
						<Button type="primary" class="submission" @click="addNewDkTime()">添加新打卡日期</Button>
						<Button type="primary" class="submission" @click="save" :disabled="disabled">创建返回</Button>
						<Button type="primary" class="submission" @click="save('add')" :disabled="disabled">继续创建</Button>
				</FormItem>

			</Form>

		</Card>
		<Modal v-model="modals" title="员工列表" footerHide class="paymentFooter" scrollable width="900"
			@on-cancel="cancel">
			<staff-list ref="stafflist" :goodsType="1" v-if="modals" @getProductId="getProductId"
				:serviceCard="1"></staff-list>
		</Modal>
	</div>
</template>

<script>
	import {
		addCheckRule
	} from '@/api/check';
	import staffList from '@/components/staffList'
	export default {
		name: "storeCouponCreate",
		components: {
			staffList
		},
		data() {
			return {
				checkedStaff: [],
				modals: false, //选择员工弹出
				disabled: false,
				tageList: [{
					value: '',
					number: 1,
					name: '星期一',
					bool: false,
				}, {
					value: '',
					number: 2,
					name: '星期二',
					bool: false,
				}, {
					value: '',
					number: 3,
					name: '星期三',
					bool: false,
				}, {
					value: '',
					number: 4,
					name: '星期四',
					bool: false,
				}, {
					value: '',
					number: 5,
					name: '星期五',
					bool: false,
				}, {
					value: '',
					number: 6,
					name: '星期六',
					bool: false,
				}, {
					value: '',
					number: 0,
					name: '星期天',
					bool: false,
				}],
				formData: {
					groupname: '',
					grouptype: 1, //规则类型: 1-固定时间上下班；2-按班次上下班；3-自由上下班
					type: 2, //	打卡方式 0-手机，2-考勤机，3-手机/考勤机
					range: {
						userid: [],
						member_id: []
					}, //打卡人员
					checkindate: [{
						'workdays': [],
						"checkintime": [{
							"time_id": '1',
							"work_sec": '', //上班时间（距0点秒数，整分钟）
							"off_work_sec": '', //下班时间
							"remind_work_sec": '', //上班提醒时间
							"remind_off_work_sec": '', //下班提醒时间
							"earliest_work_sec": '', //上班最早时间
							"latest_work_sec": '', //上班最晚时间
							"earliest_off_work_sec": '', //下班最早时间
							"latest_off_work_sec": '', //	下班最晚时间
							"start_price": '', //上班打卡奖励
							"end_price": '' //下班打卡奖励
						}],
						"flex_on_duty_time": 0,
						"flex_off_duty_time": 0
					}]

				},
			}
		},
		created() {},
		methods: {
			// 上班时间修改
			changeWordSec(ent, item) {
				let time = this.getTime(ent);
				item.work_sec = ent
				item.latest_work_sec = time + 6000;//上班最晚时间
				item.earliest_work_sec = time - 6000; //上班最早时间
				item.remind_work_sec = time - 600;//上班提醒时间
			},
			// 下班时间修改
			changeWordSecEnd(ent, item) {
				let time = this.getTime(ent);
				item.off_work_sec = ent
				item.latest_off_work_sec = time + 12000; //	下班最晚时间
				item.earliest_off_work_sec = time - 6000;//下班最早时间
				item.remind_off_work_sec = time;//下班提醒时间
			},
			// 触发改变事件
			changeWordkey(res, item, ind) {
				for (let i = 0; i < res.length; i++) {
					// 保存选中是星期几的index
					let num = res[i];
					// 判断这个星期是否未被选中过
					if (!this.tageList[num].bool) {
						this.tageList[num].bool = true;
						// 保存选中这个星期的是哪个工作日组
						this.tageList[num].value = ind;
					} else {
						// 判断这个星期选中的是否是当前工作组
						if (ind !== this.tageList[num].value) {
							let nn = this.tageList[num].value;
							// 获取选中的值在所在工作组的位置
							let wordays = this.formData.checkindate[nn].workdays;
							// 判断参数值是否存在
							if (wordays.indexOf(num) > -1) {
								wordays = wordays.splice(wordays.indexOf(num), 1);
							}
							// 获取选中的星期坐在工作组中的index用于删除该数据
							// 保存为当前的工作组
							this.tageList[num].value = ind;
						}
					}
				}
			},
			// 打开员工选择弹窗
			chooseSatff() {
				this.modals = true;
			},
			// 添加时间
			addNewDk(item) {
				item.checkintime.push({
					"time_id": '',
					"work_sec": '', //上班时间（距0点秒数，整分钟）
					"off_work_sec": '', //下班时间
					"remind_work_sec": '', //上班提醒时间
					"remind_off_work_sec": '', //下班提醒时间
					"earliest_work_sec": '', //上班最早时间
					"latest_work_sec": '', //上班最晚时间
					"earliest_off_work_sec": '', //下班最早时间
					"latest_off_work_sec": '', //	下班最晚时间
					'start_price': '', //上班打卡奖励
					"end_price": '' //下班打卡奖励
				})
			},
			// 添加日期
			addNewDkTime() {
				this.formData.checkindate.push({
					'workdays': [],
					"checkintime": [{
						"time_id": '',
						"work_sec": '', //上班时间（距0点秒数，整分钟）
						"off_work_sec": '', //下班时间
						"remind_work_sec": '', //上班提醒时间
						"remind_off_work_sec": '', //下班提醒时间
						"earliest_work_sec": '', //上班最早时间
						"latest_work_sec": '', //上班最晚时间
						"earliest_off_work_sec": '', //下班最早时间
						"latest_off_work_sec": '', //	下班最晚时间
						'start_price': '', //上班打卡奖励
						"end_price": '' //下班打卡奖励
					}],
					"flex_on_duty_time": 0,
					"flex_off_duty_time": 0
				})
			},
			// 删除时间
			delNewDkTime(index) {
				this.formData.checkindate.splice(index, 1)
			},
			// 删除日期
			delNewDk(item, index) {
				console.log(item, 'itemx')
				item.splice(index, 1)
			},
			// 用户id
			getProductId(row) {
				this.modals = false;
				console.log(row, '这个');
				for (let i = 0; i < row.length; i++) {
					let bool = false;
					for (let a = 0; a < this.checkedStaff.length; a++) {
						if (row[i].id == this.checkedStaff[a].id) {
							bool = true;
							break
						}
					}
					if (!bool) {
						this.checkedStaff.push(row[i])
					}
				}
				let arr = []
				let arr1 = []
				this.checkedStaff.forEach(item => {
					arr.push(item.userid);
					arr1.push(item.id);

				})
				console.log(arr, '22333');
				this.formData.range.userid = arr;
				this.formData.range.member_id = arr1;
			},
			getTime(str) {
				if (typeof(str) == 'string') {
					let arr = str.split(':')
					return arr[0] * 60 * 60 + arr[1] * 60
				} else {
					return str
				}
			},
			// 初始化数据
			initData() {
				this.checkedStaff = [];
				this.formData = {
					groupname: '',
					grouptype: 1, //规则类型: 1-固定时间上下班；2-按班次上下班；3-自由上下班
					type: 2, //	打卡方式 0-手机，2-考勤机，3-手机/考勤机
					range: {
						userid: [],
						member_id: []
					}, //打卡人员
					checkindate: [{
						'workdays': [],
						"checkintime": [{
							"time_id": '1',
							"work_sec": '', //上班时间（距0点秒数，整分钟）
							"off_work_sec": '', //下班时间
							"remind_work_sec": '', //上班提醒时间
							"remind_off_work_sec": '', //下班提醒时间
							"earliest_work_sec": '', //上班最早时间
							"latest_work_sec": '', //上班最晚时间
							"earliest_off_work_sec": '', //下班最早时间
							"latest_off_work_sec": '', //	下班最晚时间
							"start_price": '', //上班打卡奖励
							"end_price": '' //下班打卡奖励
						}],
						"flex_on_duty_time": 0,
						"flex_off_duty_time": 0
					}]
				}
			},
			// 创建
			save(type = 'break') {
				let that = this
				let qdata = Object.assign({}, that.formData);
				if (!qdata.groupname) {
					that.$Message.error("请填写规则名称");
					return
				}
				if (qdata.range.member_id.length == 0) {
					that.$Message.error("请选择员工");
					return
				}
				try {
					qdata.checkindate = that.formData.checkindate.map(item => {
						let data = Object.assign({}, item);
						data.checkintime = item.checkintime.map(itemt => {
							for (let key in itemt) {
								if (key == 'start_price' || key == 'end_price') {
									if (!itemt[key]) {
										throw '请填写上下班打卡奖励'
									}
								} else if (key == 'time_id') {
									itemt[key] = itemt[key] * 1
								} else {
									itemt[key] = that.getTime(itemt[key])
									if (!itemt[key]) {
										throw '请选择上下班时间'
									}
								}
							}
							return itemt
						})
						data.workdays = item.workdays.map(itemt => {
							return that.tageList[itemt].number;
						})
						if (data.workdays.length == 0) {
							throw '请选择打卡日期'
						}
						return data
					})
				} catch (e) {
					that.$Message.error(e);
					return;
				}
				that.disabled = true;
				// 请求
				addCheckRule({
						'group': qdata
					})
					.then((res) => {
						that.$Message.success(res.msg);
						if (type == "break") {
							setTimeout(() => {
								that.$router.push({
									path: "/store/checkRule/index",
								});
							}, 1000);
							return
						}
						if (type == "add") {
							that.disabled = false;
							that.initData()
							return
						}
					})
					.catch((err) => {
						that.$Message.error(err.msg);
						that.disabled = false;
					});
			},
			cancel() {
				this.modals = false;
			},
		},
	};
</script>

<style scoped lang="stylus">
	.form-submit {
		margin-bottom: 79px;
	}
	.day_box {
		margin-bottom: 20px;

		.time_box {
			margin-bottom: 20px;
		}
	}

	.jgTip {
		margin-top: -25px;
		padding-left: 25px;
		padding-bottom: 10px;
		color: #c3c3c3;
		font-size: 12px;
	}

	.right-tip {
		margin-right: 10px;
	}

	.submission {
		margin-right: 10px
	}
</style>