<template>
    <div class="page">
        <headNav :title="notEdit?'编辑检查项':'新增检查项'"></headNav>
        <van-cell-group>
            <template v-if="notEdit">
                <van-cell title="新增类型" :value="typeDesc" />
            </template>
            <template v-else>
                <van-cell title="新增类型" is-link :value="typeDesc" @click="showPicker = true" />
            </template>
            <van-field v-if="typeIndex===1" v-model="formData.item_content" label="检查内容" placeholder="请输入" />
            <template v-if="typeIndex===0">
                <template v-if="notEdit">
                    <van-cell title="检查类别" :value="checkDesc && checkDesc.enforce_class" />
                    <van-cell title="检查项" :value="itemDesc && itemDesc.enforce_content" />
                </template>
                <template v-else>
                    <van-cell title="检查类别" is-link :value="checkDesc && checkDesc.enforce_class" @click="showCheckData = true" />
                    <van-cell title="检查项" is-link :value="itemDesc && itemDesc.enforce_content" @click="showCheckItem = true" />
                </template>
            </template>
            <template v-if="bookInfo && typeIndex==0">
                <template v-if="bookInfo.enforce_method">
                    <van-cell title="检查流程及方法" :label="bookInfo.enforce_method" />
                </template>
                <template v-else>
                    <van-cell title="检查流程及方法" value="暂无" />
                </template>
                <template v-if="bookInfo.problems && bookInfo.problems.length > 0">
                    <van-cell title="常见问题" is-link value="[查看]" @click="showProblems"></van-cell>
                    <div class="problems">
                        <div class="problem" v-for="item in bookInfo.problems" :key="item.id">
                            <div v-if="item.problemImages" class="problem-pics">
                                <van-image v-for="(url, index) in item.problemImages" :key="index" width="100" height="100" :src="url" @click="previewImage(item.problemImages, index)"/>
                            </div>
                            <div class="desc">{{item.problem_desc}}</div>
                        </div>
                    </div>
                </template>
                <template v-else>
                    <van-cell title="常见问题" value="暂无"></van-cell>
                </template>
            </template>
        </van-cell-group>
        <van-cell-group>
            <van-cell title="检查结果" class="custom-cell-value">
                <van-radio-group v-model="formData.check_result" direction="horizontal">
                    <van-radio name="0">不涉及</van-radio>
                    <van-radio name="1">合格</van-radio>
                    <van-radio name="2">不合格</van-radio>
                </van-radio-group>
            </van-cell>
            <template v-if="bookInfo && typeIndex===0">
                <van-cell title="检查类型" :value="bookInfo && bookInfo.enforce_class" />
                <van-cell title="历史隐患" is-link value="查看" @click="showHistory" />
                <van-cell title="设置要求" is-link value="查看" @click="showSettingExpect" />
                <!-- <van-field v-model="formData.item_content" label="附属检查" placeholder="请输入" /> -->
                <template v-if="bookInfo.resultOptions">
                    <van-cell title="检查选项" class="custom-cell-value">
                        <van-radio-group v-model="formData.check_options" direction="horizontal">
                            <van-radio v-for="(item, ind) in bookInfo.resultOptions" :key="ind" :name="item">{{item}}</van-radio>
                        </van-radio-group>
                    </van-cell>
                </template>
                <template v-if="bookInfo.other_enforce_item">
                    <van-field v-for="(item, ind) in bookInfo.otherItems" :key="ind" v-model="item.v" :label="item.k" placeholder="请输入" />
                </template>
            </template>
        </van-cell-group>

        <div class="check" v-for="(item, ind) in checkNodes" :key="ind">
            <van-cell-group>
                <van-field
                v-model="item.content"
                rows="1"
                autosize
                label="检查情况"
                type="textarea"
                placeholder="请输入"
                />
                <van-uploader
                    v-model="item.fileList"
                    :max-count="4"
                    :before-read="beforeAvatarUpload"
                    :after-read="afterRead"
                    multiple
                    capture="camera"
                />
            </van-cell-group>
        </div>

        <div class="add">
            <van-button type="info" size="mini" @click="addCheckNode">添加检查情况</van-button>
        </div>

        <div class="submit">
            <van-button class="btn" type="info" size="mini" @click="commitNode">确定</van-button>
        </div>

        <van-popup v-model="showPicker" round position="bottom">
            <van-picker
                show-toolbar
                title="选择类型"
                :columns="columns"
                @cancel="showPicker = false"
                @confirm="onTypeConfirm"
            />
        </van-popup>

        <van-popup v-model="showCheckData" round position="bottom">
            <van-picker
                show-toolbar
                title="选择检查类别"
                value-key="enforce_class"
                :columns="checkDatas"
                @cancel="showCheckData = false"
                @confirm="onCheckDataConfirm"
            />
        </van-popup>

        <van-popup v-model="showCheckItem" round position="bottom">
            <van-picker
                show-toolbar
                title="选择检查项"
                value-key="enforce_content"
                :columns="checkItems"
                @cancel="showCheckItem = false"
                @confirm="onCheckItemConfirm"
            />
        </van-popup>

        <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 { ImagePreview, Notify } from 'vant'
