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

        <!-- <div class="png" v-if="pdfPng">
            <img :src="pdfPng" alt="" srcset="" style="width:100%;">
        </div> -->

        <div class="content">
            <div class="filePdf" id="filePdf">
                <div class="title">乡镇消防安全检查记录</div>
                <div class="title">
                    检查单位：
                    <span class="underline">{{formData.enforce_org_name}}</span>
                    编号：{{pdfNumberRes}}
                </div>
                <div class="table">
                    <table>
                        <tr>
                            <td colspan="3">被检查单位(场所)名称</td>
                            <td colspan="2">{{formData.enforce_obj_name}}</td>
                            <td width="50px">消防安全责任人</td>
                            <td>{{formData.enforce_obj && formData.enforce_obj.charge_person}}</td>
                        </tr>
                        <tr>
                            <td colspan="2">地址</td>
                            <td colspan="3">{{formData.enforce_obj && formData.enforce_obj.enforce_obj_address}}</td>
                            <td>联系电话</td>
                            <td>{{formData.enforce_obj && formData.enforce_obj.charge_person_phone}}</td>
                        </tr>
                        <tr>
                            <td colspan="2">检查人员(签名)</td>
                            <!-- @click="showSignPanel(0)" -->
                            <td width="40px"><van-image v-if="executorSign" :src="executorSign"></van-image></td>
                            <td>单位随同检查人员(签名)</td>
                             <!-- @click="showSignPanel(1)" -->
                            <td width="40px"><van-image v-if="companySign" :src="companySign"></van-image></td>
                            <td>检查日期</td>
                            <td>{{formData.start_time}}</td>
                        </tr>
                        <tr>
                            <td colspan="7">检查内容和情况记录</td>
                        </tr>
                        <tr>
                            <td width="20px" rowspan="5">单位场所履行消防安全职责情况</td>
                        </tr>
                        <template v-if="checkList">
                            <tr v-for="(node, index) in checkList" :key="index">
                                <td width="20px">{{node.name}}</td>
                                <td colspan="5">
                                    <div class="items">
                                        <template v-for="item in node.childs">
                                            <div :key="item.id" class="item">
                                                <template v-if="item.handBook.result_options">
                                                    <van-checkbox-group class="options" v-model="item.check_options" direction="horizontal" disabled>
                                                        <span class="mr10">{{item.handBook.sort}}.{{item.handBook.enforce_content}}</span>
                                                        <template v-for="(option, optionIndex) in item.handBook.result_options">
                                                            <van-checkbox shape="square" icon-size="14px" :key="optionIndex" :name="option">{{option}}</van-checkbox>
                                                        </template>
                                                    </van-checkbox-group>
                                                </template>
                                                <span class="mr10" v-else>{{item.handBook.sort}}.{{item.handBook.enforce_content}}</span>
                                            </div>
                                        </template>
                                    </div>
                                </td>
                            </tr>
                        </template>
                        <template v-if="otherRemark">
                            <tr>
                                <td colspan="2">{{otherRemark.enforce_obj_class}}</td>
                                <td colspan="5">{{otherRemark.item_content}}</td>
                            </tr>
                        </template>
                        <tr>
                            <td colspan="7" style="text-align: left;">
                                对以上第
                                <span v-if="taskIsPass" class="underline">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                                <span v-else class="underline">{{nopass}}</span>
                                条火灾隐患（违法行为），你单位（场所）应立即采取措施进行整改消除；
                                在火灾隐患（违法行为）消除前，应采取确保消防安全、防止火灾发生的措施。对
                                <span v-if="taskIsPass" class="underline">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                                <span v-else class="underline">{{nopass}}</span>
                                条火灾隐患（违法行为）责令你于
                                <span v-if="taskIsPass" class="underline">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                                <span v-else class="underline FontColorError" @click="showLimitDate=true">{{ limitDate ? limitDate : '点击选择日期'}}</span>
                                <!-- <span class="underline">{{limit_year}}</span>年
                                <span class="underline">{{limit_month}}</span>月
                                <span class="underline">{{limit_day}}</span>日 -->
                                前整改完毕。
                            </td>
                        </tr>
                    </table>
                </div>
            </div>

            <div class="btn" v-if="showNextBtn">
                <van-button type="primary" @click="backToExecute">上一步</van-button>
                <van-button type="info" @click="saveRecord">下一步</van-button>
            </div>
        </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>

        <van-popup v-model="showLimitDate" position="bottom">
            <van-datetime-picker
                v-model="currentDate"
                type="date"
                title="选择日期"
                :min-date="minDate"
                :max-date="maxDate"
                @confirm="handleConfirmLimitDate"
            />
        </van-popup>

        <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, notEmpty, dataURItoBlob, isEmpty } from '@/utils/tool';
