<template>
    <div class="page">
        <headNav title="监督检查记录"></headNav>

        <div class="content" v-if="formData">
            <div class="file" id="file">
                <div class="title">
                    <span>消防监督检查记录</span>
                </div>
                <div class="subtitle">
                    <span>(其他形式消防监督检查适用)</span>
                </div>
                <div class="other">
                    <span>编号：{{ formData.job_no }}</span>
                </div>
                <div class="other">
                    <span>检查时间：{{ formData.start_time }}</span>
                </div>
                <div class="table">
                    <table cellspacing="0" cellpadding="2">
                        <tr>
                            <td width="10%">检查类型</td>
                            <td colspan="4">
                                <div class="row">
                                    <van-checkbox-group v-model="checkResult">
                                        <van-checkbox v-for="(option, index) in typeOptions" :key="index" shape="square" :name="option">{{option}}</van-checkbox>
                                    </van-checkbox-group>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td rowspan="2">单位情况</td>
                            <td width="20%">单位（场所）名称</td>
                            <td width="30%">{{ formData.enforce_obj.enforce_obj_name }}</td>
                            <td width="20%">法定代表人/主要负责人</td>
                            <td width="20%">{{ formData.enforce_obj.legal_person }}</td>
                        </tr>
                        <tr>
                            <td>地址</td>
                            <td>{{ formData.enforce_obj.enforce_obj_address }}</td>
                            <td>联系人及联系电话</td>
                            <td>{{ formData.enforce_obj.legal_person }}/{{ formData.enforce_obj.legal_person_phone }}</td>
                        </tr>
                        <tr>
                            <td width="10%">检查内容和情况</td>
                            <td colspan="4" style="text-align: left;">
                                <div class="nodes">
                                    <template v-for="item in nodeItems">
                                        <div class="item" :key="item.id">
                                            <div>{{item.sort}}.{{item.title}}</div>
                                            <template v-if="item.resultOptions">
                                                <van-radio-group class="options" v-model="item.check_options" direction="horizontal" disabled>
                                                    <template v-for="(option, optionIndex) in item.resultOptions">
                                                        <van-radio icon-size="16px" shape="square" :key="optionIndex" :name="option">{{option}}</van-radio>
                                                    </template>
                                                </van-radio-group>
                                            </template>
                                            <template v-if="item.otherOptions">
                                                <template v-for="(other, otherIndex) in item.otherOptions">
                                                    <div :key="otherIndex"><span>{{other.k}}:</span><span class="underLine">{{other.v}}</span></div>
                                                </template>
                                            </template>
                                        </div>
                                    </template>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td width="10%">备注</td>
                            <td colspan="4" style="text-align: left;">
                                <div v-for="(remark, remarkInd) in remarkList" :key="remarkInd">
                                    {{remark}}
                                </div>
                            </td>
                        </tr>
                    </table>
                </div>
                <div class="info" @click="showSignPanel(0)">消防监督检查员(签名)：
                    <div class="underLine">
                        <img :src="executorSign" alt="" srcset="">
                    </div>
                </div>
                <div class="info" @click="showSignPanel(1)">被检查单位随同检查人员(签名)：
                    <div class="underLine">
                        <img :src="companySign" alt="" srcset="">
                    </div>
                </div>
                <div class="info">此记录由消防机构存档。对大型群众性活动举办前进行消防安全检查的，另制作一份加盖印章后移交公安机关治安管理部门，由其在存档联备注栏签收。</div>
            </div>
        </div>

        <div class="btns" v-if="!isRead">
            <van-button type="info" block @click="commitRecord">下一步</van-button>
        </div>

        <van-popup v-model="showSignPop" position="bottom">
            <div class="signPop">
            <div class="signContent" v-if="showSignPop">
                <sign-canvas
                    class="sign-canvas"
                    ref="SignCanvas"
                    :options="signOptions"
                    v-model="signValue"
                />
            </div>
            <div class="signPopbtn">
                <van-button type="info" plain @click="clearCanvas">清除</van-button>
                <van-button type="info" @click="saveCanvas">保存</van-button>
            </div>
            </div>
        </van-popup>

        <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 { downloadPDF } from "@/utils/htmlToPDF.js";

