<template>
    <div class="page">
        <headNav :canBack="false" @leftAction="onLeftAction" title="任务执行"></headNav>
        <div class="content" v-if="info">
            <van-cell-group v-if="info.enforce_obj">
                <van-cell title="单位名称" :value="info.enforce_obj_name" />
                <van-cell title="单位地址" :value="info.enforce_obj.enforce_obj_address" />
                <van-cell title="单位法人" :value="info.enforce_obj.legal_person" />
                <van-cell title="联系方式" :value="info.enforce_obj.legal_person_phone" />
            </van-cell-group>
            <van-cell-group class="mt">
                <van-cell title="下发单位" :value="info.enforce_org_name" />
                <van-cell title="编号" :value="info.job_no" />
                <van-cell title="检查时间" :value="info.start_time" />
                <van-cell title="检查类型" value="乡镇检查" />
            </van-cell-group>
            <template v-if="checkList">
                <template v-for="(group, groupIndex) in checkList">
                    <van-cell-group :key="groupIndex" :title="group.name">
                        <template v-for="item in group.childs">
                            <van-cell :key="item.id" :title="item.handBook.enforce_content" class="my">
                                <div class="items">
                                    <template v-if="item.handBook.result_options">
                                        <van-radio-group direction="horizontal" v-model="item.check_options">
                                            <van-radio v-for="(option, optionIndex) in item.handBook.result_options" :key="optionIndex" :name="option">{{option}}</van-radio>
                                        </van-radio-group>
                                    </template>
                                    <template v-if="item.handBook.other_enforce_item">
                                        <van-field v-for="(option, optionIndex) in item.handBook.other_enforce_item" :key="optionIndex" :v-model="option.v" :label="option.k" placeholder="请输入" />
                                    </template>
                                    <template v-for="(file, fileIndex) in item.records">
                                        <van-uploader
                                            :key="fileIndex"
                                            v-model="file.fileList"
                                            :max-count="1"
                                            :before-read="beforeAvatarUpload"
                                            :after-read="afterRead"
                                            capture="camera"
                                        />
                                    </template>
                                </div>
                            </van-cell>
                        </template>
                    </van-cell-group>
                </template>
            </template>
            <van-cell-group v-if="otherRemark" :title="otherRemark.enforce_obj_class" class="remark">
                <div class="remark-title">其他说明</div>
                <van-field
                    v-model="otherRemark.item_content"
                    rows="2"
                    autosize
                    type="textarea"
                    maxlength="300"
                    placeholder="请输入"
                    show-word-limit
                />
            </van-cell-group>
            <van-cell-group class="mt">
                <van-cell title="检查结论">
                    <van-radio-group direction="horizontal" v-model="info.enforce_result">
                        <van-radio name="PASS">合格</van-radio>
                        <van-radio name="NOT_PASS">不合格</van-radio>
                    </van-radio-group>
                </van-cell>
            </van-cell-group>

            <div class="mg">
                <van-button round block type="info" @click="commitTaskInfo">提交</van-button>
            </div>
        </div>

        <v-mask :showOverLay="showOverLay" :tipMsg="tipMsg"></v-mask>
    </div>
</template>

<script>
import headNav from "@/components/headNav.vue";
import baiduMap from "@/components/baiduMap.vue";
import mask_overLay from "@/components/overLay_xy.vue";
import { dateFormat, isEmpty, notEmpty } from '@/utils/tool';
import { handleProblemImgs } from '@/utils/index';
import { Dialog } from 'vant';
import { compressAccurately } from "image-conversion";
import executeStepMixin from '@/mixins/executeStep';

