<template>
    <div class="page">
        <headNav title="执行任务"></headNav>

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

		<div class="numInfo search">
			<div class="left">
				<!-- <van-button plain hairline icon="clock-o" size="mini" type="info">{{totalTime}}</van-button> -->
				共需检查：<span>{{ totaNum }}</span>项
			</div>
			<div class="right df">
				<div class="FontColorOther pr15">
					已完成：<span>{{ complateNum }}</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">
                <template #content>
                    <template v-if="nodes[active] && nodes[active].items">
                        <div class="list-item" v-for="item in nodes[active].items" :key="item.id">
                            <van-cell class="item-title" :title="(item.handBook && item.handBook.enforce_content) || item.item_content || item.item_name" is-link :arrow-direction="item.show?'down':'left'" @click="toggleItemShow(item)"/>
                            <template v-if="item.handBook">
								<van-cell class="unline titleLine bolder" center title="检查流程及方法" :value="item.handBook.enforce_method?'':'暂无'"></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" disabled>
									<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-show="item.show"> -->
								<van-cell v-show="item.show" 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.show && item.handBook.result_options && item.handBook.result_options.length > 0" title="检查选项">
										<van-radio-group v-model="item.check_options" direction="horizontal" disabled>
											<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.show && 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" readonly :label="other.k" placeholder="请输入" />
									</template>
								</template>
								<div v-show="item.show" class="records">
									<div class="record" v-for="(record, recordIndex) in item.records" :key="recordIndex">
										<van-cell title="检查情况" />
										<van-field v-model="record.check_desc" rows="1" label="" autosize type="textarea" readonly />
										<van-cell title="现场图片" />
										<template v-if="record.fileList && record.fileList.length > 0">
											<van-uploader
												v-model="record.fileList"
												:max-count="record.fileList.length"
                                                :deletable="false"
											/>
										</template>
									</div>
								</div>
							<!-- </template> -->
                        </div>
                    </template>
                </template>
            </van-tree-select>
        </div>

        <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 } from 'vant';

import { isEmpty, formatDistanceDate, notEmpty } from '@/utils/tool';
import { handleProblemImgs } from '@/utils/index';

export default {
    components: {
        headNav,
        'v-mask': mask_overLay,
        executeTaskTips,
		Problem,
    },
    data () {
        return {
            showOverLay: false,
            totaNum: 0,
            complateNum: 0,
            uncheckNum: 0,
            showTaskCount: false,
            taskCount: {
				time: ' ',
				total: 0,
				uncheck:0,
				pass: 0,
				refuse: 0,
				uninvolved: 0,
			},
            nodes: [],
			nodesItem: [],
            active: 0,
            formData: null,
			// totalTime: '05:00',
			haveHistory: true,
        }
    },
	computed: {
		dailyId() {
			return this.$route.params.ID
		},
		enforceId() {
			return this.$route.params.objId
		}
	},
    mounted () {
        if (this.dailyId) {
            this.loadTaskDatas();
        }
    },
    methods: {
		haveSettingExpect(item) {
			return item && item.handBook && item.handBook.setting_expect && notEmpty(item.handBook.setting_expect);
		},
        showSearchItems() {
			this.$router.push(`/dailyItemSearch/${this.dailyId}/${this.enforceId}`);
		},
        rightClick() {
			this.$router.push(`/special/exec/add/${this.dailyId}/${this.enforceId}`);
		},
        async loadTaskDatas() {
			this.showOverLay = true
			const res = await this.$http.get(`/v2/api/enforce-job/${this.dailyId}`);
			if (res && res.data && res.data.check_nodes) {

				this.$http.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;
					}
				})

				// if (res.data.start_time) {
				// 	const startDate = new Date(res.data.start_time);
				// 	let endDate = new Date();
				// 	if (res.data.finish_time) {
				// 		endDate = new Date(res.data.finish_time);
				// 	}
				// 	this.totalTime = formatDistanceDate(startDate, endDate);
				// }
				this.formData = res.data;
				const nodes = this.formData.check_nodes || [];
				this.totaNum = nodes.length;
				if (nodes.length > 0) {
					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.map(record => {
                                        let pics = [];
                                        if (record.pictures) {
                                            record.pictures.split(',').map(fileId => {
                                                const url = this.handleImgUrl(fileId);
                                                pics.push({
                                                    url,
													isImage: true
                                                });
                                            });
                                        }
                                        record.fileList = pics;
                                    });
                                }
								nodeItems.push(item);
							})
						}
						node.items = nodeItems;
					});
					// const bookRes = await this.$http.get(`/v2/api/enforce-handbook?page=1&size=100000&sort=sort asc&query=enforce_type==0`);
					const bookRes = await this.$http.get(`/v2/api/enforce_template_handbook/copy/job/${this.dailyId}`);
					const books = bookRes.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];
								if (item.item_id) {
									const bookList = books.filter(book => book.id == item.item_id);
									// const bookRes = await this.$http.get(`/v2/api/enforce-handbook/${item.item_id}`);
									if (bookList.length > 0) {
										const book = 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(item, book);
										item.handBook = book;
										item.haveRequire = this.haveSettingExpect(item);
									}
								}
							}
						}
					}
				}
				// else {
				// 	Notify({ type: 'danger', message: '请点击右上角“+”添加检查项后操作' });
				// }
				this.nodes = nodes;
				this.upateCheckNum();
				this.showOverLay = false;
			}
		},
		toggleItemShow(item) {
			item.show = item.show ? false : true;
		},
		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('暂无设置要求');
            }
        },
		handleImgUrl(imageId) {
			return handleProblemImgs(imageId);
		},
        handleBookItem(result, data) {
            if (result) {
                data.check_result = result.check_result;
            }
			if (data.problems) {
				data.problems.map(item => {
					let arr = [];
					if (item.problem_images) {
						item.problem_images.split(',').map(imageId => {
							arr.push(this.handleImgUrl(imageId.trim()));
						});
					}
					item.problem_images = arr;
				})
			}
            if (data.result_options && data.result_options.length > 0 && !Array.isArray(data.result_options)) {
				// console.log(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 = [];
				const resultOthersStr = result.enforce_job_node_item && result.enforce_job_node_item.replace(/，/g, ',') || '';
				const 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: ''
                        };
                        if (resultOthers && resultOthers.length > index) {
                            obj.v = resultOthers[index];
                        }
                        list.push(obj);
                    }
                })
                data.other_enforce_item = list
            }
        },
        changecheck_result() {
			this.upateCheckNum();
		},
		upateCheckNum() {
			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';
			}
			this.uncheckNum = uncheck;
			this.complateNum = check;
			this.totaNum = total;
			this.taskCount.total = total;
			this.taskCount.uncheck = uncheck;
			this.taskCount.pass = pass;
			this.taskCount.refuse = refuse;
			this.taskCount.uninvolved = uninvolved;
		},
    }
}
</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;
		}
	}
}
.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>
.numInfo {
    color: #7f7f7f;
    font-size: 12px;
    display: flex;
    justify-content: space-between;
    padding: 10px 15px;
}

.search {
    margin-top: 50px;
	display: flex;
	align-items: center;
	.left {
		display: flex;
		align-items: center;
	}
}

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

.list {
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    height: calc(100vh - 95px);
    width: 100;
	.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;
		.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%;
}
</style>