import { notEmpty, isEmpty } from '@/utils/tool';
import { handleProblemImgs } from '@/utils/index';
import BUS from '@/bus';
import { compressAccurately } from "image-conversion";

export default {
    name: 'executeTaskAddComponent',
    inject: ["reload"],
    beforeRouteEnter(to, from, next) {
        if (from.name == 'dailyItemSearch' || from.name == 'specialExec') {
            next(vm => {
                vm.reload()
            });
        } else {
            next();
        }
    },
    components: {
        headNav,
        'v-mask': mask_overLay
    },
    data () {
        return {
            showPicker: false,
            columns: ['标准检查项', '自定义检查项'],
            typeDesc: '标准检查项',
            typeIndex: 0,
            checkDatas: [],
            checkIndex: 0,
            checkDesc: null,
            showCheckData: false,
            checkItems: [],
            showCheckItem: false,
            itemIndex: 0,
            itemDesc: null,
            showOverLay: false,
            bookInfo: null,
            formData: {
                check_options: '',
                check_result: '',
                item_content: ''
            },
            checkNodes: [{
                content: '',
                fileList: []
            }]
        }
    },
    computed: {
        dailyId() {
            return this.$route.params.ID
        },
		enforceId() {
			return this.$route.params.objId
		},
		data() {
			return this.$route.params.data
		},
        notEdit() {
            return this.data;
        }
    },
    mounted () {
        if (this.data) {
            this.handleBookItemData(this.data);
        }
        else {
            this.getBooks()
        }
    },
    methods: {
        backPage() {
            this.$router.back();
        },
        onTypeConfirm(value, index) {
            this.typeDesc = value
            this.typeIndex = index
            this.showPicker = false
        },
        onCheckDataConfirm(value, index) {
            this.checkIndex = index
            this.checkDesc = value
            this.showCheckData = false
            this.checkItems = this.checkDatas[index].childs || []
            this.itemIndex = -1
            this.itemDesc = ''
            this.bookInfo = null
        },
        addCheckNode() {
            this.checkNodes.push({
                content: '',
                fileList: []
            })
        },
		previewImage(list, index) {
			ImagePreview({
				images: list,
				startPosition: index
			});
		},
        checkItemIdData() {
            if (this.itemId && this.checkDatas) {
                let flag = false;
                for (let i = 0; i < this.checkDatas.length; i++) {
                    const cls = this.checkDatas[i];
                    if (cls.childs && cls.childs.length > 0) {
                        for (let j = 0; j < cls.childs.length; j++) {
                            const item = cls.childs[j];
                            if (this.itemId == item.id) {
                                flag = true;
                                this.checkIndex = i;
                                this.checkDesc = cls;
                                this.itemIndex = j;
                                this.itemDesc = item;
                                this.getBook(item.id);
                                break;
                            }
                        }
                    }
                    if (flag) {
                        break;
                    }
                }
            }
        },
        onCheckItemConfirm(value, index) {
            this.itemIndex = index
            this.itemDesc = value
            this.showCheckItem = false
            this.getBook(value.id)
        },
        handleBookDatas(data) {
            const cls = new Set()
            data.map(item => {
                cls.add(item.enforce_class)
            })
            const list = [...cls];
            const res = [];
            list.map(item => {
                const childs = data.filter(obj => item === obj.enforce_class);
                res.push({
                    id: item,
                    enforce_class: item,
                    childs: childs
                });
            })
            this.checkDatas = res;
            this.checkItemIdData();
            this.showOverLay = false;
        },
        getBooks() {
            this.showOverLay = true;
            this.$http.get('/v2/api/enforce-handbook?page=1&size=100000&sort=sort asc&query=enforce_type==0').then(res => {
                if (res && res.data) {
                    this.handleBookDatas(res.data.data || [])
                }
                else {
                    this.showOverLay = false;
                }
            })
        },
        getBook(itemId) {
            this.showOverLay = true
            const vm = this;
			this.$http.get(`/v2/api/enforce-handbook/${itemId}`).then(res => {
				if (res.data) {
                    this.handleBookItemData(res.data);
				}
				this.showOverLay = false
			})
        },
        handleBookItemData(res) {
            const data = Object.assign({}, res);
            if (data.result_options) {
                const options = []
                data.result_options = data.result_options.replace(/，/g, ',');
                data.result_options.split(',').map(item => {
                    if (item && item.length > 0) {
                        let str = item.trim().replace('/', '');
                        str = str.replace('#', ',');
                        options.push(str);
                    }
                })
                data.resultOptions = options;
            }
            if (data.other_enforce_item) {
                const list = [];
                const others = res.other_enforce_item.replace('，', ',');
                const otherItems = others.split(',');
                otherItems.map(other => {
                    const item = other.replace('/', '');
                    if (item && item.length > 0) {
                        list.push({
                            k: item,
                            v: ''
                        })
                    }
                })
                data.otherItems = list
            }

            if (data.problems) {
                const vm = this;
                data.problems.map(item => {
                    let arr = [];
                    if (item.problem_images && item.problem_images.length > 0) {
                        item.problem_images.split(',').map(fileId => {
                            arr.push(vm.handleProblemImgs(fileId));
                        });
                    }
                    item.problemImages = arr;
                });
            }
            this.bookInfo = data
            this.initRecordData();
        },
        initRecordData() {
            if (this.data) {
                if (this.data.item_type == '1') {
                    this.typeIndex = 1;
                    this.formData.item_content = this.data.enforce_item;
                }
                else {
                    this.typeIndex = 0;
                    this.checkDesc = {
                        enforce_class: this.data.enforce_class
                    }
                    this.itemDesc = {
                        enforce_content: this.data.enforce_content
                    }
                }
                this.typeDesc = this.columns[this.typeIndex];
                if (this.data.record) {
                    this.formData.check_result = this.data.record.check_result + '';
                    if (this.data.record.item_content) {
                        this.formData.item_content = this.data.record.item_content;
                    }
                    if (this.data.record.check_options) {
                        this.formData.check_options = this.data.record.check_options;
                    }
                    if (this.data.record.records && this.data.record.records.length > 0) {
                        let arr = [];
                        const vm = this;
                        this.data.record.records.map(record => {
                            let pictures = [];
                            if (record.pictures) {
                                record.pictures.split(',').map(id => {
                                    pictures.push({
                                        url: vm.handleProblemImgs(id),
                                        isImage: true,
                                        fileID: id,
                                    });
                                });
                            }
                            arr.push({
                                content: record.check_desc || '',
                                fileList: pictures,
                            });
                        });
                        this.checkNodes = arr;
                    }
                }
            }
        },
        showProblems() {
            let res = this.bookInfo && this.bookInfo.problems;
            if (this.data) {
                res = this.data.problems
            }
            if (this.bookInfo) {
                this.$router.push({
                    name: 'dailyPicTxt',
                    params: {
                        list: res
                    }
                })
            }
        },
		handleProblemImgs,
        showHistory() {
            this.$router.push(`/history/${this.enforceId}`);
        },
        showSettingExpect() {
            let res = this.bookInfo && this.bookInfo.id;
            let isAdd = 1;
            if (this.data) {
                res = this.data.id;
                isAdd = 0;
            }
            if (res) {
                this.$router.push(`/checkStandardExplain/${this.bookInfo.id}?isAdd=${isAdd}`)
            }
            else {
                Notify('暂无设置要求');
            }
        },
        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) {
            // console.log('afterRead file: ', file.file, ', name: ', file.file.name, ', size: ', file.file.size);

			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');

					file.file = file1;
				};
			}
		},
        uploadFile(data) {
            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.checkNodes && this.checkNodes.length > 0) {
                for (let index = 0; index < this.checkNodes.length; index++) {
                    const node = this.checkNodes[index];
                    if (node.fileList && node.fileList.length > 0) {
                        for (let j = 0; j < node.fileList.length; j++) {
                            const file = node.fileList[j];
                            if (!file.fileID && !file.url) {
                                have = true;
                                this.uploadFile(file);
                                break;
                            }
                        }
                    }
                    if (have) {
                        break;
                    }
                }
            }
            return have;
        },
        commitNode() {
            if (this.typeIndex < 0) {
                Notify('请选择检查类型')
                return
            }
            
            if (this.typeIndex === 0) {
                if (!this.checkDesc) {
                    Notify('请选择检查类别')
                    return
                }
                if (!this.itemDesc) {
                    Notify('请选择检查项')
                    return
                }
                this.formData.item_id = this.itemDesc.id;
                this.formData.item_name = this.itemDesc.enforce_item;
                if (this.bookInfo) {
                    const book = Object.assign({}, this.bookInfo);
                    book.handbook_id = book.id;
                    book.id = '';
                    this.formData.handbook = book;
                    // this.formData.handbook = {
                    //     handbook_id: this.bookInfo.id
                    // };
                }
            }
            else {
                if (isEmpty(this.formData.item_content)) {
                    Notify('请输入检查内容')
                    return
                }
                this.formData.item_name = this.formData.item_content;
                this.formData.enforce_item = this.formData.item_content;
                this.formData.enforce_obj_class = '其他';
            }
            this.formData.item_type = this.typeIndex;

            if (!this.formData.check_result) {
                Notify('请选择检查结果')
                return
            }
            
            this.showOverLay = true;
            if (this.checkNodesFile() === false) {
                if (this.bookInfo && this.bookInfo.otherItems) {
                    let arr = [];
                    this.bookInfo.otherItems.map(other => {
                        const v = other.v ? other.v : '';
                        arr.push(v);
                    });
                    this.formData.enforce_job_node_item = arr.join(',');
                }
                const records = [];
                if (this.checkNodes && this.checkNodes.length > 0) {
                    this.checkNodes.map(node => {
                        const pics = [];
                        if (node.fileList) {
                            node.fileList.map(file => {
                                pics.push(file.fileID);
                            })
                        }
                        records.push({
                            item_id: this.formData.item_id,
                            pictures: pics.join(','),
                            check_desc: node.content,
                        });
                    });
                }
                this.formData.records = records;
                this.formData.enforce_obj_id = this.enforceId;
                if (this.data && this.data.job_item_id) {
                    this.formData.id = this.data.job_item_id;
                    this.formData.job_id = this.data.job_id;
                    this.formData.node_id = this.data.node_id;
                    const itemData = Object.assign(this.data, this.formData);
                    this.$http.put(`/v2/api/enforce-job/item`, [itemData]).then(res => {
                        this.showOverLay = false;
                        this.$toast.success('修改成功');
                        BUS.$emit('updateItem');
                        this.backPage();
                    })
                }
                else {
                    this.$http.post(`/v2/api/enforce-job/${this.dailyId}/item`, this.formData).then(res => {
                        this.showOverLay = false;
                        this.$toast.success('新增成功');
                        BUS.$emit('addItem');
                        this.backPage();
                    })
                }
            }
        }
    }
}
</script>

<style lang="scss">
.check {
    .van-uploader {
        padding: 10px;
    }
}
</style>

<style lang="scss" scoped>
.custom-cell-value {
    .van-cell__value {
        flex: 2.1 !important;
    }
}
.page {
    padding-top: 50px;
    height: calc(100vh - 50px);
    overflow-y: auto;

    .problems {
        padding: 4px 14px;
        .problem {
            width: 100%;
            &-pics {
                width: 100%;
                display: flex;
                align-items: center;
                overflow-x: auto;
            }
            .desc {
                margin: 10px 20px;
                font-size: 14px;
            }
        }
    }
    .check {
        margin: 10px 0;
        padding: 8px 12;
    }

    .add {
        display: flex;
        justify-content: flex-end;
        margin-bottom: 60px;
    }

    .submit {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        height: 50px;
        .btn {
            width: 100%;
            height: 100%;
        }
    }
}
</style>