<template>
	<el-container class="list_main_content fullheight">
		<el-aside
			v-if="!$route.meta.single"
			v-show="asideShow"
			class="aside-tree__wrap"
			width="200px"
		>
			<p class="flow_tree_top_title">我请求的分类</p>
			<FlowTree
				ref="FlowTree"
				:isAsideShow="isAsideShow"
				:loadCount="loadCount"
				@currentTree="getCurrent"
				@switch-change="handleSwitch"
			></FlowTree>
		</el-aside>
		<div
			v-if="!$route.meta.single"
			:class="{ 'navbar-collapse-right': !asideShow }"
			class="navbar-collapse"
			@click="asideShow = !asideShow"
		>
			<div class="navbar-collapse-bg">
				<i
					:class="{
						'el-icon-arrow-left': asideShow,
						'el-icon-arrow-right': !asideShow,
					}"
					class="navbar-collapse-arrow"
				></i>
			</div>
		</div>
		<el-container style="border-left: 1px solid #e7eaec;">
			<h3 class="flow_table_title">我的请求列表</h3>
			<div class="content_top_wrap">
				<el-form
					ref="form"
					v-form
					class="content_top_wrap_form"
					data-vv-scope="form"
				>
					<el-input
						v-model="form.tableData"
						class="form_input"
						clearable
						placeholder="标题/编号/流程名称"
						prefix-icon="el-icon-search"
						size="small"
						@keyup.enter.native="searchEnterFun"
					></el-input>
					<el-date-picker
						v-model="form.date"
						:default-time="['00:00:00', '23:59:59']"
						class="form_date_picker"
						end-placeholder="结束日期"
						size="small"
						start-placeholder="开始日期"
						type="datetimerange"
					></el-date-picker>
					<el-select
						v-model="form.statusData"
						class="form_status"
						placeholder="请选择"
						@change="statusChange"
					>
						<el-option
							v-for="item in options"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						></el-option>
					</el-select>
				</el-form>
				<el-row>
					<el-col :span="24">
						<el-button size="small" type="primary" @click="search('find')"
							>查询
						</el-button>
						<el-button size="small" @click="reset">重置</el-button>
					</el-col>
				</el-row>
			</div>
			<el-main class="content">
				<!-- default-sort  排序 -->
				<el-table
					v-loading="fullscreenLoading"
					:data="rows"
					:default-sort="{ prop: 'status,createTime', order: 'descending' }"
					header-cell-class-name="myRequest-header-row"
					row-class-name="myRequest-row"
					size="medium"
					style="width: 100%;"
				>
					<el-table-column
						align="center"
						label="序号"
						type="index"
						width="50"
					></el-table-column>
					<el-table-column align="center" label="流程图" width="70">
						<template slot-scope="scope">
							<el-button
								icon="icon-flow1"
								size="mini"
								@click="handleShowTaskImage(scope.row)"
							></el-button>
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						label="流程编号"
						prop="id"
						show-overflow-tooltip
						width="160"
					></el-table-column>
					<el-table-column label="标题" show-overflow-tooltip>
						<template slot-scope="scope">
							<span
								class="myRequest-subject"
								@click="handleRowClick(scope.row)"
								@contextmenu.prevent="handleRowClick(scope.row, true)"
								>{{ scope.row.subject }}</span
							>
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						label="流程名称"
						show-overflow-tooltip
						width="150"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.procDefName }}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						label="创建时间"
						prop="createTime"
						width="150"
					>
						<template slot-scope="scope">
							<span> {{ scope.row.createTime | formatDate }} </span>
						</template>
					</el-table-column>
					<!-- <el-table-column prop="creator" label="发起人" align="center" width="180"></el-table-column> -->
					<el-table-column align="center" label="状态" width="110">
						<template slot-scope="scope">
							<span
								v-if="
									scope.row.status == 'revoke' ||
									scope.row.status == 'revokeToStart' ||
									scope.row.status == 'back' ||
									scope.row.status == 'backToStart'
								"
								style="color: #f71010;"
								>{{ myRequestStatus[scope.row.status] }}</span
							>
							<span
								v-if="scope.row.status == 'draft'"
								style="color: #c2a437;"
								>{{ myRequestStatus[scope.row.status] }}</span
							>
							<span
								v-if="scope.row.status == 'running'"
								style="color: #318409;"
								>{{ myRequestStatus[scope.row.status] }}</span
							>
							<span
								v-if="
									scope.row.status == 'end' || scope.row.status == 'manualend'
								"
								style="color: #909399;"
								>{{ myRequestStatus[scope.row.status] }}</span
							>
						</template>
					</el-table-column>
					<el-table-column
						v-if="showOperation"
						align="center"
						label="操作"
						width="150"
					>
						<template slot-scope="scope">
							<!-- <el-button
                v-if="
                  scope.row.status == 'running' ||
                    scope.row.status == 'back' ||
                    scope.row.status == 'revoke'
                "
                size="mini"
                type="danger"
                @click="handleRevoke(scope.row.id, scope.row.status)"
                >撤回</el-button
              > -->
							<el-button
								v-if="scope.row.status == 'draft'"
								size="mini"
								type="danger"
								@click="deleteDraft(scope.row.id)"
								>删除草稿
							</el-button>
							<el-button
								v-if="
									scope.row.status == 'manualend' ||
									scope.row.status == 'revokeToStart' ||
									scope.row.status == 'backToStart' ||
									(scope.row.status == 'back' && scope.row.backToStart == true)
								"
								size="mini"
								type="danger"
								@click="deleteBpm(scope.row.id)"
								>删除
							</el-button>
							<el-button
								v-if="
									scope.row.status == 'revokeToStart' ||
									scope.row.status == 'backToStart' ||
									(scope.row.status == 'back' && scope.row.backToStart == true)
								"
								size="mini"
								style="margin-top: 5px;"
								type="danger"
								@click="doEndProcessById(scope.row.id)"
								>终止
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-main>
			<el-footer height="52px">
				<el-row justify="end" type="flex">
					<el-pagination
						:current-page="pagination.page"
						:page-size="pagination.pageSize"
						:page-sizes="[10, 20, 50, 100]"
						:total="total"
						layout="total, sizes, prev, pager, next, jumper"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					></el-pagination>
				</el-row>
			</el-footer>
			<el-dialog
				:close-on-click-modal="false"
				:visible.sync="dialogFormVisible"
				title="撤回到发起人"
			>
				<el-input
					v-model="opinion"
					:autosize="{ minRows: 4, maxRows: 4 }"
					placeholder="请输入撤回意见"
					type="textarea"
				></el-input>
				<div slot="footer" class="dialog-footer">
					<el-button size="small" type="primary" @click="saveRevoke"
						>确 定
					</el-button>
					<el-button size="small" @click="exitRevoke">取 消</el-button>
				</div>
			</el-dialog>
		</el-container>
		<!-- 流程图 -->
		<TaskImage
			ref="taskImage"
			:bpmnInstId="selectBpmnInstId"
			:defId="selectDefId"
			:instId="selectInstanceId"
		/>
	</el-container>
