<template>
    <div class="detail">
        <KVTable title="基本信息" :list="basicInfo" :enforce_result="enforce_result" :rightButton="rightButton">
            <template #slotValue="slot">
                <template v-if="slot.row.type">
                    <template v-if="slot.row.type === 1">
                        {{ slot.row.value }} <span class="blueFont point" @click="showEnfoceObjDetail">[查看详情]</span>
                    </template>
                    <template v-if="slot.row.type === 2">
                        {{ slot.row.value }} <i class="blueFont el-icon-location point"
                                                @click="showMap(slot.row.value)"></i>
                    </template>
                    <template v-if="slot.row.type === 3">
                        <span :class="slot.row.color">{{ slot.row.value }}</span>
                        <span class="blueFont point" @click="showSendMessageBox">[查看详情]</span>
                    </template>
                    <template v-if="slot.row.type === 4">
                        <span :class="slot.row.color">{{ slot.row.value }}</span>
                    </template>
                    <template v-if="slot.row.type === 5">
                        {{ slot.row.value }}
                        <span v-if="slot.row.show" @click="showCheckPDF" class="blueFont point">[查看详情]</span>
                    </template>
                    <template v-if="slot.row.type === 6">
                        <div class="point result"><span>
                             {{ slot.row.value }}，</span>
                            <div v-if="slot.row.xg" @click="showXGPDF()">
                                <span>责令限期改正通知书</span>
                                <span class="blueFont">[查看详情]</span>
                            </div>
                            <div v-if="slot.row.lg" @click="showLGPDF()">
                                <span>责令立即改正通知书</span>
                                <span class="blueFont">[查看详情]</span>
                            </div>
                        </div>
                    </template>
                </template>
                <template v-else>
                    {{ slot.row.value }}
                </template>
            </template>
        </KVTable>
        <el-dialog :title="addressTitle" :visible.sync="addressMap">
            <div id="container"></div>
        </el-dialog>

        <el-dialog :title="videos.cameraname" :visible.sync="dialogPlay" width="50%" @close="closeDialog">
            <video :src="videos.url" controls autoplay class="video"
                   width="100%"></video>
        </el-dialog>
        <el-dialog title="查看视频" :visible.sync="showVideoDialog">
            <show-video v-if="showVideoDialog" :taskId="jobId"></show-video>
        </el-dialog>
    </div>
</template>