import { dateFormat, dataURItoBlob, notEmpty } from '@/utils/tool';
import { post, put } from "@/utils/http.js";
import { getInfo } from "@/utils/auth";
import recordSign from '@/mixins/recordSign';
// import { compressAccurately } from "image-conversion";

export default {
    components: {
        headNav,
        "v-mask": mask_overLay,
    },
    mixins: [recordSign],
    data () {
        return {
            remark: null,
            formData: null,
            showOverLay: false,
            typeOptions: [
                '大型群众性活动举办前的检查',
                '建设工程施工现场检查',
                '对举报投诉的检查',
                '申请恢复施工、使用、生产、经营的检查',
                '申请解除临时查封的检查',
            ],
            checkList: [],
            checkResult: [],
            tipMsg: '加载中...',
            signOptions: {
                isSign: true,
                isShowBorder: false,
                canvasWidth: 350,
                canvasHeight: 245,
                bgColor: '#fff'
            },
            signValue: null,
            executorSign: null,
            companySign: null,
            showSignPop: false,
            signType: 0,//0检查人员 1陪同人员
            remarkList: [],
            nodeItems: [],
        }
    },
    computed: {
        dailyId() {
			return this.$route.params.ID
		},
        isRead() {
            return this.$route.params.isRead
        },
        loginUser() {
            const user = getInfo();
            if (user) {
                return user.userInfo;
            }
            return null;
        },
    },
    mounted () {
        if (this.dailyId) {
            this.loadDatas();
        }
    },
    methods: {
        showSignPanel(type) {
            this.showSignPop = true;
            this.signType = type;
            if (type === 0 && this.executorSign) {
                this.signValue = this.executorSign;
            }
            if (type === 1 && this.companySign) {
                this.signValue = this.companySign;
            }
        },
        clearCanvas() {
            this.$refs.SignCanvas.canvasClear();
        },
        saveCanvas() {
            this.showSignPop = false;
            if (this.signValue) {
                if (this.signType === 0) {
                    this.executorSign = this.signValue;
                }
                else if (this.signType === 1) {
                    this.companySign = this.signValue;
                }
                this.signValue = null;
            }
        },
        async commitRecord() {
            // if (!this.executorSign) {
            //     this.$toast.fail('请检查人员签名');
            //     return;
            // }
            // if (!this.companySign) {
            //     this.$toast.fail('请单位随同检查人员签名');
            //     return;
            // }

            this.showOverLay = true;
            this.tipMsg = "上传pdf中";
            const subData = await downloadPDF(
                document.querySelector("#file"),
                "消防监督检查记录"
            );
            
            this.startToSign(subData);
            // return;

            // this.tipMsg = "上传pdf中";
            // let imgblob = dataURItoBlob(subData.turnImgData);
            // imgblob = await compressAccurately(imgblob, {
            //     size: 500,
            // });
            // let imgFd = new FormData();
            // imgFd.append("fileBinary", imgblob, "pdf.png");
            // imgFd.append("fileName", '消防监督检查记录.png');
            // // 上传图片
            // let imgUploadRes = await this.$http.post("/v2/api/file", imgFd);
            // if (imgUploadRes.data && imgUploadRes.data.id) {
            //     this.formData.result_png_file_id = imgUploadRes.data.id;
            // }

            // var fd = new FormData(document.forms[0]);
            // fd.append("fileBinary", subData.myfile);
            // fd.append("fileName", "消防监督检查记录.pdf");
            // let res = await post("/v2/api/file", fd);
            // if (res.id) {
            //     this.formData.result_file_id = res.id;
            //     this.updateTaskRecordFile();
            // } else {
            //     this.$toast.fail("上传失败");
            // }
            // this.showOverLay = false;
        },
        updateTaskRecordFile() {
            const fileId = this.formData.result_file_id;
            // const png = this.formData.result_png_file_id;
            this.showOverLay = true;
            let params = {
                id: this.dailyId,
                result_file_id: fileId
            };
            // if (png) {
            //     params.result_png_file_id = png;
            // }
            put(`/v2/api/enforce-job/${this.dailyId}`, params)
            .then((res) => {
                this.$router.replace(`/checkResult/${this.dailyId}/normal`);
            })
            .catch(() => {
                this.$toast.fail("上传失败");
            });
            this.showOverLay = false;
        },
        async loadDatas() {
            this.showOverLay = true;
            let res = await this.$http.get(`/v2/api/enforce-job/${this.dailyId}`);
            if (res && res.data) {
                const obj = Object.assign({}, res.data);
                if (obj.start_time) {
                    obj.start_time = dateFormat('YYYY年mm月dd日HH时', new Date(res.data.start_time));
                }
                // this.formData = obj;

                res = await this.$http.get("/v2/api/enforce-handbook?page=1&size=100000&sort=sort asc&query=enforce_type==0");
                if (res.data.data) {
                    this.handleBookDatas(obj, res.data.data);
                }
            }
            this.showOverLay = false;
        },
        getBookData(itemId, books) {
            const res = books.filter(book => itemId == book.id);
            return res.length > 0 ? res[0] : null;
        },
        handleBookDatas(obj, books) {
            if (obj.check_nodes && books.length > 0) {
                let arr = [];
                let items = [];
                for (let index = 0; index < obj.check_nodes.length; index++) {
                    const node = obj.check_nodes[index];
                    if (node.items) {
                        for (let j = 0; j < node.items.length; j++) {
                            const item = node.items[j];
                            if (item.item_id) {
                                const book = this.getBookData(item.item_id, books);
                                if (book) {
                                    this.handleBookItem(item, book);
                                }
                                items.push(item);
                            }
                            else {
                                let str = item.item_content || '';
                                if (notEmpty(str)) {
                                    switch (item.check_result) {
                                        case 1:
                                        str += ' -- 合格';
                                        break;
                                        case 2:
                                        str += ' -- 不合格';
                                        break;
                                        default:
                                        str += ' -- 不涉及';
                                        break;
                                    }
                                    arr.push(str);
                                }
                            }
                        }
                    }
                }
                this.remarkList = arr;
                items = items.sort((a, b) => {
                    // console.log(a.sort, ' -- ', b.sort);
                    return a.sort - b.sort
                });
                this.nodeItems = items;
            }
            this.formData = obj;
        },
        handleBookItem(result, data) {
            result.sort = data.sort;
            result.title = data.enforce_class + '-' + data.enforce_content;
            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);
                    }
                })
                result.resultOptions = options;
            }
            if (data.other_enforce_item) {
                const list = [];
                const resultOthersStr = result && result.enforce_job_node_item && result.enforce_job_node_item.replace(/，/g, ',') || '';
				const resultOthers = resultOthersStr.split(',');
                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 (resultOthers && resultOthers.length > index) {
                            obj.v = resultOthers[index];
                        }
                        list.push(obj);
                    }
                })
                result.otherOptions = list;
            }
        },
    }
}
</script>

