<template>
    <div class="page">
        <headNav @rightClick="rightClick" iconName="plus" title="执行任务"></headNav>

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

		<div class="numInfo">
			<div class="left">
				共需检查：<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 :title="item.handBook.enforce_content" is-link :arrow-direction="item.show?'down':'left'" @click="toggleItemShow(item)"/>
                            <van-cell 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 center title="常见问题" :value="item.handBook.problems && item.handBook.problems.length > 0?'[查看]':'暂无'" @click="showPictxt(item)"></van-cell>
							<template v-if="item.handBook.problems">
								<div v-for="problem in item.handBook.problems" :key="problem.id" class="item-row">
									<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>
							<van-cell title="检查结果">
								<!-- 0-不涉及,1-合格,2-不合格 -->
								<van-radio-group v-model="item.check_result" direction="horizontal">
									<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.enforce_class" />
								<van-cell v-show="item.show" title="历史隐患" value="[查看]" @click="showHistory(item.id)" />
								<van-cell v-show="item.show" title="设置要求" :value="item.handBook.setting_expect ? '[查看]':'暂无'" @click="showSettingExpect(item)" />
								<van-cell v-show="item.show" 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>
								<!-- <van-field v-show="item.show" v-model="item.item_content" label="附属检查" placeholder="请输入" /> -->
								<template v-if="item.show && item.other_enforce_item && item.other_enforce_item.length > 0">
									<van-field v-for="(other, otherIndex) in item.other_enforce_item" :key="otherIndex" v-model="other.v" :label="other.k" placeholder="请输入" />
								</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="2" autosize type="textarea" placeholder="请输入"/>
										<van-cell title="现场图片" />
										<van-uploader
											v-model="record.fileList"
											:max-count="4"
											:after-read="afterRead"
											multiple
											capture="camera"
										/>
									</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>

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

        <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>
    </div>
</template>

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

import { ImagePreview, Notify } from 'vant';

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

export default {
    components: {
        headNav,
        'v-mask': mask_overLay,
        executeTaskTips,
    },
    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,
        }
    },
	computed: {
		dailyId() {
			return this.$route.params.ID
		},
		enforceId() {
			return this.$route.params.objId
		}
	},
    mounted () {
        if (this.dailyId) {
            this.loadTaskDatas();
        }
    },
    methods: {
        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.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 + '';
								item.handBook = {
									request: true,
								};
								if (!item.records || item.records.length === 0) {
									item.records = [{
										fileList: [],
										check_desc: '',
										pictures: '',
										item_id: item.item_id
									}];
								}
								nodeItems.push(item);
							})
						}
						node.items = nodeItems;
					});
					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];
								const bookRes = await this.$http.get(`/v2/api/enforce-handbook/${item.item_id}`);
								if (bookRes.data) {
									const book = bookRes.data;
									this.handleBookItem(item, book);
									item.handBook.request = false;
									item.handBook = Object.assign(item.handBook, book);
								}
							}
						}
					}
				}
				this.nodes = nodes;
				this.upateCheckNum();
				this.showOverLay = 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
					}
				})
			}
		},
		previewImage(list, index) {
			ImagePreview({
				images: list,
				startPosition: index
			});
		},
        showHistory(itemId) {
            this.$router.push(`/history/${this.enforceId}`);
        },
        showSettingExpect(data) {
            if (data && data.item_id) {
                this.$router.push(`/checkStandardExplain/${data.item_id}`)
            }
            else {
                Notify('暂无设置要求');
            }
        },
        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(handleProblemImgs(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 = [];
                const others = data.other_enforce_item.replace('，', ',');
                const otherItems = others.split(',');
                otherItems.map((other, index) => {
                    const item = other.replace('/', '');
                    if (item && item.length > 0) {
                        const obj = {
                            k: item,
                            v: ''
                        };
                        if (result && result.enforce_job_node_item && result.enforce_job_node_item.length > index) {
                            obj.v = result.enforce_job_node_item[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;
		},
		addCheck(data) {
			const len = data.recordsList.length - 1;
			const obj = {
				check_desc: '',
				pictures: '',
				item_id: data.item_id
			};
			data.recordsList.splice(len, 0, obj);
			// data.recordsList.push(obj);
		},
		afterRead(file) {
			if (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;
				};
			}
		},
        uploadFile(data) {
			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();
                }
            })
        },
		checkFile() {
            const have = this.checkNodesFile();
            if (!have) {
                this.commitNode();
            }
        },
        checkNodesFile() {
            let have = false;
            if (this.mainList && this.mainList.length > 0) {
                for (let index = 0; index < this.mainList.length; index++) {
                    const node = this.mainList[index];
                    if (node.items && node.items.length > 0) {
                        for (let j = 0; j < node.items.length; j++) {
                            const item = node.items[j].handBook;
							if (item.recordsList && item.recordsList.length > 0) {
								for (let z = 0; z < item.recordsList.length; z++) {
									const record = item.recordsList[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) {
												have = true;
												this.uploadFile(file);
												break;
											}
										}
									}
									if (have) {
										break;
									}
								}
							}
							if (have) {
								break;
							}
                        }
                    }
                    if (have) {
                        break;
                    }
                }
            }
            return have;
        },
		changeCheckResult() {
			this.upateCheckNum();
		},
        handleConfirmTaskInfo() {
			this.showTaskCount = false;
			this.showOverLay = true;
			let items = [];
			for (let i = 0; i < this.nodes.length; i++) {
				const node = this.nodes[i];
				if (node.items && node.items.length > 0) {
					items = items.concat(node.items);
				}
			}
			if (this.checkNodesFile() === false) {
				this.tipMsg = '保存数据中...';
				items.map(item => {
					if (isEmpty(item.check_result)) {
						item.check_result = 0;
					}
					else {
						item.check_result = parseInt(item.check_result);
					}
				});
				this.$http.put(`/v2/api/enforce-job/item`, items).then(res => {
					this.showOverLay = false;
					this.$toast.success({ type: 'success', message: '提交成功' })
					this.turnToRecord()
				})
			}
		},
		// 跳转消防监督检查记录
        turnToRecord() {
            this.$router.replace(`/checkRecord/${this.dailyId}`);
        },
        // 跳转复查监督检查记录
        turnToRecheckRecord() {
            this.$router.push(
                `/reviewRecord/${this.dailyId}/${this.dataList.taskId}`
            );
        },
        // 跳转检查结果
        turnToResult() {
            if (!this.hasJudge) {
                this.$router.push(`/checkResult/${this.dataList.taskId}/${this.dailyId}/normal`)
            } 
            else {
                this.$router.push(`/checkResultDetail/${this.dataList.taskId}/${this.dailyId}`)
            }
        },
		submitCheck() {
			this.upateCheckNum();
			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;
	}
}
</style>

<style lang="scss" scoped>
.numInfo {
    color: #7f7f7f;
    font-size: 12px;
    display: flex;
    justify-content: space-between;
    padding: 10px 15px;
}

.search {
    margin-top: 57px;
}

.list {
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    height: calc(100vh - 194px);
    width: 100;
	.list-item:not(:first-child) {
		margin-top: 20px;
	}
	.item-row {
		display: flex;
		flex-direction: column;
		&-images {
			width: max-content;
			overflow-x: auto;
		}
		&-desc {
			font-size: 14px;
			color: #666666;
		}
	}
	.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>