<script>
    import KVTable from '@/component/KVTable'
    import {jobMixin} from '@/mixin/job'
    import {resourceMixin} from '@/mixin/resource'
    import {formatDate, formatDateMonth} from '@/utils/tool'
    import {getOneJob, getOneJobStatistics, getJobVideos, getJobs} from '@/api/job'
    import {openPng, exportFile} from '@/api/file'
    import ShowVideo from '@/component/ShowVideo'

    export default {
        name: "ReportDetail",
        components: {
            KVTable,
            ShowVideo
        },
        mixins: [jobMixin, resourceMixin],
        data() {
            return {
                baseUrl: process.env.VUE_APP_API,
                enforce_result: null,
                objData: null,
                basicInfo: [],
                rightButton: {},
                recentDatas: [],
                showVideoDialog: false,
                staticDatas: [
                    {
                        icon: 'el-icon-time',
                        name: '检查耗时',
                        value: '0:00'
                    },
                    {
                        icon: 'el-icon-data-analysis',
                        name: '通勤耗时',
                        value: '0:00'
                    },
                    {
                        icon: 'el-icon-video-camera',
                        name: '执法视频',
                        value: '查看'
                    }
                ],
                query: {},
                nodes: [],
                addressMap: false,
                addressTitle: '',
                imgUrls: [],
                imgUrlsList: [],
                job_result_content: '',
                job_result_remark: '',
                videos: {
                    url: '',
                    cameraid: '',
                    cameraname: ''
                },
                dialogPlay: false

            }
        },
        computed: {
            jobId() {
                return this.$route.query.id
            },
            pdfUrl() {
                return process.env.VUE_APP_PDF
            },
            apiUrl() {
                if (process.env.NODE_ENV == 'development') {
                    return 'http://183.66.101.90:10023/v2/api'
                }
                return process.env.VUE_APP_API + '/v2/api'
            }
        },
        mounted() {
            //    console.log("@",process.env.VUE_APP_API)
            this.getJobDetail();
            this.recentJobsDatas();
        },
        methods: {
            formatDate,
            showStaticItem(index) {
                if (index === 2) {
                    this.showVideoDialog = true;
                }
            },
            //列表下载
            listDownload(id, name) {
                this.downloadPdf(id, name);
            },
            //当前下载
            oneDownload() {
                this.downloadPdf(this.objData.result_file_id, this.objData.result_file_name)
            },
            //下载文书
            downloadPdf(id, name) {
                exportFile(id).then(res => {
                    this.pdfUrlOther = window.URL.createObjectURL(new Blob([res],
                        {type: `application/pdf`}));
                    const fname = name; // 下载文件的名字
                    const link = document.createElement('a');
                    link.href = this.pdfUrlOther;
                    link.setAttribute('download', fname);
                    document.body.appendChild(link);
                    link.click();
                })
            },
            showEnfoceObjDetail() {
                this.$router.push({
                    path: '/resource/detail',
                    query: {
                        id: this.objData.enforce_obj_id
                    }
                })
            },
            getJobDetail() {
                if (this.jobId) {
                    getOneJob(this.jobId).then(res => {
                        if (res) {
                            this.objData = res;
                            this.generateBasicInfo(res)
                            if (res.check_nodes) {
                                res.check_nodes.map(node => {
                                    if (node.items && node.items.length > 0) {
                                        const items = []
                                        node.items.map(item => {
                                            const obj = Object.assign({}, item)
                                            obj.item_id = item.id
                                            obj.checkResult = item.check_result === 1 ? '合格' : (item.check_result === 2 ? '不合格' : '不涉及')
                                            if (item.hanbook) {
                                                obj.enforce_class = item.hanbook.enforce_class
                                                obj.enforce_item = item.hanbook.enforce_item
                                                obj.enforce_method = item.hanbook.enforce_method
                                                obj.hanbook = undefined
                                            }
                                            if (item.item_type === '1' && item.item_content) {
                                                obj.enforce_class = '其它'
                                                obj.enforce_item = item.item_content
                                            }
                                            items.push(obj)
                                        })
                                        node.items = items
                                    }
                                })
                                this.nodes = res.check_nodes
                            }
                        }

                        getOneJobStatistics(this.jobId).then(result => {
                            if (result) {
                                this.staticDatas[0].value =this.ChangeHourMinutestr(result.checkTime)
                                this.staticDatas[1].value = this.ChangeHourMinutestr(result.commutingTime)
                            }
                            console.log('汇总情况result: ', result)
                        })
                    })
                }
            },
            ChangeHourMinutestr(str) {
                if (str !== "0" && str !== "" && str !== null) {
                    return ((Math.floor(str / 60)).toString().length < 2 ? "0" + (Math.floor(str / 60)).toString() :
                        (Math.floor(str / 60)).toString()) + ":" + ((str % 60).toString().length < 2 ? "0" + (str % 60).toString() : (str % 60).toString());
                } else {
                    return "00:00";
                }
            },
            getAppointmentFontColor(status) {
                if (status === 'NOT') {
                    return 'danger'
                }
                if (status === 'SENDING') {
                    return 'yellowFont'
                }
                return 'success'
            },
            getJobStatusFontColor(status) {
                if (status === 'REJECT') {
                    return 'danger'
                }
                if (status === 'DOING') {
                    return 'blueFont'
                }
                if (status === 'ACCEPT') {
                    return 'success'
                }
                return 'yellowFont'
            },
            recentJobsDatas() {
                if (!this.query.query) {
                    this.query.query = "job_type=='REPORT'"
                } else {
                    this.query.query = this.query.query + ";job_type=='REPORT'"
                }
                getJobs(this.query).then(res => {
                    if (res) {
                        this.total = res.total || 0
                        const list = res.data || []
                        list.map(item => {
                            item.start_time = formatDate(item.start_time, true)
                        })
                        this.recentDatas = list
                    }
                })
            },
            generateBasicInfo(res) {
                this.enforce_result = res.enforce_result;
                if (res && res.job_result_pictures) {
                    this.imgUrls = res.job_result_pictures.split(",");
                }
                // imgUrlsList
                this.imgUrls.forEach(item => {
                    this.imgUrlsList.push(this.apiUrl + '/file/' + item + '/open')
                })
                this.job_result_content = res.job_result_content
                this.job_result_remark = res.job_result_remark
                const mainUser = res.executors && res.executors.length > 0 ? res.executors[0] : null
                const secondUser = res.executors && res.executors.length > 1 ? res.executors[1] : null
                this.basicInfo = [

                    [
                        {
                            label: '举报人：',
                            value: res.report_user_name || '-'
                        },
                        {
                            label: '举报时间：',
                            value: formatDate(res.create_time, true) || '-'
                        }
                    ],
                    [
                        {
                            label: '联系方式：',
                            value: res.report_user_phone || '-'
                        },
                        {
                            label: '通讯地址：',
                            value: res.report_user_address || '-',
                            type: 2
                        }
                    ],
                    [
                        {
                            label: '电子邮箱：',
                            value: res.report_user_mail || '-'
                        },
                        {
                            label: '邮编：',
                            value: res.report_user_post || '-'
                        },
                    ],
                    [
                        {
                            label: '举报概要：',
                            value: res.job_desc || '-',
                            row: true
                        },

                    ],
                    [
                        {
                            label: '举报内容：',
                            value: res.report_content || '-',
                            row: true
                        },

                    ],


                ];
                if (res) {
                    let data = [
                        {
                            label: '审核状态：',
                            value: this.parseJobAuditStatus(res.job_status) || '-',
                            type: 4,
                            color: this.getJobStatusFontColor(res.job_status)
                        }
                    ]
                    if (res.job_status === 'ARCHIVED' || res.job_status === 'TODO' || res.job_status === 'DOING') {
                        data.push({
                            label: '任务编号：',
                            value: res.job_no || '-'
                        })

                        this.basicInfo.push(data);
                        let d1 = [
                            {
                                label: '被检查单位：',
                                value: res.enforce_obj && res.enforce_obj.enforce_obj_name || '-',
                                type: 1
                            },
                            {
                                label: '执法机构：',
                                value: res.enforce_org_name || '-'
                            },
                        ];

                        this.basicInfo.push(d1);


                        let d2 = [
                            {
                                label: '主检查员：',
                                value: mainUser && mainUser.user_name || '-'
                            },
                            {
                                label: '联系电话：',
                                value: mainUser && mainUser.phone || '-'
                            }
                        ];

                        this.basicInfo.push(d2);
                        let d3 = [
                            {
                                label: '协检查员：',
                                value: secondUser && secondUser.user_name || '-'
                            },
                            {
                                label: '联系电话：',
                                value: secondUser && secondUser.phone || '-'
                            }
                        ];
                        this.basicInfo.push(d3);

                        this.basicInfo.push([
                            {
                                label: '检查期限：',
                                value: res.last_enforce_date || '-',
                                row: true
                            },
                        ])

                    }
                }
            },
            showCheckPDF() {
                const fileId = this.objData.result_file_id;
                this.showPdf(fileId);
            },
            showXGPDF() {
                const fileId = this.objData.deadline_file_id;
                this.showPdf(fileId);
            },
            showLGPDF() {
                const fileId = this.objData.immediately_file_id;
                this.showPdf(fileId);
            },
            showPdf(fileId) {
                if (fileId) {
                    let url = this.apiUrl + `/file/${fileId}/open`;
                    url = window.btoa(url);
                    window.open(this.pdfUrl + url);
                }
            },
            showMap(address) {
                this.addressTitle = address
                this.addressMap = true
                this.$nextTick(() => {
                    // eslint-disable-next-line no-undef
                    const map = new AMap.Map('container', {
                        resizeEnable: true,
                        animateEnable: true,
                        zoom: 16
                    })
                    // eslint-disable-next-line no-undef
                    this.marker = new AMap.Marker({
                        map: map,
                        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
                    })
                    // eslint-disable-next-line no-undef
                    AMap.plugin('AMap.PlaceSearch', () => {
                        // eslint-disable-next-line no-undef
                        let placeSearch = new AMap.PlaceSearch({
                            pageSize: 1, // 单页显示结果条数
                            pageIndex: 1, // 页码
                            extensions: 'all',
                        })
                        placeSearch.search(address, (status, result) => {
                            if (status === 'complete' && result.poiList.pois && result.poiList.pois.length > 0) {
                                let l = result.poiList.pois[0].location
                                // eslint-disable-next-line no-undef
                                this.marker.setPosition(new AMap.LngLat(l.lng, l.lat))
                                // eslint-disable-next-line no-undef
                                map.setCenter(new AMap.LngLat(l.lng, l.lat))
                            }
                        })
                    })
                })
            },
            // showResultFile() {
            //     exportFile(this.objData.result_file_id).then(res => {
            //         this.pdfUrl = window.URL.createObjectURL(new Blob([res], {type: `application/pdf`}));
            //         const fname = `检查文书`; // 下载文件的名字
            //         const link = document.createElement('a');
            //         link.href = this.pdfUrl;
            //         link.setAttribute('download', fname);
            //         document.body.appendChild(link);
            //         link.click();
            //     })
            // },
            showVideos() {
                getJobVideos(this.objData.id).then(res => {
                    if (res && res.data && res.data.url) {
                        this.videos = res.data
                        this.dialogPlay = true;
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '该任务还未完成'
                    });
                });
            },
            closeDialog() {
                this.dialogPlay = false;
                this.videos.url = ""; //清空数据 关闭视频播放
                this.videos.cameraid = "";
                this.videos.cameraname = "";
            },
            //todo 抽离公用失败
            parseJobAuditStatus(statusCode) {
                if (!statusCode || "AUDIT" === statusCode) {
                    return "审核中"
                }

                if ("REJECT" === statusCode) {
                    return "已驳回"
                }

                if ("TODO" === statusCode || "DOING" === statusCode || "ARCHIVED" === statusCode) {
                    return "已通过"
                }
            }
        }
    }
</script>

<style lang="scss" scoped>
    .result {
        display: flex;
    }

    .point {
        cursor: pointer;
    }

    .mt {
        margin-top: 20px;
        padding-bottom: 20px;
    }

    .statistic {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .node {
        padding-bottom: 20px;

        .header {
            display: flex;
            justify-content: flex-start;
            align-items: center;

            .node-name {
                font-size: 16px;
                color: #343435;
                font-weight: bold;
            }

            .node-detail {
                margin-left: 15px;
                font-size: 13px;
                color: #888888;
                max-width: 600px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }
    }

    #container {
        width: 100%;
        height: 400px;
    }
</style>
