<template>
    <div class="page">
        <template v-if="showRight">
			<headNav :canBack="false" @rightClick="rightClick" @leftAction="onLeftAction" iconName="plus" title="执行任务"></headNav>
		</template>
		<template v-else>
			<headNav title="执行任务"></headNav>
		</template>

		<!-- 搜索 -->
		<div class="search" v-if="showRight">
			<van-search
				placeholder="请输入搜索关键词"
				input-align="center"
				readonly
				@click.prevent="showSearchItems"/>
		</div>

		<div class="numInfo" :class="showRight?'':'numInfo1'">
			<div class="left">
				<van-button plain hairline icon="clock-o" size="mini" type="info">{{totalTime}}</van-button>
				共需检查：<span>{{ totalNum }}</span>项
			</div>
			<div class="right df">
				<div class="FontColorOther pr15">
					已完成：<span>{{ completeNum }}</span>项
				</div>
				<div class="FontColorWarn">
					未检查：<span>{{ uncheckNum }}</span>项
				</div>
			</div>
		</div>

        <div class="list">
            <van-tree-select height="100%" :items="nodes" :main-active-index.sync="active" @click-nav="handleClickNav">
                <template #content>
                    <template v-if="nodes[active] && nodes[active].items">
                        <div class="list-item" v-for="(item, itemIndex) in nodes[active].items" :key="item.id">
                            <van-cell class="item-title unLine" :class="item.haveResult?'errorItem':''" :title="item.handBook && item.handBook.enforce_content || item.item_content || item.item_name" is-link :arrow-direction="item.show?'down':'left'" @click="toggleItemShow(item)"/>
							<div class="action">
								<div class="action-item" :class="{'action-item-active': item.customAction==itemAction.zan}" @click="praiseItem(item)">
									<span class="iconfont icon-zan"></span>
									<span>赞</span>
								</div>
								<div class="action-item" :class="{'action-item-active': item.customAction==itemAction.cai}" @click="caiItem(item)">
									<span class="iconfont icon-cai"></span>
									<span>踩</span>
								</div>
							</div>
                            <template v-if="item.handBook">
								<van-cell class="unLine mt10 titleLine bolder" center title="检查流程及方法"></van-cell>
								<div class="item-row" v-if="item.handBook.enforce_method" v-html="item.handBook.enforce_method"></div>
								<van-cell class="unLine bolder" :class="item.handBook.haveProblems?'haveContent':''" center title="常见问题" :value="item.handBook.haveProblems?'[查看]>':'暂无'" @click="showPictxt(item)"></van-cell>
								<template v-if="item.handBook.problems">
									<problem :list="item.handBook.problems" @click.native="showPictxt(item)"></problem>
									<!-- <div v-for="(problem, problemIndex) in item.handBook.problems" :key="problem.id" class="item-row">
										<div>问题{{problemIndex+1}}.</div>
										<div v-if="problem.problem_images" class="problems-images">
											<van-image v-for="(url, urlIndex) in problem.problem_images" :key="urlIndex" width="50" height="50" :src="url" @click="previewImage(problem.problem_images, urlIndex)" />
										</div>
										<div class="problems-desc">{{problem.problem_desc || ''}}</div>
									</div> -->
								</template>
							</template>
							<van-cell title="检查结果">
								<!-- 0-不涉及,1-合格,2-不合格 -->
								<van-radio-group v-model="item.check_result" direction="horizontal" @change="updateCheckOption(item)">
									<van-radio name="1">合格</van-radio>
									<van-radio name="2">不合格</van-radio>
									<van-radio name="0">不涉及</van-radio>
								</van-radio-group>
							</van-cell>
							<template v-if="item.show">
								<van-cell title="检查类型" :value="item.handBook && item.handBook.enforce_class || '其他'" />
								<template v-if="item.handBook">
									<van-cell v-show="item.show" title="历史隐患" :class="haveHistory?'haveContent':''" :value="haveHistory?'[查看]>':'暂无'" @click="showHistory" />
									<van-cell v-show="item.show" title="设置要求" :class="item.haveRequire?'haveContent':''" :value="item.haveRequire ? '[查看]>':'暂无'" @click="showSettingExpect(item)" />
									<van-cell v-show="item.handBook && item.handBook.result_options && item.handBook.result_options.length > 0" title="检查选项">
										<van-radio-group v-model="item.check_options" direction="horizontal">
											<van-radio v-for="(option, optionIndex) in item.handBook.result_options" :key="optionIndex" :name="option">{{option}}</van-radio>
										</van-radio-group>
									</van-cell>
									<template v-if="item.handBook && item.handBook.other_enforce_item && item.handBook.other_enforce_item.length > 0">
										<van-field v-for="(other, otherIndex) in item.handBook.other_enforce_item" :key="otherIndex" v-model="other.v" :label="other.k" maxlength="100" placeholder="不能超过100字符" @blur="blurOtherInput(item, itemIndex)" />
									</template>
								</template>
								<div v-if="item.records && item.records.length > 0" class="records">
									<div class="record" v-for="(record, recordIndex) in item.records" :key="recordIndex">
										<van-cell title="检查情况" class="noline" />
										<van-field v-model="record.check_desc" rows="2" autosize type="textarea" placeholder="请输入"/>
										<van-cell title="现场图片" class="noline" />
										<div class="files">
											<van-uploader
												v-model="record.fileList"
												:max-count="4"
												:after-read="afterRead"
												:before-read="beforeAvatarUpload"
												multiple
												@delete="deleteRecordFile"
												capture="camera"
											/>
										</div>
									</div>
									<div class="add">
										<van-button round size="small" type="info" @click="addRecord(item)">添加检查情况</van-button>
									</div>
								</div>
							</template>
                        </div>
                    </template>
                </template>
            </van-tree-select>
        </div>
		<div class="submit">
			<van-button type="info" style="width: 100%;" @click="submitCheck">提交</van-button>
		</div>

        <van-overlay :show="showTaskCount">
			<div class="wrapper" @click.stop>
				<execute-task-tips :taskCount.sync="taskCount" @cancel="showTaskCount=false" @confirm="handleConfirmTaskInfo"></execute-task-tips>
			</div>
		</van-overlay>

		<van-dialog v-model="showCaiComment" title="反馈意见" show-cancel-button :before-close="beforeCloseCaiDialog" @confirm="confirmCaiItem">
			<div class="box">
				<van-field
					v-model="caiComment"
					rows="5"
					autosize
					type="textarea"
					maxlength="300"
					placeholder="请输入您的反馈意见，方便我们及时改正"
					show-word-limit
				/>
			</div>
		</van-dialog>

		<v-mask :showOverLay="showOverLay" tipMsg="加载中..."></v-mask>
    </div>
