<template>
    <div class="page">
        <headNav :canBack="false" @leftAction="onLeftAction" title="执行任务"></headNav>

        <div class="content" v-if="jobData">
            <van-cell-group v-if="jobData.enforce_obj">
                <van-cell title="单位名称" is-link :value="jobData.enforce_obj_name" @click="turnToCompany" />
                <van-cell title="单位地址" :value="jobData.enforce_obj.enforce_obj_address" />
                <van-cell title="单位法人" :value="jobData.enforce_obj.legal_person" />
                <van-cell title="联系方式" :value="jobData.enforce_obj.legal_person_phone" />
            </van-cell-group>
            <van-cell-group class="mt20">
                <van-cell title="下发单位" :value="jobData.enforce_org_name" />
                <van-cell title="编号" :value="jobData.job_no" />
                <van-cell title="检查时间" :value="jobData.startDate" />
                <van-cell title="检查类型" :value="jobData.jobType" />
                <!-- <van-cell v-if="jobData.job_desc" title="任务描述" :value="jobData.job_desc" /> -->
                <van-cell class="noLine" title="检查内容和情况" />
                <div class="check">
                    <van-field
                        v-model="jobData.job_result_content"
                        rows="4"
                        autosize
                        type="textarea"
                        maxlength="300"
                        placeholder="请输入"
                        show-word-limit
                    />
                    <!-- <van-field
                        v-model="jobData.job_result_content"
                        rows="4"
                        autosize
                        type="textarea"
                        placeholder="请输入"
                    /> -->
                </div>
                <van-divider />
                <van-cell title="现场照片" class="custom-title">
                    <van-uploader
                        v-model="fileList"
                        :max-count="9"
                        :before-read="beforeAvatarUpload"
                        :after-read="afterRead"
                        capture="camera"
                    />
                </van-cell>
                <van-cell class="noLine" title="备注" />
                <div class="check">
                    <van-field
                        v-model="jobData.job_result_remark"
                        rows="4"
                        autosize
                        type="textarea"
                        maxlength="300"
                        placeholder="请输入"
                        show-word-limit
                    />
                    <!-- <van-field
                        v-model="jobData.job_result_remark"
                        rows="4"
                        autosize
                        type="textarea"
                        placeholder="请输入"
                    /> -->
                </div>
                <van-divider />
                <van-field name="radio" required label="检查结论">
                    <template #input>
                        <van-radio-group v-model="jobData.enforce_result" input-align="right" direction="horizontal">
                            <van-radio name="PASS">合格</van-radio>
                            <van-radio name="NOT_PASS">不合格</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
            </van-cell-group>

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

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

<script>
import headNav from '@/components/headNav.vue';
import mask_overLay from '@/components/overLay_xy.vue';
import { get, put } from "@/utils/http.js";
import { Dialog } from 'vant';
import { compressAccurately } from "image-conversion";
import { isEmpty, dateFormat } from '@/utils/tool';
import { handleProblemImgs } from '@/utils/index';