export default {
    components: {
        headNav,
        baiduMap,
        "v-mask": mask_overLay,
    },
    computed: {
        taskId() {
            return this.$route.params.ID
        },
        taskStart() {
            if (this.info) {
                const s = this.info.job_status;
                return s == 'TODO' || s == 'DOING' || s == 'REJECT';
            }
            return false
        }
    },
    mixins: [executeStepMixin],
    data() {
        return {
            info: null,
            showOverLay: false,
            tipMsg: '加载中...',
            checkList: [],
            otherRemark: null,
        }
    },
    mounted() {
        if (this.taskId) {
            this.loadTaskDatas();
        }
    },
    methods: {
        onLeftAction() {
			const vm = this;
			Dialog.confirm({
				title: '温馨提示',
				message: '是否放弃该任务？',
				confirmButtonText: '暂存',
				cancelButtonText: '放弃',
			}).then(() => {
				// on confirm
				vm.commitItemsInfo(true);
			}).catch(() => {
				// on cancel
				put(`/v2/api/enforce-job/${this.taskId}/exchange`).then(res => {
					vm.$router.back();
				});
			});
		},
		handleImgUrl(imageId) {
			return handleProblemImgs(imageId);
		},
        async loadTaskDatas() {
            this.showOverLay = true;
            const res = await this.$http.get(`/v2/api/enforce-job/${this.taskId}`);
            if (res.data) {
                const obj = Object.assign({}, res.data);
                if (obj.start_time) {
                    obj.start_time = dateFormat('YYYY-mm-dd', new Date(obj.start_time));
                }
                if (obj.check_nodes) {
                    const nodes = obj.check_nodes;
                    nodes.forEach((node, nodeIndex) => {
                        node.text = node.node_name;
                        let nodeItems = [];
                        if (node.items) {
                            node.items.forEach(itemRes => {
                                let item = Object.assign({}, 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
                                    }];
                                }
                                else {
                                    item.records.map(record => {
                                        let pics = [];
                                        if (record.pictures) {
                                            record.pictures.split(',').map(fileId => {
                                                const url = this.handleImgUrl(fileId);
                                                pics.push({
                                                    url,
                                                    isImage: true,
													fileID: fileId
                                                });
                                            });
                                        }
                                        record.fileList = pics;
                                    });
                                }
                                nodeItems.push(item);
                            })
                        }
                        node.items = nodeItems;
                    });
                    let arr = [];
                    const bookRes = await this.$http.get("/v2/api/enforce-handbook?page=1&size=100000&sort=sort asc&query=enforce_type==1");
                    const bookList = bookRes && bookRes.data && bookRes.data.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_type == '1') {
                                    this.otherRemark = item;
                                    node.items.splice(j, 1);
                                    j--;
                                    continue;
                                }
                                // const bookRes = await this.$http.get(`/v2/api/enforce-handbook/${item.item_id}`);
                                const bookFilter = bookList.filter(book => book.id == item.item_id);
                                if (bookFilter.length > 0) {
                                    const book = bookFilter[0];
                                    this.handleBookItem(item, book);
                                    item.handBook.request = false;
                                    item.handBook = Object.assign(item.handBook, book);
                                }
                            }
                            node.items = this.handleBookDatas(node.items);
                            arr = arr.concat(node.items);
                        }
                    }
                    this.checkList = arr;
                }
                this.info = obj;
            }
            this.updateTaskStep(this.taskId, 'EXECUTE');
            this.showOverLay = false;
        },
        handleBookDatas(data) {
            const cls = new Set();
            data.map((item) => {
                if (item.handBook) {
                    cls.add(item.handBook.enforce_class);
                }
            });
            const list = [...cls];
            const res = [];
            const vm = this;
            list.map((item) => {
                const childs = data.filter((obj) => item === obj.handBook.enforce_class);
                const obj = {
                    id: item,
                    name: item,
                    childs: childs,
                };
                res.push(obj);
            });
            return res;
        },
        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) {
                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
            }
        },
        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;
				};
			}
		},
        uploadFile(data, isSaveCache) {
            let name = data.file.name;
			if (!name || name.length == 0) {
				name = Date.now() + '.jpeg';
			}
			this.tipMsg = '上传图片中...';
            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(isSaveCache);
                }
            })
        },
		checkFile(isSaveCache) {
            const have = this.checkNodesFile(isSaveCache);
            if (!have) {
                this.commitItemsInfo(isSaveCache);
            }
        },
        checkNodesFile(isSaveCache) {
            let have = false;
            for (let index = 0; index < this.checkList.length; index++) {
                const node = this.checkList[index];
                for (let j = 0; j < node.childs.length; j++) {
                    const item = node.childs[j];
                    if (item.records && item.records.length > 0) {
                        const record = item.records[0];
                        if (record.fileList) {
                            for (let m = 0; m < record.fileList.length; m++) {
                                const file = record.fileList[m];
                                if (!file.fileID && !file.url) {
                                    have = true;
                                    this.uploadFile(file, isSaveCache);
                                    break;
                                }
                            }
                        }
                    }
                    if (have) {
                        break;
                    }
                }
                if (have) {
                    break;
                }
            }
            return have;
        },
        commitTaskInfo() {
            if (isEmpty(this.info.enforce_result)) {
                this.$toast.fail('请选择检查结论');
                return;
            }
            if (this.checkList.length > 0) {
                let flag = 0;
                this.checkList.forEach(row => {
                    row.childs.forEach(item => {
                        if (isEmpty(item.check_options)) {
                            flag++;
                        }
                    });
                });
                if (flag > 0) {
                    Dialog.confirm({
                        title: '提示',
                        message: `还有${flag}项没有处理，是否直接提交？`,
                    })
                    .then(() => {
                        // on confirm
                        this.commitItemsInfo();
                    })
                    .catch(() => {
                        // on cancel
                    });
                }
                else {
                    this.commitItemsInfo();
                }
            }
        },
        commitItemsInfo(isSaveCache) {
            this.showOverLay = true;
            if (!this.checkNodesFile(isSaveCache)) {
                let items = [];
                for (let i = 0; i < this.checkList.length; i++) {
                    const node = this.checkList[i];
                    if (node.childs && node.childs.length > 0) {
                        items = items.concat(node.childs);
                    }
                }
                items.map(item => {
                    if (item.records && item.records.length > 0) {
                        const record = item.records[0];
                        if (record.fileList && record.fileList.length > 0) {
                            let pictures = [];
                            record.fileList.map(file => {
                                pictures.push(file.fileID);
                            });
                            record.pictures = pictures.join(',');
                        }
                    }
                    let check = 0;
                    if (notEmpty(item.check_options) && item.check_options != '不涉及') {
                        check = 1;
                    }
                    const options = item.handBook && item.handBook.result_problem_options || [];
                    if (options && options.indexOf(item.check_options) >= 0) {
                        check = 2;
                    }
                    item.check_result = check;
                });
                if (this.otherRemark) {
                    items.push(this.otherRemark);
                }
                this.tipMsg = '保存数据中...';
                this.$http.put(`/v2/api/enforce-job/item`, items).then(res => {
                    this.$http.put(`/v2/api/enforce-job/${this.taskId}`, {
                        enforce_result: this.info.enforce_result
                    }).then(result => {
                        this.showOverLay = false;
                        if (isSaveCache == true) {
                            this.$toast.success({ type: 'success', message: '暂存成功' });
                            this.$router.back();
                        }
                        else {
                            this.$toast.success({ type: 'success', message: '提交成功' });
                            this.$router.replace(`/town/record/${this.taskId}`);
                        }
                    })
                })
            }
        },
    }
}
</script>

<style lang="scss">
.my {
    .van-cell__title {
        width: 150px;
        max-width: 150px;
    }
    .van-cell__value {
        white-space: normal;
    }
}
.remark {
    .van-cell {
        padding: 0;
    }
}
</style>

<style lang="scss" scoped>
.mt {
    margin-top: 16px;
}
.items {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
}
.remark {
    padding: 10px 16px;
}
.remark-title {
    font-size: 14px;
    color: #353535;
}
</style>