</template>

<script>
import { mapState } from 'vuex';
import FlowTree from '@/components/flow/flowTree.vue';
import utils from '@/utils.js';
import process from '@/api/process.js';
import TaskImage from '@/components/flow/task/taskImage.vue';

const MY_REQUEST_STATUS = {
	revoke: '撤回',
	revokeToStart: '撤回到发起人',
	draft: '草稿',
	running: '运行中',
	end: '结束',
	manualend: '人工结束',
	back: '驳回',
	backToStart: '驳回到发起人',
};

export default {
	name: 'myRequest',
	components: {
		FlowTree,
		TaskImage,
	},
	props: {
		defKey: {
			type: String,
			default: '',
		},
	},
	data() {
		return {
			myRequestStatus: MY_REQUEST_STATUS,
			isAsideShow: false,
			asideShow: false,
			form: { tableData: '', date: '', statusData: '' },
			fullscreenLoading: true,
			dialogFormVisible: false,
			opinion: '',
			currentTree: '',
			id: '',
			statusData: '',
			options: [
				{
					value: '',
					label: '请选择状态',
				},
				{
					value: 'revoke',
					label: '撤回',
				},
				{
					value: 'draft',
					label: '草稿',
				},
				{
					value: 'back',
					label: '驳回',
				},
				{
					value: 'end',
					label: '结束',
				},
				{
					value: 'running',
					label: '运行中',
				},
			],
			showOperation: false,
			selectInstanceId: '',
			selectDefId: '',
			selectBpmnInstId: '',
		};
	},
	computed: {
		...mapState('storeProcess', ['rows', 'pagination', 'total']),
		currentSwitchValue() {
			return (
				localStorage.myRequestAsideShow === 'true' ||
				localStorage.myRequestAsideShow === true
			);
		},
	},
	methods: {
		//将当前展开或者收起的值存在localStorage中
		handleSwitch(val) {
			localStorage.myRequestAsideShow = val;
		},
		//选择状态查询
		statusChange(value) {
			this.form.statusData = value;
			this.search('find');
		},
		handleClose(done) {
			this.dialogFormVisible = true;
		},
		//逻辑删除流程实例
		deleteBpm(id) {
			this.$confirm('确认删除此流程?', '提示', {
				cancelButtonText: '取消',
				confirmButtonText: '确定',
				type: 'warning',
				closeOnClickModal: false,
			}).then(() => {
				this.$store.dispatch('storeProcess/restore', id).then(() => {
					this.search('find');
				});
			});
		},
		//终止流程
		doEndProcessById(id) {
			this.$confirm('确认终止此流程?', '提示', {
				cancelButtonText: '取消',
				confirmButtonText: '确定',
				type: 'warning',
				closeOnClickModal: false,
			}).then(() => {
				this.$store.dispatch('storeProcess/doEndProcessById', id).then(() => {
					this.search('find');
				});
			});
		},
		//删除草稿
		deleteDraft(id) {
			this.$store.dispatch('storeProcess/removeDraftById', id).then(() => {
				this.search('find');
			});
		},
		//撤回到发起人
		handleRevoke(id, status) {
			if (status == 'revokeToStart') {
				this.$message.warning('已撤回，不能再撤回');
				return false;
			}
			this.dialogFormVisible = true;
			this.id = id;
		},
		saveRevoke() {
			if (this.opinion == '') {
				this.$message.warning('请填写撤回意见');
				return false;
			}
			let data = {
				instanceId: this.id,
				isHandRevoke: false,
				cause: this.opinion,
			};
			this.$store.dispatch('storeProcess/revokeInstance', data).then(() => {
				this.dialogFormVisible = false;
				this.opinion = '';
				this.search();
			});
		},
		exitRevoke() {
			this.dialogFormVisible = false;
			this.opinion = '';
		},
		//Loading 加载中
		openFullScreen() {
			this.fullscreenLoading = true;
		},
		handleSizeChange: function (size) {
			//每页下拉显示数据
			this.$store.dispatch('storeProcess/setPaginationSize', size);
			this.search();
		},
		handleCurrentChange: function (currentPage) {
			//点击第几页
			this.$store.dispatch('storeProcess/setPaginationPageNum', currentPage);
			this.search();
		},
		//回车查询
		searchEnterFun: function (e) {
			var keyCode = window.event ? e.keyCode : e.which;
			if (keyCode == 13) {
				this.search('find');
			}
		},
		// 查询
		search(str) {
			this.openFullScreen();
			if (str == 'find') {
				this.$store.dispatch('storeProcess/setPaginationPageNum', 1);
			}
			let querys = []; //查询条件
			let queryFilter = {};
			let pageBean = { pageBean: this.pagination };
			let beginDate = ''; //开始时间
			let endDate = ''; //结束时间
			let group = 'main'; //判断条件
			if (
				this.form.tableData == '' &&
				this.form.statusData == '' &&
				(this.form.date == '' || this.form.date == null)
			) {
				if (this.currentTree != '') {
					querys = [
						{
							property: 'type_id_',
							value: this.currentTree,
							group: 'typeId',
							operation: 'IN',
							relation: 'AND',
						},
					];
				}
			} else {
				if (
					this.form.tableData != '' &&
					this.form.statusData != '' &&
					this.form.date != '' &&
					this.form.date != null
				) {
					group = 'time';
				}
				if (this.form.date != null && this.form.date != '') {
					beginDate = utils.formatDate(this.form.date[0].getTime());
					endDate = utils.formatDate(this.form.date[1].getTime());
				}
				if (this.form.tableData) {
					querys.push({
						property: 'proc_def_name_',
						value: this.form.tableData,
						group: 'main',
						operation: 'LIKE',
						relation: 'OR',
					});
					querys.push({
						property: 'subject_',
						value: this.form.tableData,
						group: 'main',
						operation: 'LIKE',
						relation: 'OR',
					});
					querys.push({
						property: 'bpm_pro_inst.id_',
						value: this.form.tableData,
						group: 'main',
						operation: 'LIKE',
						relation: 'OR',
					});
				}
				if (beginDate && endDate) {
					querys.push({
						property: 'create_time_',
						value: [beginDate, endDate],
						group: 'time',
						operation: 'BETWEEN',
						relation: 'AND',
					});
				}

				if (this.form.statusData) {
					querys.push({
						property: 'status_',
						value: this.form.statusData,
						group: 'status',
						operation: 'LIKE',
						relation: 'AND',
					});
				}

				if (this.currentTree) {
					querys.push({
						property: 'type_id_',
						value: this.currentTree,
						group: 'typeId',
						operation: 'IN',
						relation: 'AND',
					});
				}
			}
			if (this.defKey) {
				querys.push({
					property: 'proc_def_key_',
					value: this.defKey,
					operation: 'EQUAL',
					relation: 'AND',
				});
			}
			queryFilter = { pageBean: this.pagination, querys };
			this.$store
				.dispatch('storeProcess/getMyRequestByPagination', queryFilter)
				.then(() => {
					this.fullscreenLoading = false;
				});
		},
		//重置
		reset() {
			this.form = { tableData: '', date: '', statusData: '' };
			this.search('find');
		},
		handleRowClick(row, newWin) {
			if (this.defKey) {
				this.handleOpenUrl(
					'/sysModuleInst/' + row.id + '/request/' + this.defKey,
					newWin
				);
			}
			if (row.status == 'draft') {
				this.handleOpenUrl('/start/' + row.procDefId + '/' + row.id, newWin);
			} else if (row.status == 'end' || row.status == 'manualend') {
				this.handleOpenUrl('/instRead/' + row.id + '/myRequest', newWin);
			} else if (
				row.status == 'backToStart' ||
				row.status == 'back' ||
				row.status == 'revoke' ||
				row.status == 'revokeToStart'
			) {
				this.$http
					.get(
						'${bpmRunTime}/runtime/instance/v1/getStartNodeTaskByInstId?instId=' +
							row.id
					)
					.then(resp => {
						let url = '/inst/' + row.id + '/request';
						if (resp && resp.data) {
							url = '/taskFromOtherPage/' + resp.data.id + '/0/myRequest';
							if (this.defKey) {
								url =
									'/sysModuleInst/' +
									resp.data.id +
									'/0' +
									'/' +
									this.defKey +
									'/true';
							}
						}
						this.handleOpenUrl(url, newWin);
					});
			} else {
				this.handleOpenUrl('/inst/' + row.id + '/request', newWin);
			}
		},
		handleOpenUrl(url, newWin) {
			if (!newWin) {
				this.$router.push(url);
				return;
			}
			if (!url) {
				return;
			}
			let token = this.$store.state.login.currentUser.token;
			if (!url.toLowerCase().startsWith('http')) {
				url = window.context.front + url;
			}
			if (url.indexOf('?') == -1) {
				url = url + '?token=' + token;
			} else {
				url = url + '&token=' + token;
			}
			window.open(url, '_blank');
		},
		//子组件传值父组件(我的请求分类查询)
		getCurrent(data) {
			if (data.id == 6) {
				this.openFullScreen();
				this.currentTree = '';
				let pageBean = { pageBean: this.pagination };
				this.$store
					.dispatch('storeProcess/getMyRequestByPagination', pageBean)
					.then(() => {
						//页面加载调用myRequest.js里面的分页方法
						this.fullscreenLoading = false;
					});
			} else {
				let ids = [];
				this.getFlowTrees(data, ids);
				this.currentTree = ids.join(',');
				this.search('find');
			}
		},
		getFlowTrees(data, ids) {
			ids.push(data.id);
			let arr = data.children;
			for (var i = 0; i < arr.length; i++) {
				this.getFlowTrees(arr[i], ids);
			}
		},
		loadCount() {
			let pageBean = {};
			return process.getMyRequestCount(pageBean);
		},
		checkOperationShow(data) {
			//draft manualend revokeToStart backToStart back revokeToStart backToStart back(&&backToStart==true)
			//是否显示操作列
			if (!data || data.length == 0) {
				this.showOperation = false;
				return;
			}
			let arr = [
				'draft',
				'manualend',
				'revokeToStart',
				'backToStart',
				'revokeToStart',
			];
			for (let i = 0; i < data.length; i++) {
				let row = data[i];
				if (
					(row.status == 'back' && row.backToStart == true) ||
					arr.includes(row.status)
				) {
					this.showOperation = true;
					return;
				}
			}
			this.showOperation = false;
		},
		async handleShowTaskImage(row) {
			await this.changeSeletion(row);
			this.$refs.taskImage.handleOpen();
		},
		changeSeletion(row) {
			this.selectInstanceId = row.id;
			this.selectBpmnInstId = row.bpmnInstId;
		},
	},
	created() {
		this.asideShow = this.currentSwitchValue;
		this.isAsideShow = this.currentSwitchValue;
		let querys = [];
		if (this.defKey) {
			querys.push({
				property: 'proc_def_key_',
				value: this.defKey,
				operation: 'EQUAL',
				relation: 'AND',
			});
		}
		let pageBean = {
			pageBean: { page: '1', pageSize: '10', showTotal: 'true' },
			querys,
		}; //初次加载默认pageBean
		this.$store
			.dispatch('storeProcess/getMyRequestByPagination', pageBean)
			.then(() => {
				//页面加载调用myRequest.js里面的分页方法
				this.fullscreenLoading = false;
			});
	},
	watch: {
		rows(newValue, oldValue) {
			this.checkOperationShow(newValue);
		},
	},
};
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';