export default {
    components: {
        headNav,
        'v-mask': mask_overLay,
    },
    data () {
        return {
            showOverLay: false,
            tipMsg: '加载中...',
            isloading: false,
            jobData: null,
            fileList: [],
        }
    },
	computed: {
		jobId() {
			return this.$route.params.ID
		},
	},
    mounted () {
        if (this.jobId) {
            this.loadJobDatas();
        }
    },
    methods: {
        onLeftAction() {
			const vm = this;
			Dialog.confirm({
				title: '温馨提示',
				message: '是否放弃该任务？',
				confirmButtonText: '暂存',
				cancelButtonText: '放弃',
			}).then(() => {
				// on confirm
				vm.checkFiles(true);
			}).catch(() => {
				// on cancel
				put(`/v2/api/enforce-job/${this.jobId}/exchange`).then(res => {
					vm.$router.back();
				});
			});
		},
        async loadJobDatas() {
            if (this.isloading) {
                return
            }
            this.isloading = true;
            this.showOverLay = true
            const obj = await get(`/v2/api/enforce-job/${this.jobId}`);
            if (obj) {
                obj.job_desc = '测试一下测试一下测试一下测试一下测试一下测试一下测试一下测试一下';
                obj.startDate = dateFormat('YYYY-mm-dd', new Date(obj.start_time));
                switch (obj.job_type) {
                    case 'OTHER':
                        obj.jobType = '其他检查';
                        break;
                    case 'SPECIAL':
                        obj.jobType = '专项检查';
                        break;
                    case 'REPORT':
                        obj.jobType = '举报检查';
                        break;
                    case 'TOWNS':
                        obj.jobType = '乡镇检查';
                        break;
                    default:
                        obj.jobType = '日常检查';
                        break;
                }
                if (obj.job_result_pictures && obj.job_result_pictures.length > 0) {
                    let pics = [];
                    obj.job_result_pictures.split(',').map(fileId => {
                        pics.push({
                            url: handleProblemImgs(fileId),
                            isImage: true,
                            fileID: fileId
                        });
                    });
                    this.fileList = pics;
                }
            }
            this.jobData = obj;
            this.showOverLay = false;
            setTimeout(() => {
                this.isloading = false;
            }, 2000);
        },
        turnToCompany() {
            if (this.jobData && this.jobData.enforce_obj_id) {
                this.$router.push(`/companyInfo/${this.jobData.enforce_obj_id}`);
            }
        },
        beforeAvatarUpload(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,
				})
				.then((res) => {
						this.showOverLay = false;
					resolve(res);
				});
			});
		},
        afterRead(file) {
			if (file && file.file && file.file.size > 2000000) {
				// 创建Canvas对象(画布)
				let canvas = document.createElement('canvas');
				let context = canvas.getContext('2d');
				let img = new Image();
				img.src = file.content;
				img.onload = () => {
					canvas.width = img.width;
					canvas.height = img.height;
					context.drawImage(img, 0, 0, img.width, img.height);
					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, flag) {
            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.checkFiles(flag);
                }
            })
        },
        checkFiles(flag) {
            if (isEmpty(this.jobData.enforce_result) && flag != true) {
                this.$toast.fail('请选择检查结论');
                return
            }

            this.showOverLay = true;
            let have = false;
            if (this.fileList && this.fileList.length > 0) {
                for (let index = 0; index < this.fileList.length; index++) {
                    const item = this.fileList[index];
                    if (!item.fileID && !item.url) {
                        have = true;
                        this.uploadFile(item, flag);
                        break;
                    }
                }
            }
            if (!have) {
                this.commitTaskInfo(flag);
            }
        },
        commitTaskInfo(flag) {
            this.tipMsg = '提交数据...';
            let pics = [];
            if (this.fileList && this.fileList.length > 0) {
                this.fileList.map(item => {
                    pics.push(item.fileID);
                });
            }
            let params = {
                job_result_content: this.jobData.job_result_content,
                job_result_remark: this.jobData.job_result_remark,
                job_result_pictures: pics.join(','),
                enforce_result: this.jobData.enforce_result,
            }
            put(`/v2/api/enforce-job/${this.jobId}`, params).then(res => {
                this.showOverLay = false;
                if (flag == true) {
                    this.$toast.success('暂存成功');
                    this.$router.back();
                }
                else {
                    this.$toast.success('提交成功');
                    this.$router.replace(`/simpleCheckRecord/${this.jobId}`);
                }
            });
        },
    }
}
</script>

<style lang="scss">
.noLine::after {
    border-bottom: none;
}
.van-radio-group--horizontal {
    justify-content: flex-end;
    width: 100%;
}
.custom-title {
    .van-cell__title {
        flex: 0.5;
    }
    .van-cell__value {
        white-space: inherit;
        flex: 2;
    }
}
</style>

<style lang="scss" scoped>
.check {
    margin: auto 16px;
    border: 1px solid #f0f0f0;
}
</style>