<style lang="scss">
.row {
    .van-checkbox {
        margin: 4px;
    }
}
</style>

<style lang="scss" scoped>
.content {
    margin-top: 20px;
    background-color: #FFFFFF;
    height: calc(100vh - 90px) !important;
}
.file {
    overflow: auto;
    padding-bottom: 10px;
}
.title {
    margin-top: 68px;
    width: 100%;
    text-align: center;
    font-size: 20px;
    font-weight: bolder;
    color: #343434;
}
.subtitle {
    width: 100%;
    text-align: center;
    font-size: 14px;
    color: #676767;
}
.other {
    margin-right: 14px;
    text-align: right;
    font-size: 14px;
    color: #343434;
}
.other:first-child {
    margin-top: 8px;
}
.table {
    margin: 10px 14px;
    font-size: 10px;
    border: 1px solid #676767;
    table tr th, table tr td { 
        border:1px solid #E6E6E6; 
    }
    table {
        min-height: 25px; 
        line-height: 25px; 
        text-align: center; 
        border-collapse: collapse; 
        padding:2px;
        table-layout: fixed;
    }
    .row {
        display: flex;
        flex-wrap: wrap;
    }
}
.info {
    padding: 10px 14px 0;
    font-size: 12px;
    display: flex;
}
.info:last-child {
    font-size: 10px;
}
.btns {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 44px;
}
.underLine {
    text-decoration: underline;
    &>img {
        width: 50px;
    }
}
</style>