</template>

<script>
import headNav from '@/components/headNav.vue';
import mask_overLay from '@/components/overLay_xy.vue';
import executeTaskTips from '@/components/executeTaskTips.vue';
import Problem from './component/Problem.vue';

import { ImagePreview, Notify, Dialog } from 'vant';
import { compressAccurately } from "image-conversion";
import { isEmpty, notEmpty, formatDistanceDate } from '@/utils/tool';
import { handleProblemImgs } from '@/utils/index';
import { get, post, put, deleteRequest } from "@/utils/http.js";
import templateData from '@/config/check';
import executeStepMixin from '@/mixins/executeStep';

export default {
    components: {
        headNav,
        'v-mask': mask_overLay,
        executeTaskTips,
		Problem,
    },
	inject: ['reload'],
	mixins: [executeStepMixin],
    data () {
        return {
			isLoading: false,
            showOverLay: false,
			showRight: false,
            totalNum: 0,
            completeNum: 0,
            uncheckNum: 0,
            showTaskCount: false,
			totalTime: '00:00',
            taskCount: {
				time: ' ',
				total: 0,
				uncheck:0,
				pass: 0,
				refuse: 0,
				uninvolved: 0,
			},
            nodes: [],
			nodesItem: [],
            active: 0,
            formData: null,
			showCaiComment: false,
			caiComment: '',
			handleActionItem: null,
			itemAction: {
				zan: 1,
				cai: 2,
				none: 10,
			},
			executeTimer: null,
			haveHistory: true,
        }
    },
	computed: {
		dailyId() {
			return this.$route.params.ID
		},
		enforceId() {
			if (this.formData) {
				return this.formData.enforce_obj_id
			}
			return ''
		}
	},
	beforeRouteEnter: (to, from, next) => {
		// to.meta.keepAlive = true;
		if (from.name != 'historyItems' && from.name != 'checkStandardExplain' && from.name != 'dailyPicTxt') {
			next(vm => {
				if (vm._data.formData) {
					vm.reload();
				}
			});
		} else {
			next();
		}
	},
    mounted () {
        if (this.dailyId) {
            this.loadTaskData();
        }
    },
    methods: {
		onLeftAction() {
			const vm = this;
			Dialog.confirm({
				title: '温馨提示',
				message: '是否放弃该任务？',
				confirmButtonText: '暂存',
				cancelButtonText: '放弃',
			}).then(() => {
				// on confirm
				vm.handleConfirmTaskInfo(true);
			}).catch(() => {
				// on cancel
				vm.showOverLay = true;
				put(`/v2/api/enforce-job/${this.dailyId}/exchange`).then(res => {
					vm.showOverLay = false;
					vm.$router.back();
				});
			});
		},
		handleClickNav() {
			// setTimeout(() => {
				const e = document.getElementsByClassName('van-tree-select__content')[0];
				if (e) {
					e.scrollTop = 0;
				}
			// }, 500);
		},
		haveSettingExpect(item) {
			return item && item.handBook && item.handBook.setting_expect && notEmpty(item.handBook.setting_expect);
		},
        showSearchItems() {
			if (this.enforceId) {
				this.saveCacheItems();
				this.$router.push(`/dailyItemSearch/${this.dailyId}/${this.enforceId}`);
			}
		},
        rightClick() {
			if (this.enforceId) {
				this.saveCacheItems();
				this.$router.push(`/special/exec/add/${this.dailyId}/${this.enforceId}`);
			}
			// const vm = this;
			// BUS.$on('addItem', function() {
			// 	vm.loadTaskData();
			// });
		},
		saveCacheItems() {
			this.showOverLay = false;
			if (this.checkNodesFile(true) === false) {
				this.commitCacheItems();
			}
		},
		commitCacheItems() {
			this.showOverLay = false;
			let items = [];
			this.nodes.map(node => {
				if (node.items && node.items.length > 0) {
					node.items.map(item => {
						if (notEmpty(item.check_result)) {
							let obj = Object.assign({}, item);
							obj.check_result = parseInt(obj.check_result);
							items.push(obj);
						}
					});
				}
			});
			items.map(item => {
				if (item.records && item.records.length > 0) {
					item.records.map(record => {
						let pictures = [];
						record.fileList.map(file => {
							pictures.push(file.fileID);
						});
						record.pictures = pictures.join(',');
					});
				}
				if (item.handBook && item.handBook.other_enforce_item && item.handBook.other_enforce_item.length > 0) {
					let others = [];
					item.handBook.other_enforce_item.map(other => {
						const otherV = other.v ? other.v : '';
						others.push(otherV);
					});
					item.enforce_job_node_item = others.join(',');
				}
			});
			if (items.length > 0) {
				this.$http.put(`/v2/api/enforce-job/item`, items).then(res => {});
			}
		},
		blurOtherInput(item, itemIndex) {
			// const items = this.nodes[this.active];
			// this.$set(items, item, itemIndex);
			const obj = this.nodes[this.active];
			this.$set(this.nodes, this.active, obj);
		},
		runExecuteTimer() {
			if (!this.executeTimer && this.formData.start_time) {
				let startDate = new Date(this.formData.start_time);
				const vm = this;
				const finished = this.formData.job_status == 'ARCHIVED';
				const dis = parseInt((new Date() - startDate)/1000);
				if (dis < 60) {
					startDate = new Date(); 
				}
				this.executeTimer = setInterval(() => {
					let endDate = new Date();
					if (finished && this.formData.finish_time) {
						endDate = new Date(this.formData.finish_time);
						clearInterval(vm.executeTimer);
					}
					vm.totalTime = formatDistanceDate(startDate, endDate);
				}, 1000);
			}
		},
        async loadTaskData() {
			if (this.isLoading || this.formData) {
				return;
			}
			this.isLoading = true;
			this.showOverLay = true
			const res = await get(`/v2/api/enforce-job/${this.dailyId}`);
			if (res && res.check_nodes) {
				this.formData = res;
				if (res.start_time) {
					this.runExecuteTimer();
				}

				get(`/v2/api/enforce-job/item?page=1&size=2&query=check_result==2;enforce_obj_id==${res.enforce_obj_id}`).then(res => {
					if (res && res.data && res.data.length > 0) {
						this.haveHistory = true;
					}
					else {
						this.haveHistory = false;
					}
				})

				const nodes = this.formData.check_nodes || [];
				this.totalNum = nodes.length;
				if (nodes.length > 0) {
					this.showRight = true;
					nodes.forEach((node, nodeIndex) => {
						node.text = node.node_name;
						node.badge = '';
						node.className = '';
						let nodeItems = [];
						if (node.items) {
							node.items.forEach((itemRes, itemIndex) => {
								const show = nodeIndex == 0 && itemIndex == 0;
								let item = Object.assign({
									show: show
								}, itemRes);
								item.check_result = item.check_result + '';
								// if (item.item_id && item.item_type == '0') {
								// 	item.handBook = {
								// 		request: true,
								// 	};
								// }
								if (!item.records || item.records.length === 0) {
									item.records = [{
										fileList: [],
										check_desc: '',
										pictures: '',
										item_id: item.item_id
									}];
								}
                                else {
                                    item.records.map(record => {
                                        let arr = new Array();
                                        if (record.pictures) {
                                            record.pictures.split(',').map(fileId => {
                                                const url = this.handleImgUrl(fileId);
                                                arr.push({
													url,
													isImage: true,
													fileID: fileId
												});
                                            });
                                        }
										record.fileList = arr;
                                    });
                                }
								nodeItems.push(item);
							})
						}
						node.items = nodeItems;
					});

					const books = await get(`/v2/api/enforce_template_handbook/copy/job/${res.id}`);
					const commentRes = await get(`/v2/api/enforce_comment?page=1&size=100000&query=job_id==${res.id}`);
					const comments = commentRes && commentRes.data || [];
					for (let index = 0; index < nodes.length; index++) {
						const node = nodes[index];
						if (node.items && node.items.length > 0) {
							for (let j = 0; j < node.items.length; j++) {
								const item = node.items[j];
								item.haveResult = false;
								item.customAction = this.itemAction.none;
								const commentList = comments.filter(comment => item.id == comment.item_id);
								if (commentList.length > 0) {
									item.actionData = commentList[0];
									if (item.actionData.comment_type == 'APPROVE') {
										item.customAction = this.itemAction.zan;
									}
									if (item.actionData.comment_type == 'CRITICISM') {
										item.customAction = this.itemAction.cai;
									}
								}
								if (item.item_id) {
									//  && item.item_type == '0'
									const bookList = books.filter(book => book.id == item.item_id);
									if (bookList.length > 0) {
										const book = Object.assign({}, bookList[0]);
										book.haveProblems = book.problems && book.problems.length > 0;
										if (notEmpty(book.enforce_method)) {
											book.enforce_method = book.enforce_method.replace(/\n/g, '<br>');
										}
										this.handleBookItem(node, item, book);
										item.handBook = book;
										item.haveRequire = this.haveSettingExpect(item);
									}
								}
							}
						}
					}
				}
				else {
					Notify({ type: 'danger', message: '请到管理平台绑定流程后操作' });
				}
				this.nodes = nodes;
				this.updateCheckNum();
			}
			this.updateTaskStep(this.dailyId, 'EXECUTE');
			this.showOverLay = false;
			this.isLoading = false;
		},
		toggleItemShow(item) {
			item.show = item.show ? false : true;
		},
		addRecord(item) {
			const data = {
				fileList: [],
				check_desc: '',
				pictures: '',
				item_id: item.item_id
			};
			item.records.push(data);
		},
		showPictxt(item) {
			if (item.handBook.problems && item.handBook.problems.length > 0) {
				this.$router.push({
					name: 'dailyPicTxt',
					params: {
						list: item.handBook.problems
					}
				})
			}
		},
		previewImage(list, index) {
			ImagePreview({
				images: list,
				startPosition: index
			});
		},
        showHistory() {
            // this.$router.push(`/history/${itemId}/1`);
			if (this.haveHistory) {
				this.$router.push(`/history/${this.formData.enforce_obj_id}`);
			}
			else {
				Notify('暂无历史隐患');
			}
        },
        showSettingExpect(data) {
            if (this.haveSettingExpect(data)) {
                this.$router.push(`/checkStandardExplain/${data.item_id}`)
            }
            else {
                Notify('暂无设置要求');
            }
        },
		praiseItem(data) {
			if (data.actionData && notEmpty(data.actionData.comment_type)) {
				const isCai = data.actionData.comment_type == 'CRITICISM';
				if (isCai) {
					// this.commitItemAction('update', this.itemAction.zan, data);
					Notify({ type: 'warning', message: '请取消点踩后操作' });
				}
				else {
					// Notify({ type: 'success', message: '已点赞' });
					this.commitItemAction('remove', this.itemAction.none, data);
				}
			}
			else {
				this.commitItemAction('add', this.itemAction.zan, data);
			}
		},
		caiItem(data) {
			if (data.actionData && notEmpty(data.actionData.comment_type)) {
				const isZan = data.actionData.comment_type == 'APPROVE';
				if (isZan) {
					Notify({ type: 'warning', message: '请取消点赞后操作' });
				}
				// Notify({ type: 'success', message: '已点踩' });
				else {
					this.commitItemAction('remove', this.itemAction.none, data);
				}
			}
			else {
				this.handleActionItem = data;
				this.caiComment = data.actionData && data.actionData.comment_content || '';
				this.showCaiComment = true;
			}
		},
		beforeCloseCaiDialog(action, done) {
			if (action == 'confirm') {
				if (isEmpty(this.caiComment)) {
					Notify({ type: 'danger', message: '请输入反馈意见' });
				}
				done(false);
			}
			done();
		},
		confirmCaiItem() {
			if (notEmpty(this.caiComment) && this.handleActionItem) {
				const type = this.handleActionItem.actionData && this.handleActionItem.actionData.comment_type == 'CRITICISM' ? 'update' : 'add';
				this.commitItemAction(type, this.itemAction.cai, this.handleActionItem, this.caiComment);
			}
		},
		commitItemAction(action, type, data, content) {
			if (action == 'remove') {
				// const vm = this;
				this.showOverLay = true;
				deleteRequest(`/v2/api/enforce_comment/${data.actionData.id}`).then(res => {
					data.customAction = type;
					data.actionData.comment_type = '';
					this.showOverLay = false;
					// const msg = type == 1 ? '点赞' : '点踩';
					// Notify({ type: 'success', message: `取消${msg}成功` });
				});
				return;
			}
			const params = {
				item_id: data.id
			}
			this.showOverLay = true;
			// comment_type 评论类型 APPROVE-点赞,CRITICISM-点踩
			params.comment_type = type == 1 ? 'APPROVE' : 'CRITICISM';
			if (content) {
				params.comment_content = content;
			}
			if (action == 'add') {
				post('/v2/api/enforce_comment', params).then(res => {
					data.customAction = type;
					data.actionData = res;
					this.showOverLay = false;
					this.showCaiComment = false;
				})
			}
			else {
				put(`/v2/api/enforce_comment/${data.actionData.id}`, params).then(res => {
					data.customAction = type;
					data.actionData.comment_content = content;
					data.actionData.comment_type = params.comment_type;
					this.showOverLay = false;
					this.showCaiComment = false;
				})
			}
		},
		handleImgUrl(imageId) {
			return handleProblemImgs(imageId);
		},
        handleBookItem(node, result, data) {
            if (result) {
                data.check_result = result.check_result;
            }
			if (data.problems) {
				data.problems.map(item => {
					let arr = [];
					if (item.problem_images) {
						if (Array.isArray(item.problem_images)) {
							arr = item.problem_images;
						}
						else {
							item.problem_images.split(',').map(imageId => {
								arr.push(this.handleImgUrl(imageId.trim()));
							});
						}
					}
					item.problem_images = arr;
				})
			}
            if (data.result_options) {
                const options = []
                data.result_options = data.result_options.replace(/，/g, ',');
                data.result_options.split(',').map(item => {
                    let str = item.trim().replace('/', '');
					str = str.replace('#', ',');
					options.push(str);
                })
                data.result_options = options;
            }
            if (data.other_enforce_item) {
                const list = [];
				let placeholder = '';
				// if (result.enforce_job_node_item == null && data.other_enforce_item.indexOf('部位') >= 0) {
				// 	placeholder = node.node_name;
				// }
				let resultOthers = null;
				if (result.enforce_job_node_item) {
					const resultOthersStr = result.enforce_job_node_item.replace(/，/g, ',');
					resultOthers = resultOthersStr.split(',');
				}
                const others = data.other_enforce_item.replace(/，/g, ',');
                others.split(',').map((other, index) => {
                    const item = other.replace('/', '');
                    if (item && item.length > 0) {
                        const obj = {
                            k: item,
                            v: placeholder
                        };
                        if (resultOthers && resultOthers.length > index) {
                            obj.v = resultOthers[index];
                        }
                        list.push(obj);
                    }
                })
                data.other_enforce_item = list
            }
        },
		getTemplateDefaultOption(item) {
			if (templateData && templateData.length > 0) {
				let res = templateData.filter(obj => obj.enforce_class == item.enforce_obj_class);
				if (res.length > 0) {
					res = res[0].items.filter(obj => obj.item_content == item.item_content);
					if (res.length > 0) {
						const target = res[0];
						return target[item.check_result];
					}
				}
			}
			return '';
		},
		updateCheckOption(item) {
			this.updateCheckNum();
			if (!item.show && item.check_result != '0') {
				this.toggleItemShow(item);
			}
			if (item.show && item.check_result == '0') {
				this.toggleItemShow(item);
			}
			// notEmpty(item.check_result) && 
			if (item.item_type == "0") {
				if (item.enforce_obj_class && item.item_content) {
					if (item.check_result == 0) {
						item.check_options = '';
					}
					else {
						//  if (isEmpty(item.check_options)) 
						item.check_options = this.getTemplateDefaultOption(item);
					}
				}
				if (item.handBook && item.handBook.other_enforce_item && item.handBook.other_enforce_item.length > 0) {
					const name = this.nodes[this.active].node_name;
					const isZero = item.check_result == '0';
					item.handBook.other_enforce_item.map(other => {
						if (isZero) {
							other.v = '';
						}
						else if (isEmpty(other.v)) {
							other.v = name;
						}
					})
				}
			}
		},
		updateCheckNum() {
			let check = 0, uncheck = 0, total = 0;
			let pass = 0, refuse = 0, uninvolved = 0;
			for (let i = 0; i < this.nodes.length; i++) {
				const node = this.nodes[i];
				let nodeUncheck = 0;
				if (node.items && node.items.length > 0) {
					total += node.items.length;
					for (let j = 0; j < node.items.length; j++) {
						const item = node.items[j];
						if (isEmpty(item.check_result)) {
							nodeUncheck++;
							uncheck++;
							uninvolved++;
						}
						else {
							check++;
							// 0-不涉及,1-合格,2-不合格
							if (item.check_result == 0) {
								uninvolved++;
							}
							if (item.check_result == 1) {
								pass++;
							}
							if (item.check_result == 2) {
								refuse++;
							}
						}
					}
				}
				node.badge = nodeUncheck > 0 ? nodeUncheck + '' : '';
				node.className = nodeUncheck > 0 ? 'FontColorError' : 'FontColorSuccess';
			}
			if (uncheck == total) {
				this.nodes.map(node => {
					node.badge = '';
					node.className = '';
				});
			}
			this.uncheckNum = uncheck;
			this.completeNum = check;
			this.totalNum = total;
			this.taskCount.total = total;
			this.taskCount.uncheck = uncheck;
			this.taskCount.pass = pass;
			this.taskCount.refuse = refuse;
			this.taskCount.uninvolved = uninvolved;
		},
		deleteRecordFile() {
			const obj = this.nodes[this.active];
			this.$set(this.nodes, this.active, obj);
		},
		beforeAvatarUpload(file) {
			console.log('beforeAvatarUpload file: ', file);
			const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
			if (!isJpgOrPng) {
				this.$toast.fail("图片只能是 JPG 或 PNG 格式!");
				return false;
			}
			this.showOverLay = true;
			this.tipMsg = '图片处理中';
			return new Promise((resolve) => {
				compressAccurately(file, {
					size: 100, //图片大小压缩到100kb
					// width: 1280, //宽度压缩到1280
				})
				.then((res) => {
						this.showOverLay = false;
						// this.tipMsg = '上传成功';
					resolve(res);
				});
			});
		},
		afterRead(file) {
			if (file && file.file && file.file.size > 2000000) {
				// 创建Canvas对象(画布)
				let canvas = document.createElement('canvas');
				// 获取对应的CanvasRenderingContext2D对象(画笔)
				let context = canvas.getContext('2d');
				// 创建新的图片对象
				let img = new Image();
				// 指定图片的DataURL(图片的base64编码数据)
				img.src = file.content;

				img.onload = () => {
					// 监听浏览器加载图片完成，然后进行进行绘制

					// 指定canvas画布大小，该大小为最后生成图片的大小
					canvas.width = img.width;
					canvas.height = img.height;
					/* drawImage画布绘制的方法。(0,0)表示以Canvas画布左上角为起点，400，300是将图片按给定的像素进行缩小。
					        如果不指定缩小的像素图片将以图片原始大小进行绘制，图片像素如果大于画布将会从左上角开始按画布大小部分绘制图片，最后的图片就是张局部图。*/
					context.drawImage(img, 0, 0, img.width, img.height);
					// 将绘制完成的图片重新转化为base64编码，file.file.type为图片类型，0.92为默认压缩质量
					let base_img = canvas.toDataURL(file.file.type, 0.75);
					const blodBin = atob(base_img.split(',')[1]);
					let data = [];
					for (let i = 0; i < blodBin.length; i++) {
						data.push(blodBin.charCodeAt(i));
					}
					let blob1 = new Blob([new Uint8Array(data)], { type: 'image/png' });
					let file1 = new File([blob1], new Date().getTime() + '.png');

					console.warn(file1);

					file.file = file1;
				};
			}
			const obj = this.nodes[this.active];
			this.$set(this.nodes, this.active, obj);
		},
        uploadFile(data, saveCache) {
			this.tipMsg = '上传图片中...';
			let name = data.file.name;
			if (!name || name.length == 0) {
				name = Date.now() + '.jpeg';
			}
            const form = new FormData();
            form.append('fileName', name);
            form.append('fileBinary', data.file);
            this.$http.post('/v2/api/file', form).then(res => {
                if (res && res.data && res.data.id) {
                    data.fileID = res.data.id;
                    this.checkFile(saveCache);
                }
            })
        },
		checkFile(saveCache) {
            const have = this.checkNodesFile(saveCache);
            if (!have && !saveCache) {
                this.handleConfirmTaskInfo();
            }
			if (saveCache) {
				this.commitCacheItems();
			}
        },
        checkNodesFile(saveCache) {
            let have = false;
            if (this.nodes && this.nodes.length > 0) {
                for (let index = 0; index < this.nodes.length; index++) {
                    const node = this.nodes[index];
                    if (node.items && node.items.length > 0) {
                        for (let j = 0; j < node.items.length; j++) {
                            const item = node.items[j];
							if (item.records && item.records.length > 0) {
								for (let z = 0; z < item.records.length; z++) {
									const record = item.records[z];
									if (record.fileList && record.fileList.length > 0) {
										for (let m = 0; m < record.fileList.length; m++) {
											const file = record.fileList[m];
											if (!file.fileID && !file.url) {
												have = true;
												this.uploadFile(file, saveCache);
												break;
											}
										}
									}
									if (have) {
										break;
									}
								}
							}
							if (have) {
								break;
							}
                        }
                    }
                    if (have) {
                        break;
                    }
                }
            }
            return have;
        },
		changeCheckResult() {
			this.updateCheckNum();
		},
        handleConfirmTaskInfo(flag) {
			this.showTaskCount = false;
			this.showOverLay = true;
			if (this.checkNodesFile() === false) {
				let items = [];
				this.nodes.map(node => {
					if (node.items && node.items.length > 0) {
						items = items.concat(node.items);
					}
				});
				this.tipMsg = '保存数据中...';
				let params = [];
				let item;
				items.map(temp => {
					item = JSON.parse(JSON.stringify(temp));
					if (isEmpty(item.check_result)) {
						item.check_result = 0;
					}
					else {
						item.check_result = parseInt(item.check_result);
					}
					if (item.records && item.records.length > 0) {
						item.records.map(record => {
							let pictures = [];
							record.fileList.map(file => {
								pictures.push(file.fileID);
							});
							record.pictures = pictures.join(',');
						});
					}
					if (item.handBook && item.handBook.other_enforce_item && item.handBook.other_enforce_item.length > 0) {
						let others = [];
						item.handBook.other_enforce_item.map(other => {
							const otherV = other.v ? other.v : '';
							others.push(otherV);
						});
						item.enforce_job_node_item = others.join(',');
					}
					params.push(item);
				});
				this.$http.put(`/v2/api/enforce-job/item`, params).then(res => {
					this.showOverLay = false;
					if (flag == true) {
						this.$toast.success({ type: 'success', message: '暂存成功' });
						this.$router.back();
					}
					else {
						this.$toast.success({ type: 'success', message: '提交成功' });
						this.turnToRecord()
					}
				})
			}
		},
		turnToRecord() {
			// if (this.formData.job_type == 'SPECIAL') {
			// 	this.$router.replace(`/special/record/${this.dailyId}`);
			// }
			// else {
				this.$router.replace(`/checkRecord/${this.dailyId}`);
			// }
		},
		checkItemHaveResult() {
			const nodes = this.formData.check_nodes || [];
			nodes.map(node => {
				if (node.items && node.items.length > 0) {
					node.items.map(item => {
						item.haveResult = isEmpty(item.check_result);
					});
				}
			});
			
			this.blurOtherInput();
		},
		submitCheck() {
			this.checkItemHaveResult();
			// return
			const nodes = this.formData.check_nodes || [];
			if (nodes.length <= 0) {
				Notify({ type: 'danger', message: '请到管理平台绑定流程后操作' });
				return;
			}
			this.updateCheckNum();
			if (this.formData.start_time) {
				let dis = new Date() - new Date(this.formData.start_time);
				// console.log('dis: ', dis)
				let str = '';
				const hour = Math.floor(dis / (1000 * 3600));
				if (hour < 10) {
					str = `0${hour}:`;
				}
				else {
					str = `${hour}:`
				}
				dis = dis % (1000 * 3600);
				const minute = Math.floor(dis / (1000 * 60));
				if (minute < 10) {
					str += `0${minute}:`
				}
				else {
					str += `${minute}:`
				}
				dis = dis % (1000 * 60);
				dis = Math.ceil(dis / 1000);
				if (dis < 10) {
					str += `0${dis}`
				}
				else {
					str += `${dis}`
				}
				this.taskCount.time = str;
			}
			this.showTaskCount = true;
		},
    }
}
</script>

