<template>
	<el-container class="list_main_content fullheight">
		<el-aside
			width="200px"
			v-if="!$route.meta.single"
			v-show="asideShow"
			class="aside-tree__wrap"
		>
			<p class="flow_tree_top_title">待办事项分类</p>
			<FlowTree
				ref="FlowTree"
				@currentTree="getCurrent"
				:loadCount="loadCount"
				@switch-change="handleSwitch"
				:isAsideShow="isAsideShow"
			></FlowTree>
		</el-aside>
		<div
			v-if="!$route.meta.single"
			class="navbar-collapse"
			:class="{ 'navbar-collapse-right': !asideShow }"
			@click="asideShow = !asideShow"
		>
			<div class="navbar-collapse-bg">
				<i
					class="navbar-collapse-arrow"
					:class="{
						'el-icon-arrow-left': asideShow,
						'el-icon-arrow-right': !asideShow,
					}"
				></i>
			</div>
		</div>
		<!-- <el-aside width="200px" v-if="!$route.meta.single">
      <b class="top-title el-icon-menu">待办事项分类</b>
      <FlowTree ref="FlowTree" @currentTree="getCurrent" :loadCount="loadCount"></FlowTree>
    </el-aside> -->
		<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
					data-vv-scope="form"
					class="content_top_wrap_form"
				>
					<el-input
						class="form_input"
						size="small"
						clearable
						placeholder="标题/编号/流程名称/任务名称/扩展字段"
						prefix-icon="el-icon-search"
						v-model="form.tableData"
						@keyup.enter.native="searchEnterFun"
					></el-input>
					<el-date-picker
						class="form_date_picker"
						v-model="form.date"
						type="datetimerange"
						size="small"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
						:default-time="['00:00:00', '23:59:59']"
					></el-date-picker>
					<div>
						<eip-org-selector
							class="form_org_selector"
							style="display: inline-block;"
							placeholder="发起人组织"
							:single="true"
							v-model="form.orgName"
							:config="{ id: 'form.orgId' }"
						/>
					</div>
				</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-button size="small" @click="taskToCopyTo()">传阅</el-button>
						<el-button size="small" @click="batchHandle">批量处理</el-button>
					</el-col>
				</el-row>
			</div>
			<el-main class="content">
				<!-- default-sort 默认不排序（排序时查询待办很慢，用户可以点击某列进行排序） -->
				<el-table
					:data="rows"
					ref="htTable"
					style="width: 100%;"
					header-cell-class-name="todo-header-row"
					row-class-name="todo-row"
					size="medium"
					@row-click="rowClick"
					v-loading="fullscreenLoading"
					@selection-change="handleSelectionChange"
					v-if="defaultFiledShowConf"
				>
					<el-table-column
						type="selection"
						width="50"
						align="center"
					></el-table-column>
					<el-table-column label="流程图" width="70" align="center">
						<template slot-scope="scope">
							<el-button
								@click="handleShowTaskImage(scope.row)"
								icon="icon-flow1"
								size="mini"
							></el-button>
						</template>
					</el-table-column>
					<el-table-column
						prop="procInstId"
						:label="defaultFiledShowConf.procInstId.desc"
						v-if="defaultFiledShowConf.procInstId.frontShow"
						show-overflow-tooltip
						width="160"
						align="center"
					></el-table-column>
					<el-table-column
						:label="defaultFiledShowConf.subject.desc"
						v-if="defaultFiledShowConf.subject.frontShow"
						show-overflow-tooltip
					>
						<template slot-scope="scope">
							<span
								class="todo-subject"
								@click="handleRowClick(scope.row, false)"
								@contextmenu.prevent="handleRowClick(scope.row, true)"
							>
								{{ scope.row.subject }}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						:label="defaultFiledShowConf.procDefName.desc"
						v-if="defaultFiledShowConf.procDefName.frontShow"
						show-overflow-tooltip
						align="center"
						width="120"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.procDefName }}</span>
						</template>
					</el-table-column>
					<el-table-column
						:label="defaultFiledShowConf.name.desc"
						v-if="defaultFiledShowConf.name.frontShow"
						show-overflow-tooltip
						align="center"
						width="120"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.name }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="createTime"
						:label="defaultFiledShowConf.createTime.desc"
						v-if="defaultFiledShowConf.createTime.frontShow"
						align="center"
						width="150"
					></el-table-column>
					<el-table-column
						prop="creator"
						:label="defaultFiledShowConf.creator.desc"
						v-if="defaultFiledShowConf.creator.frontShow"
						align="center"
						width="90"
					></el-table-column>
					<el-table-column
						prop="ownerName"
						:label="defaultFiledShowConf.ownerName.desc"
						v-if="defaultFiledShowConf.ownerName.frontShow"
						align="center"
						width="90"
					></el-table-column>
					<el-table-column
						prop="assigneeName"
						:label="defaultFiledShowConf.assigneeName.desc"
						v-if="defaultFiledShowConf.assigneeName.frontShow"
						align="center"
						width="90"
					></el-table-column>
					<el-table-column
						width="100"
						:label="defaultFiledShowConf.status.desc"
						v-if="defaultFiledShowConf.status.frontShow"
						align="center"
					>
						<template slot-scope="{ row }">
							<span size="small" class="blue-color">{{
								status[row.status] +
								(row.instIsForbidden === '1' ? '(挂起)' : '')
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="prop1"
						:label="defaultFiledShowConf.prop1.desc"
						v-if="defaultFiledShowConf.prop1.frontShow"
						align="center"
						width="100"
					></el-table-column>
					<el-table-column
						prop="prop2"
						:label="defaultFiledShowConf.prop2.desc"
						v-if="defaultFiledShowConf.prop2.frontShow"
						align="center"
						width="100"
					></el-table-column>
					<el-table-column
						prop="prop3"
						:label="defaultFiledShowConf.prop3.desc"
						v-if="defaultFiledShowConf.prop3.frontShow"
						align="center"
						width="100"
					></el-table-column>
					<el-table-column
						prop="prop4"
						:label="defaultFiledShowConf.prop4.desc"
						v-if="defaultFiledShowConf.prop4.frontShow"
						align="center"
						width="100"
					></el-table-column>
					<el-table-column
						prop="prop5"
						:label="defaultFiledShowConf.prop5.desc"
						v-if="defaultFiledShowConf.prop5.frontShow"
						align="center"
						width="100"
					></el-table-column>
					<el-table-column
						prop="prop6"
						:label="defaultFiledShowConf.prop6.desc"
						v-if="defaultFiledShowConf.prop6.frontShow"
						align="center"
						width="100"
					></el-table-column>
					<el-table-column label="到期时间" width="140">
						<template slot-scope="scope">
							<span :style="computeColor(scope.row.deadline)">{{
								computeTime(scope.row.deadline)
							}}</span>
						</template>
					</el-table-column>
				</el-table>
			</el-main>
			<el-footer height="52px">
				<el-row type="flex" justify="end">
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="pagination.page"
						:page-sizes="[10, 20, 50, 100]"
						:page-size="pagination.pageSize"
						layout="total, sizes, prev, pager, next, jumper"
						:total="total"
					></el-pagination>
				</el-row>
			</el-footer>
			<!-- 流程传阅-->
			<TaskToCopyTo ref="taskToCopyTo" :taskId="ids" />
			<TaskImage
				ref="taskImage"
				:bpmnInstId="selectBpmnInstId"
				:instId="selectInstanceId"
				:defId="selectDefId"
			/>
		</el-container>
		<el-dialog
			:visible.sync="batchDialogVisible"
			title="批量处理"
			@close="batchHandleSetting = {}"
			@opened="afterOpen"
		>
			<el-form
				v-model="batchHandleSetting"
				label-width="120px"
				ref="batchHandleForm"
			>
				<el-form-item label="审批意见">
					<el-input
						type="textarea"
						placeholder="请输入审批内容"
						v-model="batchHandleSetting.opinion"
						maxlength="500"
						show-word-limit
					></el-input>
				</el-form-item>
				<el-form-item label="审批动作" validate="required">
					<el-select v-model="batchHandleSetting.action" validate="required">
						<el-option key="agree" label="同意" value="agree"></el-option>
						<el-option key="reject" label="驳回" value="reject"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					label="驳回重提模式"
					v-if="
						batchHandleSetting.action === 'reject' ||
						batchHandleSetting.action === 'backToStart'
					"
					validate="required"
				>
					<el-radio v-model="batchHandleSetting.backHandMode" label="normal"
						>重新审批</el-radio
					>
					<el-radio v-model="batchHandleSetting.backHandMode" label="direct"
						>回到本节点</el-radio
					>
				</el-form-item>
				<el-form-item
					label="驳回方式"
					v-if="
						batchHandleSetting.action === 'reject' ||
						batchHandleSetting.action === 'backToStart'
					"
					validate="required"
				>
					<el-radio v-model="batchHandleSetting.rejectType" label="backToStart"
						>驳回到发起人</el-radio
					>
					<el-radio v-model="batchHandleSetting.rejectType" label="reject"
						>驳回上一步</el-radio
					>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button
					type="primary"
					@click="batchHandleSubmit"
					:loading="batchSubmitBtnLoad"
					>提交</el-button
				>
				<el-button @click="batchDialogVisible = false">取消</el-button>
			</span>
		</el-dialog>

		<el-dialog
			:visible.sync="batchResultDialog"
			title="处理结果"
			@close="afterResultClose"
		>
			<template>
				<div v-if="batchUnBatchableList.length !== 0">
					<span>以下任务不允许批量办理，请进入页面审批</span>
					<div v-for="task in batchUnBatchableList">
						<el-link type="primary" @click="open(task)">{{
							task.subject
						}}</el-link>
					</div>
				</div>
			</template>
			<template>
				<div v-if="batchCompleteList.length !== 0">
					<span>以下任务处理完成</span>
					<div v-for="task in batchCompleteList">
						<el-link type="success" @click="doneView(task.procInstId)">{{
							task.subject
						}}</el-link>
					</div>
				</div>
			</template>
			<template>
				<div v-if="batchFailedList.length !== 0">
					<span>以下任务处理失败</span>
					<div v-for="task in batchFailedList">
						<el-link type="danger"
							>{{ task.subject }}({{ failedMsgMap[task.id] }})</el-link
						>
					</div>
				</div>
			</template>
			<template>
				<div v-if="batchNotAuthList.length !== 0">
					<span>以下任务您无权处理</span>
					<div v-for="task in batchNotAuthList">
						<el-link disabled>{{ task.subject }}</el-link>
					</div>
				</div>
			</template>
		</el-dialog>
	</el-container>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import process from '@/api/process';
import FlowTree from '@/components/flow/flowTree.vue';
import utils from '@/utils.js';
import { Message } from 'element-ui';
import TaskImage from '@/components/flow/task/taskImage.vue';
import TaskToCopyTo from '@/components/flow/task/taskToCopyTo.vue';
import eipOrgSelector from '@/components/eipControl/selector/EipOrgSelector.vue';
import req from '@/request.js';
const STATUS = {
	NORMAL: '待办',
	TRANSFORMED: '流转',
	TRANSFORMEDINQU: '征询',
	DELIVERTO: '转办',
	FOLLOW: '跟踪',
	COMMU: '沟通',
	BACK: '驳回',
	ADDSIGN: '会签加签',
	AGENT: '委托',
	SHARE: '共享',
	BACKSHARE: '驳回共享',
	APPROVELINEED: '并行审批',
	SIGNSEQUENCEED: '顺序签署',
	SIGNLINEED: '并行签署',
	USERADDSIGN: '用户加签',
};
export default {
	name: 'todo',
	components: {
		FlowTree,
		TaskToCopyTo,
		eipOrgSelector,
		TaskImage,
	},
	props: {
		defKey: {
			type: String,
			default: '',
		},
		orgName: { type: String, default: '' },
		orgId: { type: String, default: '' },
	},
	data() {
		return {
			isAsideShow: false,
			batchHandleIds: [],
			asideShow: false,
			form: { tableData: '', date: '', orgName: '', orgId: '' },
			status: STATUS,
			currentTree: '',
			fullscreenLoading: true,
			sorter: [],
			urgentStateConf: {},
			urgentStateConfList: [],
			urgentStateVal: '',
			ids: '', //待办任务id集合
			defaultFiledShowConf: '',
			defaultFiledShowConfList: [
				{ name: 'subject', desc: '标题', frontShow: true },
				{ name: 'procInstId', desc: '流程编号', frontShow: true },
				{ name: 'procDefName', desc: '流程名称', frontShow: true },
				{ name: 'name', desc: '任务名称', frontShow: true },
				{ name: 'status', desc: '类型', frontShow: true },
				{ name: 'createTime', desc: '创建时间', frontShow: true },
				{ name: 'creator', desc: '创建人', frontShow: true },
				{ name: 'urgentStateValue', desc: '紧急状态', frontShow: true },
				{ name: 'dueExpDate', desc: '到期时间', frontShow: false },
				{ name: 'ownerName', desc: '所属人', frontShow: false },
				{ name: 'assigneeName', desc: '待审批人', frontShow: false },
				{ name: 'prop1', desc: '扩展1', frontShow: false },
				{ name: 'prop2', desc: '扩展2', frontShow: false },
				{ name: 'prop3', desc: '扩展3', frontShow: false },
				{ name: 'prop4', desc: '扩展4', frontShow: false },
				{ name: 'prop5', desc: '扩展5', frontShow: false },
				{ name: 'prop6', desc: '扩展6', frontShow: false },
			],
			selectInstanceId: '',
			selectBpmnInstId: '',
			selectDefId: '',
			batchDialogVisible: false,
			batchHandleSetting: {},
			batchResultDialog: false,
			batchCompleteList: [],
			batchFailedList: [],
			batchUnBatchableList: [],
			batchNotAuthList: [],
			failedMsgMap: {},
			batchSubmitBtnLoad: false,
			skipMsg: '',
			unBatchMsg: '',
		};
	},
	watch: {
		'form.orgId': {
			handler(newName, oldName) {
				this.search('find');
			},
			immediate: true,
		},
	},
	computed: {
		...mapState('storeProcess', ['rows', 'pagination', 'total']),
		currentSwitchValue() {
			return (
				localStorage.todoAsideShow === 'true' ||
				localStorage.todoAsideShow === true
			);
		},
	},
	created() {
		this.getTaskList();
		this.asideShow = this.currentSwitchValue;
		this.isAsideShow = this.currentSwitchValue;
	},
	methods: {
		//将当前展开或者收起的值存在localStorage中
		handleSwitch(val) {
			localStorage.todoAsideShow = val;
		},
		getTaskList() {
			this.$http
				.get(
					'${portal}/sys/sysProperties/v1/getDecryptByAlias?alias=taskListFiledConf'
				)
				.then(resp => {
					let tempConf = {};
					if (resp.data) {
						tempConf = JSON.parse(resp.data.value);
					} else {
						tempConf = this.defaultFiledShowConfList;
					}
					this.formatConfListToObj(tempConf);
				});

			let querys = [];
			if (this.defKey) {
				querys.push({
					property: 'bt.proc_def_key_',
					value: this.defKey,
					operation: 'EQUAL',
					relation: 'AND',
				});
			}
			//判断是否有URL传参
			if (this.orgName && this.orgId) {
				this.form.orgName = this.orgName;
				this.form.orgId = this.orgId;
				querys.push({
					group: 'orgId',
					property: 'inst.CREATE_ORG_PATH_',
					value: this.orgId,
					operation: 'LIKE',
					relation: 'AND',
				});
			}
			let pageBean = {
				pageBean: { page: '1', pageSize: '10', showTotal: 'true' },
				querys: querys,
			}; //初次加载默认pageBean
			// this.$store
			//   .dispatch("storeProcess/getUrgentStateConf", { getConf: true })
			//   .then(data => {
			this.$store
				.dispatch('storeProcess/getTodoByPagination', pageBean)
				.then(() => {
					//页面加载调用tudo.js里面的分页方法
					this.fullscreenLoading = false;
				});
			// if (data.conf) {
			//   try {
			//     data.conf = JSON.parse(data.conf);
			//   } catch (error) {
			//     data.conf = window.eval("(" + data.conf + ")");
			//   }
			//   this.urgentStateConfList = data.conf;
			//   let conf = {};
			//   for (let index = 0, c; (c = data.conf[index++]); ) {
			//     if (c.default) {
			//       this.urgentStateConf.defaultValue = c.state;
			//     }
			//     conf[c.state] = c;
			//   }
			//   this.urgentStateConf.conf = conf;
			// }
			// });
		},
		rowClick(row, column, event) {
			//操作列不触发多选按钮
			if (column && column.label == '流程图') {
				return;
			}
			this.$refs.htTable.toggleRowSelection(row);
		},
		//流程传阅
		taskToCopyTo() {
			if (this.ids == '') {
				Message.warning('请选择要传阅的流程');
				return;
			}
			this.$refs.taskToCopyTo.handleClose(); //父组件调用子组件方法
		},
		//批量勾选待办流程获取
		handleSelectionChange(val) {
			this.ids = '';
			if (val.length > 0) {
				for (let i = 0; i < val.length; i++) {
					this.ids = this.ids + val[i].id + ',';
				}
				this.ids = this.ids.substring(0, this.ids.length - 1);
			}
		},
		//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');
			}
		},
		// 处理排序
		handleSortChange: function (m) {
			this.sorter.splice(
				this.sorter.findIndex(s => s.property == m.prop),
				1
			);
			if (m.order) {
				this.sorter.push({
					property: m.prop,
					direction: m.order == 'ascending' ? 'ASC' : 'DESC',
				});
			}
			this.search();
		},
		// 查询
		search(str) {
			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) {
				querys = [
					{
						property: 'bt.subject_',
						value: this.form.tableData,
						group: 'main',
						operation: 'LIKE',
						relation: 'OR',
					},
					{
						property: 'bt.proc_inst_id_',
						value: this.form.tableData,
						group: 'main',
						operation: 'LIKE',
						relation: 'OR',
					},
					{
						property: 'bt.proc_def_name_',
						value: this.form.tableData,
						group: 'main',
						operation: 'LIKE',
						relation: 'OR',
					},
					{
						property: 'bt.name_',
						value: this.form.tableData,
						group: 'main',
						operation: 'LIKE',
						relation: 'OR',
					},
				];
				let temp = querys[0];
				for (let index = 1; index < 7; index++) {
					let query = JSON.parse(JSON.stringify(temp));
					query.property = 'prop' + index;
					querys.push(query);
				}
			}
			if (this.form.orgId) {
				querys.push({
					property: 'inst.CREATE_ORG_PATH_',
					value: this.form.orgId,
					group: 'orgId',
					operation: 'LIKE',
					relation: 'AND',
				});
			}
			if (this.currentTree) {
				querys.push({
					property: 'bt.type_id_',
					value: this.currentTree,
					group: 'typeId',
					operation: 'IN',
					relation: 'AND',
				});
			}
			if (this.defKey) {
				querys.push({
					property: 'bt.proc_def_key_',
					value: this.defKey,
					operation: 'EQUAL',
					relation: 'AND',
				});
			}
			if (this.form.date) {
				beginDate = utils.formatDate(this.form.date[0].getTime());
				endDate = utils.formatDate(this.form.date[1].getTime());
				querys.push({
					property: 'bt.create_time_',
					value: [beginDate, endDate],
					group: 'time',
					operation: 'BETWEEN',
					relation: 'AND',
				});
			}
			queryFilter = { pageBean: this.pagination, querys, sorter: this.sorter };
			this.openFullScreen();
			this.$store
				.dispatch('storeProcess/getTodoByPagination', queryFilter)
				.then(() => {
					this.fullscreenLoading = false;
				});
		},
		//重置
		reset() {
			this.form = { tableData: '', date: '', orgName: '', orgId: '' };
			this.search('find');
		},
		handleRowClick(row, newWin) {
			if (row.status == 'SHARE' || row.status == 'BACKSHARE') {
				if (row.identityList && row.identityList.length == 1) {
					let url = '/task/' + row.id + '/' + row.identityList[0].id;
					this.handleOpenUrl(url, newWin);
				} else {
					let html =
						'<select ref=' +
						Math.random() +
						' id="approvalLeaderSelect" style="width: 200px;height: 30px;border-radius: 4px;margin: 20px 70px;" ><option value="">请选择</option>';
					row.identityList.forEach(identity => {
						html +=
							'<option value="' +
							identity.id +
							'">' +
							identity.name +
							'</option>';
					});
					html += '</select>';
					let this_ = this;
					this.$alert(html, '请选择一个领导代为审批', {
						dangerouslyUseHTMLString: true,
						beforeClose: function (action, instance, done) {
							if (action == 'confirm') {
								let se = document.getElementById('approvalLeaderSelect');
								if (se.selectedIndex == 0) {
									this.$message.warning('请选择代为审批的领导');
								} else {
									instance.close();
									this_.handleOpenUrl(
										'/task/' + row.id + '/' + se[se.selectedIndex].value,
										newWin
									);
								}
							} else {
								instance.close();
							}
						},
					});
				}
			} else if (
				row.status == 'AGENT' &&
				row.ownerId != row.assigneeId &&
				row.ownerId == this.$store.state.login.currentUser.userId
			) {
				//委托任务
				this.handleOpenUrl('/instRead/' + row.procInstId + '/agent', newWin);
			} else if (row.status == 'FOLLOW') {
				//跟踪任务
				this.handleOpenUrl('/taskRead/' + row.id + '/FOLLOW', newWin);
			} else {
				let url = '/task/' + row.id + '/0';
				if (this.defKey) {
					url = '/sysModuleInst/' + row.id + '/0' + '/' + this.defKey + '/true';
				}
				this.handleOpenUrl(url, 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.currentTree = '';
				this.openFullScreen();
				let pageBean = { pageBean: this.pagination };
				this.$store
					.dispatch('storeProcess/getTodoByPagination', pageBean)
					.then(() => {
						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);
			}
		},
		formatConfListToObj(tempList) {
			let editConfObj = {};
			tempList.forEach(c => {
				let key = c.name;
				editConfObj[key] = c;
			});
			this.$set(this, 'defaultFiledShowConf', editConfObj);
		},
		loadCount() {
			return process.getCountByUserId(this.pagination);
		},
		computeTime(deadline) {
			if (deadline) {
				let time = new Date(deadline).getTime();
				let nowTime = new Date().getTime();
				let duration = time - nowTime;
				if (duration > 0) return deadline;
				else {
					let hour = Math.floor(Math.abs(duration / 3600000));
					let minute = Math.ceil(Math.abs((duration % 3600000) / 60000));
					return '已到期' + hour + '时' + minute + '分';
				}
			}
			return '';
		},
		computeColor(deadline) {
			if (deadline) {
				let time = new Date(deadline).getTime();
				let nowTime = new Date().getTime();
				let day = (time - nowTime) / 86400000;
				if (day > 0)
					//绿色
					return { color: '#22870D' };
				else {
					if (Math.ceil(Math.abs(day)) >= 3)
						//红色
						return { color: '#F1300A' };
					//黄色
					else return { color: '#E1A306' };
				}
			}
			return {};
		},
		async handleShowTaskImage(row) {
			await this.changeSeletion(row);
			this.$refs.taskImage.handleOpen();
		},
		changeSeletion(row) {
			this.selectInstanceId = row.procInstId;
			this.selectBpmnInstId = row.bpmnInstId;
		},
		batchHandle() {
			let selectTasks = this.$refs.htTable.selection;
			if (!selectTasks || selectTasks.length == 0) {
				this.$message({ type: 'warning', message: '请至少选择一条任务' });
				return;
			}
			//忽略掉非待办类型的任务
			let ids = [];
			this.skipMsg = '';
			for (let i = selectTasks.length - 1; i >= 0; i--) {
				if (selectTasks[i].status == 'NORMAL') {
					ids.push(selectTasks[i].id);
				} else {
					this.skipMsg += selectTasks[i].subject + '</br>';
					selectTasks.splice(i, 1);
				}
			}
			if (ids.length > 0) {
				req
					.get(
						'${bpmRunTime}/runtime/task/v1/filterUnBatchable?taskIds=' +
							ids.join(',')
					)
					.then(resp => {
						if (resp.data.state && resp.data.value) {
							if (resp.data.value.length != ids.length) {
								ids = resp.data.value;
								let unBatchMsg = '以下任务未配置批量处理<br/>';
								for (let i = selectTasks.length - 1; i >= 0; i--) {
									if (!resp.data.value.includes(selectTasks[i].id)) {
										unBatchMsg += selectTasks[i].subject + '<br/>';
										selectTasks.splice(i, 1);
									}
								}
								//this.$message({type:"warning",dangerouslyUseHTMLString:true,message:unBatchMsg});
								this.unBatchMsg = unBatchMsg;
							}
							if (ids && ids.length > 0) {
								this.batchHandleIds = ids;
								this.batchDialogVisible = true;
							} else {
								this.showMsg();
							}
						}
					});
			} else {
				if (this.skipMsg) {
					this.showMsg();
				}
			}
			this.batchHandleCheck();
		},
		batchHandleCheck() {},
		batchHandleSubmit() {
			let errMsg = '';
			this.batchSubmitBtnLoad = true;
			if (!this.batchHandleSetting.opinion || !this.batchHandleSetting.action) {
				errMsg = '完善表单信息';
			}
			if (
				this.batchHandleSetting.action == 'reject' &&
				(!this.batchHandleSetting.backHandMode ||
					!this.batchHandleSetting.rejectType)
			) {
				errMsg = '请完善驳回设置';
			}
			if (errMsg) {
				this.$message({ type: 'warning', message: errMsg });
				this.batchSubmitBtnLoad = false;
				return;
			}
			let action;
			if (this.batchHandleSetting.action == 'agree') {
				action = 'agree';
			} else {
				action =
					this.batchHandleSetting.rejectType || this.batchHandleSetting.action;
			}
			this.$http
				.post(window.context.bpmRunTime + '/runtime/task/v1/batchHandle', {
					taskIds: this.batchHandleIds.join(','),
					action: action,
					opinion: this.batchHandleSetting.opinion,
				})
				.then(resp => {
					if (resp.data && resp.data.state) {
						this.batchDialogVisible = false;
						this.batchSubmitBtnLoad = false;
						this.showBatchResult(resp.data.value);
					}
				});
		},
		showBatchResult(taskMaps) {
			this.batchCompleteList = taskMaps['complete'];
			this.batchFailedList = taskMaps['failedList'];
			this.batchUnBatchableList = taskMaps['unHandleList'];
			this.batchNotAuthList = taskMaps['notAuth'];
			this.failedMsgMap = taskMaps['failedMsg'];
			this.batchResultDialog = true;
		},
		afterBatchClose() {
			this.batchDialogVisible = false;
			this.batchHandleSetting = {};
		},
		afterResultClose() {
			this.batchCompleteList = [];
			this.batchFailedList = [];
			this.batchUnBatchableList = [];
			this.batchNotAuthList = [];
			this.failedMsgMap = [];
			this.batchResultDialog = false;
			this.search('find');
		},
		open(row) {
			let token = this.$store.state.login.currentUser.token;
			if (row.status == 'SHARE' || row.status == 'BACKSHARE') {
				if (row.identityList && row.identityList.length == 1) {
					let url =
						'/task/' +
						row.id +
						'/' +
						row.identityList[0].id +
						'?token=' +
						token;
					//this.$router.push(url);
					window.open(window.context.front + url, '_blank');
				} else {
					let html =
						'<select ref=' +
						Math.random() +
						' id="approvalLeaderSelect" style="width: 200px;height: 30px;border-radius: 4px;margin: 20px 70px;" ><option value="">请选择</option>';
					row.identityList.forEach(identity => {
						html +=
							'<option value="' +
							identity.id +
							'">' +
							identity.name +
							'</option>';
					});
					html += '</select>';
					// let this_ = this;
					this.$alert(html, '请选择一个领导代为审批', {
						dangerouslyUseHTMLString: true,
						beforeClose: function (action, instance, done) {
							if (action == 'confirm') {
								let se = document.getElementById('approvalLeaderSelect');
								if (se.selectedIndex == 0) {
									this.$message.warning('请选择代为审批的领导');
								} else {
									instance.close();
									/*this_.$router.push(
                          "/task/" + row.id + "/" + se[se.selectedIndex].value
                  );*/
									let url =
										window.context.front +
										'/task/' +
										row.id +
										'/' +
										se[se.selectedIndex].value +
										'?token=' +
										token;
									window.open(url, '_blank');
								}
							} else {
								instance.close();
							}
						},
					});
				}
			} else if (
				row.status == 'AGENT' &&
				row.ownerId != row.assigneeId &&
				row.ownerId == this.$store.state.login.currentUser.userId
			) {
				//委托任务
				//this.$router.push("/instRead/" + row.procInstId + "/agent");
				window.open(
					window.context.front +
						'/instRead/' +
						row.procInstId +
						'/agent' +
						'?token=' +
						token,
					'_blank'
				);
			} else if (row.status == 'FOLLOW') {
				//跟踪任务
				//this.$router.push("/taskRead/" + row.id + "/FOLLOW");
				window.open(
					window.context.front +
						'/taskRead/' +
						row.id +
						'/FOLLOW' +
						'?token=' +
						token,
					'_blank'
				);
			} else {
				let url = '/task/' + row.id + '/0';
				if (this.defKey) {
					url += '/noSingle' + '?token=' + token;
				}
				//this.$router.push(url);
				window.open(window.context.front + url, '_blank');
			}
		},
		doneView(procId) {
			let token = this.$store.state.login.currentUser.token;
			let url =
				window.context.front + '/inst/' + procId + '/doneList?token=' + token;
			window.open(url, '_blank');
		},
		afterOpen() {
			this.showMsg();
		},
		showMsg() {
			let message = '';
			if (this.skipMsg) {
				message =
					'以下任务不是待办任务，不支持批量处理:</br>' + this.skipMsg + '<br/>';
			}
			if (this.unBatchMsg) {
				message += this.unBatchMsg;
			}
			if (message) {
				this.$message({
					dangerouslyUseHTMLString: true,
					message,
					type: 'warning',
				});
			}
		},
	},
};
</script>

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

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

.el-table /deep/ tr.todo-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;
}

.todo-subject {
	cursor: pointer;
}

.todo-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,
		.form_org_selector {
			margin-right: 10px;
			min-width: 300px;
		}
	}
}
.el-table /deep/ .icon-flow1 {
	color: #2761ff;
}
</style>