import {getOnePdf} from '@/utils/htmlToPDF.js';
import { post, put } from '@/utils/http.js';
import recordSign from '@/mixins/recordSign';
import pdfNumber from '@/mixins/pdfNumber';
import executeStepMixin from '@/mixins/executeStep';

export default {
    components: {
        headNav,
        baiduMap,
        "v-mask": mask_overLay,
    },
    mixins: [recordSign, pdfNumber, executeStepMixin],
    computed: {
        taskId() {
            return this.$route.params.ID
        },
        taskStart() {
            if (this.formData) {
                const s = this.formData.job_status;
                return s == 'TODO' || s == 'DOING' || s == 'REJECT';
            }
            return false
        },
        taskIsPass() {
            return isEmpty(this.nopass);
        }
    },
    data() {
        return {
            formData: null,
            showOverLay: false,
            tipMsg: '加载中...',
            checkList: [],
            otherRemark: null,
            executorSign: null,
            companySign: null,
            showSignPop: false,
            signType: 0,//0检查人员 1陪同人员
            signValue: '',
            signOptions: {
                isSign: true,
                isShowBorder: false,
                canvasWidth: 350,
                canvasHeight: 245,
                bgColor: '#fff'
            },
            nopass: ' ',
            limit_year: '',
            limit_month: '',
            limit_day: '',
            showLimitDate: false,
            limitDate: null,
            currentDate: null,
            minDate: new Date(),
            maxDate: new Date(2025, 10, 1),
            otherRemark: null,
            showNextBtn: true,
            pdfPng: null,
        }
    },
    mounted() {
        if (this.taskId) {
            this.showOverLay = true;
            this.loadTaskDetailData();
        }
    },
    methods: {
        backToExecute() {
            this.$router.replace(`/town/exec/${this.taskId}`);
        },
        handleConfirmLimitDate() {
            this.showLimitDate = false;
            if (this.currentDate) {
                this.limitDate = dateFormat('YYYY年mm月dd日', this.currentDate);
            }
        },
        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 loadTaskDetailData() {
            this.loadPdfNumber('record');
            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.last_enforce_date) {
                //     const led = obj.last_enforce_date.split('-');
                //     if (led.length > 2) {
                //         this.limit_year = led[0];
                //         this.limit_month = led[1];
                //         this.limit_day = led[2];
                //     }
                // }
                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);
                                if (item.check_options) {
                                    item.check_options = [item.check_options];
                                }
                                item.handBook = {
                                    request: true,
                                };
                                nodeItems.push(item);
                            })
                        }
                        node.items = nodeItems;
                    });
                    let nodeList = [];
                    let count = 0;
                    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) {
                            count += node.items.length;
                            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);
                            nodeList = nodeList.concat(node.items);
                        }
                    }
                    this.checkList = nodeList;
                    obj.count = count;
                }
                this.formData = obj;
                this.loadNopassNum();
            }
            this.updateTaskStep(this.taskId, 'RECORD');
            this.showOverLay = false;
        },
        loadNopassNum() {
            let str = [];
            this.checkList.map(node => {
                if (node.childs) {
                    node.childs.map(item => {
                        let options = item.check_options;
                        if (options && Array.isArray(options)) {
                            options = options.join(',');
                        }
                        if (notEmpty(options) && item.handBook.result_problem_options.indexOf(options) >= 0) {
                            str.push(item.handBook.sort);
                        }
                    });
                }
            });
            if (str.length === 0) {
                this.nopass = '';
            }
            else {
                this.nopass = str.join('、');
            }
        },
        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,
                    count: childs.length,
                };
                res.push(obj);
            });
            return res;
        },
        handleBookItem(result, data) {
            if (result) {
                if (result.check_options) {
                    // 0-不涉及,1-合格,2-不合格
                    let check = 1;
                    if (result.check_options == '不涉及') {
                        check = 0;
                    }
                    if (data.result_problem_options && data.result_problem_options.indexOf(result.check_options) >= 0) {
                        check = 2;
                    }
                    result.checkResult = check;
                }
                else {
                    result.check_options = [];
                }
            }
            let options = []
            if (data.result_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;
        },
        async saveRecord() {
            // if (notEmpty(this.info.result_file_id)) {
            //     this.updateTaskFile();
            //     return;
            // }

            // if (!this.executorSign) {
            //     this.$toast.fail('请检查人员签名');
            //     return;
            // }
            // if (!this.companySign) {
            //     this.$toast.fail('请单位随同检查人员签名');
            //     return;
            // }
            if (!this.currentDate && notEmpty(this.nopass)) {
                this.$toast.fail('请选择整改期限');
                return;
            }

            this.showOverLay = true;
            this.showNextBtn = false;
            this.tipMsg = "保存pdf中";
            let subData = "";

            subData = await getOnePdf(
                document.querySelector("#filePdf"),
                "乡镇消防安全检查记录"
            );
            this.startToSign(subData);
            // return;

            // var blob = this.dataURItoBlob(subData.turnImgData); // 上一步中的函数

            // var canvas = document.createElement("canvas");
            // var dataURL = canvas.toDataURL("image/jpeg", 0.5);
            // var fd = new FormData(document.forms[0]);
            // fd.append("fileBinary", subData.myfile);
            // fd.append("fileName", "乡镇消防安全检查记录.pdf");
            // this.pdfPng = subData.turnImgData;
            // this.showOverLay = false;
            // return;

            // this.tipMsg = "上传pdf中";
            // const 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 res = this.setupStaticNoticeResult(this.formData, 'record');
            put(`/v2/api/enforce-job/${this.taskId}`, {
                id: this.dailyId,
                result_file_id: fileId,
                static_notice_result: res,
            })
            .then((res) => {
                this.$router.replace(`/town/check/${this.taskId}`);
            })
            .catch(() => {
                this.$toast.fail("上传失败");
            });
        }
    }
}
</script>