<style lang="scss">
.list {
    .van-tree-select {
        width: 100%;
    }
	.van-tree-select__content {
		background-color: #F5F5F5;
	}
	.van-cell__value {
		white-space: normal;
		flex: 2;
	}
	.van-radio--horizontal {
		margin-right: 2px;
	}
	.van-uploader {
		margin-left: 12px;
	}
	.van-field__body {
		background-color: #F5F5F5;
	}
	.van-sidebar-item--select::before {
		top: 0;
		height: 100%;
		transform: none;
		background-color: #02A7F0;
	}
	.unLine {
		border-bottom: none !important;
	}
	.unLine::after {
		border-bottom: none !important;
	}

	.list-item {
		.van-radio--horizontal {
			margin-top: 5px;
		}
	}
	.van-info {
		min-width: 24px;
	}
	.van-sidebar-item__text {
		min-width: 20px;
	}
}
.records {
	.noline::after {
		border-bottom: none !important; 
	}
}
.titleLine {
	.van-cell__title {
		flex: 2;
	}
}
.haveContent {
	.van-cell__value {
		color: #02A7F0;
	}
}
.bolder {
	.van-cell__title {
		font-weight: bolder;
		font-size: 16px;
	}
}
</style>

<style lang="scss" scoped>
@import '@/style/variable.scss';
.errorItem {
	color: $colorRed !important;
}
.numInfo {
    color: #7f7f7f;
    font-size: 12px;
    display: flex;
    justify-content: space-between;
	align-items: center;
    padding: 10px;
	.left {
		display: flex;
		align-items: center;
	}
}
.numInfo1 {
	margin-top: 47px;
}

