<template>
    <div class="detail">
        <KVTable3 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[1] }}
                        <span class="blueFont" @click="showEnforceObjDetail">[查看详情]</span>
                    </template>
                    <template v-if="slot.row.type === 2">
                        {{ slot.row.value }} <i class="blueFont el-icon-location" @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">[查看详情]</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="oneDownload"
                              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&&slot.row.class==='result2'" @click="showXGPDF()">
                                <span>责令限期改正通知书</span>
                                <span class="blueFont">[查看详情]</span>
                            </div>
                            <div v-if="slot.row.lg&&slot.row.class==='result2'" @click="showLGPDF()">
                                <span>责令立即改正通知书</span>
                                <span class="blueFont">[查看详情]</span>
                            </div>
                        </div>

                    </template>
                </template>
                <template v-else>
                    {{ slot.row.value }}
                </template>
            </template>
        </KVTable3>
        <form-option title="近期检查" class="mt">

            <el-table
                    :data="recentDatas"
                    stripe
                    border>
                <el-table-column type="index" align="center" label="序号" width="80"/>
                <el-table-column prop="enforce_obj_name" show-overflow-tooltip label="任务编号"/>
                <el-table-column prop="start_time" show-overflow-tooltip label="检查时间" align="center">
                    <template slot-scope="scope">{{ formatDate(scope.row.start_time, true) }}</template>
                </el-table-column>
                <el-table-column prop="enforce_org_name" show-overflow-tooltip label="检查机构" align="center">
                    <template slot-scope="scope">{{scope.row.result_file_name}}</template>
                </el-table-column>
                <el-table-column prop="executor_names" show-overflow-tooltip label="检查人员" align="center"/>
                <el-table-column prop="enforce_org" show-overflow-tooltip label="隐患数量" align="center"/>
                <el-table-column prop="executors_names" show-overflow-tooltip label="已整改数量" align="center"/>
                <el-table-column prop="action" label="检查文书" align="center">
                    <template slot-scope="scope">
                        <el-button v-if="scope.row.result_file_id" type="text" size="small"
                                   @click="listDownload(scope.row.result_file_id,scope.row.result_file_name)">查看
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="action" label="检查结果" align="center">
                    <template slot-scope="scope">
                        <span :class="scope.row.statusClass">{{ parseStatus(scope.row.enforce_result) }}</span>
                    </template>
                </el-table-column>
            </el-table>

        </form-option>
        <form-option title="汇总情况" class="mt" v-if="objData && objData.enforce_result != 'OVERPASS'">
            <div class="statistic plr">
                <other-statistic-item v-for="(item, index) in staticDatas" :key="index"
                                      @click.native="showStaticItem(index)"
                                      :data="item"></other-statistic-item>
            </div>
        </form-option>

        <form-option title="检查详情" class="mt" v-if="objData && objData.enforce_result != 'OVERPASS'">
            <el-descriptions :column="1" border>
                <el-descriptions-item label="检查内容和情况：" :labelStyle="{'width':'150px','text-align': 'right'}">
                    {{ objData.job_result_content || (job_status ? '无' : '') }}
                </el-descriptions-item>
                <el-descriptions-item label="现场照片：" :labelStyle="{'width':'150px','text-align': 'right'}">
                    <el-row :gutter="50" v-if="this.objData.job_result_pictures">
                        <template v-if="imgUrls && imgUrls.length">
                            <el-col :span="3" v-for="url in imgUrls" :key="url">
                                <el-image style="width: 100px; height: 100px" :src="baseUrl+'/v2/api/file/'+url+'/open'"
                                          lazy :preview-src-list="imgUrlsList">
                                </el-image>
                            </el-col>
                        </template>
                        <template v-else>
                            <el-col :span="3">{{(job_status ? '无' : '')}}</el-col>
                        </template>
                    </el-row>
                </el-descriptions-item>
                <el-descriptions-item label="备注：" :labelStyle="{'width':'150px','text-align': 'right'}">
                    {{ objData.job_result_remark || (job_status ? '无' : '') }}
                </el-descriptions-item>
            </el-descriptions>
        </form-option>

        <KVTable title="检查详情" :list="noCheckList" :job_status="job_status" :enforce_result="enforce_result" :fixedLine="true" v-if="objData && objData.enforce_result == 'OVERPASS'"></KVTable>

        <el-dialog :title="addressTitle" :visible.sync="addressMap">
            <div id="container"></div>
        </el-dialog>
        <el-dialog title="查看单位信息" :visible.sync="orgVisible" v-if="orgVisible">
            <org-info :id="this.orgId"></org-info>
        </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 KVTable3 from '@/component/KVTable3'
    import ShowVideo from '@/component/ShowVideo'
    import FormOption from '@/component/FormOption.vue'
    import OtherStatisticItem from './component/OtherStatisticItem.vue'
    import {jobMixin} from '@/mixin/job'
    import {resourceMixin} from '@/mixin/resource'
    import {formatDate, notEmpty} from '@/utils/tool'
    import {getOneJob, getOneJobStatistics, getRecent} from '@/api/job'
    import OrgInfo from "@/component/OrgInfo";
    import {openPng, exportFile} from '@/api/file'
    import {getPlaceTypes} from '@/api/resource'

    export default {
        components: {
            KVTable,
            KVTable3,
            FormOption,
            OtherStatisticItem,
            OrgInfo,
            ShowVideo
        },
        mixins: [jobMixin, resourceMixin],
        data() {
            return {
                baseUrl: process.env.VUE_APP_API,
                enforce_result: null,
                basicInfo: [],
                objData: {},
                rightButton: {},
                recentDatas: [],
                orgVisible: false,
                staticDatas: [
                    {
                        icon: 'el-icon-time',
                        name: '检查耗时',
                        value: '00:00'
                    },
                    {
                        icon: 'el-icon-data-analysis',
                        name: '通勤耗时',
                        value: '00:00'
                    },
                    {
                        icon: 'el-icon-video-camera',
                        name: '执法视频',
                        value: '查看'
                    }
                ],
                nodes: [],
                query: {},
                addressMap: false,
                addressTitle: '',
                imgUrls: [],
                imgUrlsList: [],
                job_result_content: '',
                job_result_remark: '',
                showVideoDialog: false,
                placeType: [],
              noCheckList: [],
              job_status: ''
            }
        },
        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/file'
                }
                return process.env.VUE_APP_API + '/v2/api/file'
            }
            // 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() {
            //  this.getPlaceTypesAll();
            this.getJobDetail();
        },
        methods: {

            formatDate,
            showLGPDF() {
                const fileId = this.objData.immediately_file_id;
                this.showPdf(fileId);
            },
            showXGOrLGPDF(row) {
                if (row.xg) {
                    this.showXGPDF();
                } else if (row.lg) {
                    this.showLGPDF();
                }
            },
            showXGPDF() {
                const fileId = this.objData.deadline_file_id;
                this.showPdf(fileId);
            },
            async getPlaceTypesAll() {
                const list = await getPlaceTypes();
                if (list && list.length > 0) {
                    this.placeType = list;
                }
            },
            handleItemRecords(item) {
                let images = [], res = [];
                if (item.records) {
                    item.records.map(obj => {
                        if (obj.pictures) {
                            obj.pictures.split(',').map(fileId => {
                                if (fileId) {
                                    images.push(`${this.apiUrl}/file/${fileId}/open`);
                                    // images.push('https://img2.baidu.com/it/u=3857110896,2991552077&fm=26&fmt=auto');
                                    // images.push('https://img0.baidu.com/it/u=3987829044,4252062811&fm=26&fmt=auto');
                                    // images.push('https://img2.baidu.com/it/u=3632709951,3282474928&fm=26&fmt=auto');
                                }
                            });
                        }
                        if (notEmpty(obj.check_desc)) {
                            res.push(obj.check_desc);
                        }
                        // res.push('检查情况说明...');
                    });
                }
                // debugger;
                item.recordImgs = images;
                item.recordDesc = res;
            },
            showStaticItem(index) {
                if (index === 2) {
                    this.showVideoDialog = true;
                }
            },
            //列表下载
            listDownload(id, name) {
                // this.downloadPdf(id, name);
                this.showPdf(id);
            },
            //当前下载
            oneDownload() {
                this.showPdf(this.objData.result_file_id);
            },
            //下载文书
            downloadPdf(id, name) {
                exportFile(id).then(res => {
                    this.pdfUrl = window.URL.createObjectURL(new Blob([res],
                        {type: `application/pdf`}));
                    const fname = name; // 下载文件的名字
                    const link = document.createElement('a');
                    link.href = this.pdfUrl;
                    link.setAttribute('download', fname);
                    document.body.appendChild(link);
                    link.click();
                })
            },
            showPdf(fileId) {
                if (fileId) {
                    let url = this.apiUrl + `/${fileId}/open`;
                    url = window.btoa(url);
                    window.open(this.pdfUrl + url);
                }
            },
            showEnforceObjDetail() {
                this.$router.push({
                    path: '/resource/detail',
                    query: {
                        id: this.objData.enforce_obj_id
                    }
                })
            },
            //查看被检查组织
            showOrg(id) {
                this.orgId = id;
                this.orgVisible = true;
                //this.$message.warning(id)
            },
            recentJobsDatas(enforce_obj_id) {
                getRecent(enforce_obj_id).then(res => {
                    if (res) {
                        this.total = res.total || 0
                        const list = res.data || []
                        list.map(item => {
                            item.start_time = formatDate(item.start_time, true)
                          item.status = this.parseJobResult(item);//item.enforce_result == 'PASS' ? '合格' : '不合格';
                          item.statusClass = item.status == '不检查' ? 'basic' : item.status == '合格' ? 'success' : 'danger';
                        })
                        list.sort((a, b) => a['start_time'] > b['start_time'] ? -1 : 1);
                        this.recentDatas = list
                    }
                    // this.loading = false
                })
            },
            async getJobDetail() {
                if (this.jobId) {
                    const list = await getPlaceTypes();
                    if (list && list.length > 0) {
                        this.placeType = list;
                    }
                    getOneJob(this.jobId).then(res => {
                        if (res) {
                            this.objData = res;
                            this.generateBasicInfo(res)
                            this.setNoCheckList(res)
                            this.job_status = res.job_status === 'ARCHIVED'
                            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
                            }
                            this.recentJobsDatas(res.enforce_obj_id);
                        }

                        getOneJobStatistics(this.jobId).then(result => {
                            if (result) {
                                let data = result;
                                this.staticDatas[0].value = this.ChangeHourMinutestr(data.checkTime);
                                this.staticDatas[1].value = this.ChangeHourMinutestr(data.commutingTime);
                            }
                        })
                    })
                }
            },
          setNoCheckList(res) {
            this.noCheckList = [
              {
                label: '不检查原因：',
                value: res.job_result_remark || '-',
              },
              {
                label: '不检查情况说明：',
                value: res.job_result_content || '-',
              },
              {
                label: '现场照片：',
                value: res.job_result_pictures ? res.job_result_pictures.split(',') : '',
                type: 'img'
              },
            ]
          },
            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 === 'ARCHIVED') {
                    return 'success'
                }
                return 'yellowFont'
            },
            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";
                }
            },
            orgInfo(res) {
                //  console.log(res)
                if (res.enforce_obj && res.enforce_obj_name && res.enforce_obj_id) {
                    let data = new Array();
                    data.push(res.enforce_obj_id);
                    data.push(res.enforce_obj_name);
                    return data;
                }
                return '-';
            },
            generateBasicInfo(res) {
                this.enforce_result = res.enforce_result;
                const mainUser = res.executors && res.executors.length > 0 ? res.executors[0] : null
                const secondUser = res.executors && res.executors.length > 1 ? res.executors[1] : null;
                if (res && res.job_result_pictures) {
                    this.imgUrls = res.job_result_pictures.split(",");
                    // this.imgUrls.push(1624)
                }
                // imgUrlsList
                // debugger;
                this.imgUrls.forEach(item => {
                    this.imgUrlsList.push(`${this.apiUrl}/${item}/open`);
                })
                this.basicInfo = [
                    [
                        {
                            label: '被检查单位：',
                            value: this.orgInfo(res),
                            type: 1
                        },
                        {
                            label: '单位地址：',
                            value: res.enforce_obj && res.enforce_obj.enforce_obj_address || '-',
                            type: 2
                        }
                    ],
                    [
                        {
                            label: '执法机构：',
                            value: res.enforce_org_name || '-'
                        },
                        {
                            label: '创建时间：',
                            value: formatDate(res.create_time) || '-'
                        }
                    ],
                    [
                        {
                            label: '检查类型：',
                            value: this.parseJobType(res.job_type) || '-'
                        },
                        {
                            label: '任务来源：',
                            value: this.parseJobSource(res.job_source) || '-'
                        }
                    ],
                    [
                        {
                            label: '任务名称：',
                            value: res.job_name || '-'
                        },
                        {
                            label: '检查期限：',
                            value: res.last_enforce_date || '-'
                        }
                    ],
                    [
                        {
                            label: '任务概要：',
                            value: res.job_desc || '-',
                            row: true
                        }
                    ],
                    [
                        {
                            label: '单位规模：',
                            value: res.enforce_obj && this.parseUnitSize(res.enforce_obj.enforce_obj_type) || '-'
                        },
                        {
                            label: '场所类型：',
                            value: res.enforce_obj && this.parsePlaceType(res.enforce_obj.place_type) || '-'
                        }
                    ],
                    [
                        {
                            label: '主检查员：',
                            value: mainUser && mainUser.user_name || '-'
                        },
                        {
                            label: '联系电话：',
                            value: mainUser && mainUser.phone || '-'
                        }
                    ],
                    [
                        {
                            label: '协检查员：',
                            value: secondUser && secondUser.user_name || '-'
                        },
                        {
                            label: '联系电话：',
                            value: secondUser && secondUser.phone || '-'
                        }
                    ],
                    [
                        {
                            label: '任务编号：',
                            value: res.job_no || '-'
                        },
                        {
                            label: '任务状态：',
                            value: this.parseJobStatus(res.job_status) || '-',
                            type: 4,
                            color: this.getJobStatusFontColor(res.job_status)
                        }
                    ],
                    // [
                    //     {
                    //         label: '检查文书：',
                    //         value: res.result_file_id ? res.result_file_name : '-',
                    //         type: 5,
                    //         show: res.result_file_id && res.result_file_id > 0
                    //     },
                    //     {
                    //         label: '检查结果：',
                    //         value: this.parseStatus(res.enforce_result) || '-',
                    //     }
                    // ]
                ]
              if (res.job_status == 'ARCHIVED' && res.enforce_result == 'OVERPASS') {
                this.enforce_result = 'OVERPASS'
                this.basicInfo.push({
                  label: '检查结果：',
                  value: '不检查'
                })
                this.basicInfo.push({
                  label: '',
                  value: ''
                })
                return
              }
                let tmp = [];
                if (res.result_file_id) {
                    let fileObj = {
                        label: '检查文书：',
                        value: res.result_file_name,
                        type: 5,
                        show: res.result_file_id && res.result_file_id > 0
                    };

                    if (res.job_status == 'ARCHIVED') {
                        tmp.push(fileObj);

                        const noPass = res.immediately_file_id > 0 || res.deadline_file_id > 0;
                        let jobRes = noPass ? '不合格' : '合格';
                        if (res.enforce_result) {
                            jobRes = this.parseStatus(res.enforce_result);
                        }
                        tmp.push({
                            label: '检查结果：',
                            value: jobRes,
                            type: 6,
                            class: res.enforce_result == 'PASS' ? 'result1' : 'result2',
                            lg: res.immediately_file_id,
                            xg: res.deadline_file_id
                        })
                    } else {
                        fileObj.row = true;
                        tmp.push(fileObj);
                    }
                  this.basicInfo.push(tmp)
                }
            },
            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))
                            }
                        })
                    })
                })
            }
        }
    }
</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>