<style lang="scss">
.my {
    .van-cell__value {
        white-space: normal;
    }
}
.content {
    // .van-row {
    //     border: 1px solid #F00;
    //     .van-col:not(:last-child) {
    //         border-right: 1px solid #F00;
    //     }
    // }
    // .van-row:not(:first-child) {
    //     margin-top: -1px;
    // }
    .van-col {
        height: 100%;
        padding: 2px;
        white-space: normal;
    }
    .options {
        .van-checkbox__icon--disabled .van-icon {
            background-color: #FFFFFF;
            border-color: #c8c9cc;
        }
    }
}
</style>

<style lang="scss" scoped>
.content {
    background-color: #FFFFFF;
    overflow-x: hidden;
    // height: 100vh;
    .mg {
        margin: 16px;
        padding-bottom: 50px;
    }
    .filePdf {
        overflow: auto;
        background-color: #fff;
        font-family: arial;
        font-size: 10px;
    }
    .title {
        margin-top: 10px;
        text-align: center;
    }
    .title:first-child {
        // margin-top: 70px;
        font-size: 18px;
    }
    .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;
        }
        table tr {
            line-height: 20px;
            min-width: 20px;
        }
        .items {
            text-align: left;
            .item {
                margin-top: 2px;
                display: flex;
                flex-wrap: wrap;
                .options {
                    display: flex;
                }
            }
        }
    }
}
.underline {
    min-width: 40px;
    width: 40px;
    min-height: 10px;
}
.btn {
    margin: 15px 0;
    display: flex;
    justify-content: space-around;

    button {
        flex: 1;
        margin: 5px 25px;
        height: 40px;
    }
}
</style>