.el-table /deep/ th.myRequest-header-row {
	background-color: #fafafa;
	font-size: 13px;
}

.el-table /deep/ tr.myRequest-row {
	font-size: 13px;
	color: $--color-text-regular;
}

.el-container {
	background-color: #fff;
}

.el-row {
	margin-bottom: 20px;
}

.el-header {
	border-bottom: 1.5px solid #ededed;
}

.myRequest-subject {
	cursor: pointer;
}

.myRequest-subject {
	color: $--theme-color;
}

.top-title {
	line-height: 58px;
	margin-left: 20px;
	font-size: 16px;
	color: #a2a2a2;
}

/deep/ .el-tree {
	position: relative;
	cursor: default;
	background: #fff;
	color: $--color-text-primary;
	font-size: 13px;
}

.content {
	padding-top: 0;
}

.content_top_wrap {
	display: flex;
	flex-direction: row;
	margin: 10px 0 0 20px;
	flex-wrap: wrap;
	// height: 32px;
	&_form {
		display: flex;
		flex-direction: row;
		margin-bottom: 10px;

		/deep/ .el-input__prefix,
		/deep/ .el-input__suffix {
			height: 32px;
		}

		.form_input {
			margin-right: 10px;
		}

		.form_date_picker {
			margin-right: 10px;
			min-width: 300px;
		}

		.form_status {
			margin-right: 10px;
			min-width: 200px;
		}
	}
}
</style>