.item-title {
	font-size: 18px;
	color: #323234;
	font-weight: bolder;
}

.action {
	margin-top: -10px;
	padding: 4px 10px;
	position: relative;
	display: flex;
	align-items: center;
	&-item {
		padding: 3px 5px;
		color: $colorBlueHove;
		border-radius: 4px;
		border: 1px solid $colorBlueHove;
	}
	&-item:last-child {
		margin-left: 10px;
	}
	&-item-active {
		color: $colorRed;
		border-radius: 4px;
		border: 1px solid $colorRed;
	}
}
.action::after {
	position: absolute;
	content: ' ';
	bottom: -10px;
	left: 14px;
	right: 14px;
	height: 1px;
	background-color: #ebedf0;
	transform: scaleY(0.5);
}

.search {
    margin-top: 57px;
}

.list {
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    height: calc(100vh - 194px);
    width: 100;
	.list-item {
		background-color: #FFFFFF;
	}
	.list-item:not(:first-child) {
		margin-top: 20px;
	}
	.item-row {
		position: relative;
		display: flex;
		flex-direction: column;
		background-color: #FFFFFF;
		padding: 4px 16px;
		&-images {
			width: max-content;
			overflow-x: auto;
		}
		&-desc {
			font-size: 14px;
			color: #666666;
		}
	}
	.item-row::after {
		position: absolute;
		box-sizing: border-box;
		content: ' ';
		pointer-events: none;
		right: 16px;
		bottom: 0;
		left: 16px;
		border-bottom: 1px solid #ebedf0;
	}
	.records {
		background-color: #FFFFFF;
		.record {
			border-top: 1px solid #F5F5F5;
			.files {
				display: flex;
				align-items: center;
				padding: 0 14px;
				flex-wrap: wrap;
				.fileImg {
					position: relative;
					width: 80px;
					height: 80px;
					.close {
						position: absolute;
						right: 0;
						top: 0;
						width: 20px;
						height: 20px;
					}
				}
			}
		}
		.add {
			display: flex;
			justify-content: flex-end;
			margin-right: 14px;
			padding-bottom: 14px;
		}
	}
}
.submit {
	display: flex;
	align-items: center;
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	height: 44px;
}
.wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
	width: 100%;
}
.box {
	margin: 10px 20px;
	border: 1px solid #ebedf0;
	border-radius: 6px;
}
</style>