<template>
  <div class="detail" v-loading="loading">
    <KVTable3 title="基本信息" :list="basicInfo" :enforce_result="enforce_result" :rightButton="rightButton" v-if="basicInfo && basicInfo.length">
      <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">
            <div @click="showSendMessageBox">
              <span class="point" :class="slot.row.color">{{ slot.row.value }}</span>
              <span v-if="txtInfo" class="blueFont point">[查看详情]</span>
            </div>
          </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 }}{{ slot.row.xg || slot.row.lg ? '，' : '' }}</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>
    </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="job_no" show-overflow-tooltip label="任务编号"/>
        <el-table-column prop="checkDate" show-overflow-tooltip label="检查时间" align="center"/>
        <el-table-column prop="enforce_org_name" show-overflow-tooltip label="检查机构"/>
        <el-table-column prop="executor_names" show-overflow-tooltip label="检查人员"/>
        <el-table-column prop="problem_sum" show-overflow-tooltip label="隐患数量" align="center"/>
        <el-table-column prop="correct_problem_num" show-overflow-tooltip label="已整改数量" align="center"/>
        <el-table-column prop="action" label="检查文书" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.result_file_id">
              <el-button type="text" size="small" @click="showPdf(scope.row.result_file_id)">查看</el-button>
            </template>
            <template v-else>-</template>
          </template>
        </el-table-column>
        <el-table-column prop="action" label="检查结果" align="center">
          <template slot-scope="scope">
            <span :class="scope.row.statusClass">{{scope.row.status}}</span>
          </template>
        </el-table-column>
      </el-table>
    </form-option>
    <form-option title="汇总情况" class="mt" v-if="objData && objData.enforce_result != 'OVERPASS'">
      <div class="statistic">
        <random-statistic-item v-for="(item, index) in staticDatas" :key="index" :data="item" @click.native="showStaticItem(index)"></random-statistic-item>
      </div>
    </form-option>
    <form-option title="检查详情" class="mt" v-if="objData && objData.enforce_result != 'OVERPASS'">
        <div v-if="objData && objData.check_type=='EASY'">
          <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">
                    <template v-if="objData.jobResultPictures && objData.jobResultPictures.length">
                      <el-col :span="3" v-for="(url, urlIndex) in objData.jobResultPictures" :key="urlIndex">
                        <el-image style="width: 100px; height: 100px" :src="url" 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>
        </div>
        <div v-else class="node" v-for="node in nodes" :key="node.id">
          <div class="header">
            <div class="node-name">{{ node.node_name }}</div>
            <el-tooltip class="item" effect="dark" :content="node.detail" placement="top">
              <div class="node-detail">{{ node.detail }}</div>
            </el-tooltip>
          </div>
          <el-table
            :data="node.items"
            border>
            <el-table-column type="index" align="center" label="序号" width="80"/>
            <el-table-column prop="enforce_obj_class" show-overflow-tooltip label="检查类型"/>
            <el-table-column prop="item_content" show-overflow-tooltip label="检查项"/>
            <el-table-column prop="checkResult" label="检查结果">
              <template slot-scope="scope">
                <span>{{scope.row.checkResult || (job_status ? '不涉及' : '')}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="enforce_method" label="现场照片">
                <template slot-scope="scope">
                      <template v-if="scope.row.recordImgs.length > 0">
                          <el-image
                              style="width: 80px; height: 80px"
                              :src="scope.row.recordImgs[0]"
                              :preview-src-list="scope.row.recordImgs">
                          </el-image>
                      </template>
                      <span v-else>{{(job_status ? '无' : '')}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="enforce_method" label="检查情况">
                <template slot-scope="scope">
                    <template v-if="scope.row.recordDesc.length > 0">
                        <div v-for="(desc, descInd) in scope.row.recordDesc" :key="descInd">{{descInd+1}}.{{desc}}</div>
                    </template>
                    <span v-else>{{(job_status ? '无' : '')}}</span>
                </template>
            </el-table-column>
          </el-table>
        </div>
    </form-option>

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

    <el-dialog :title="addressTitle" :visible.sync="addressMap">
      <div id="container"></div>
    </el-dialog>
    <el-dialog :title="txtInfo?'检查通知':'发送通知'" :visible.sync="showSendMessage">
      <send-message ref="sendMsg" :obj="objData" :msg="txtInfo" @cancel="cancelSendBox"></send-message>
    </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 FormOption from '@/component/FormOption.vue'
import RandomStatisticItem from './component/RandomStatisticItem.vue'
import SendMessage from './component/SendMessage.vue'
import ShowVideo from '@/component/ShowVideo'

// import moment from 'moment'

import { jobMixin } from '@/mixin/job'
import { resourceMixin } from '@/mixin/resource'
import { getPlaceTypes } from '@/api/resource'
import { formatDate, dateFormat, notEmpty, handleProblemImgs } from '@/utils/tool';
import { getOneJob, getOneJobStatistics, getJobMessages, getRecent } from '@/api/job'

export default {
  components: {
    KVTable,
    KVTable3,
    FormOption,
    RandomStatisticItem,
    SendMessage,
    ShowVideo
  },
  mixins: [jobMixin, resourceMixin],
  data () {
    return {
      loading: true,
      objData: null,
      showVideoDialog: false,
      basicInfo: [],
      enforce_result:'',
      rightButton: {},
      recentDatas: [],
      staticDatas: [
        {
          icon: 'el-icon-time',
          name: '检查耗时',
          value: '00:00'
        },
        {
          icon: 'el-icon-data-analysis',
          name: '通勤耗时',
          value: '00:00'
        },
        {
          icon: 'el-icon-pie-chart',
          name: '检查总数',
          value: '0项'
        },
        {
          icon: 'el-icon-document-delete',
          name: '不合格数',
          value: '0项'
        },
        {
          icon: 'el-icon-document-checked',
          name: '合格数',
          value: '0项'
        },
        {
          icon: 'el-icon-video-camera',
          name: '执法视频',
          value: '查看',
          point: true
        }
      ],
      nodes: [],
      addressMap: false,
      addressTitle: '',
      txtInfo: null,
      showSendMessage: false,
      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'
    },
  },
  mounted () {
    this.getJobDetail()
  },
  methods: {
        showEnfoceObjDetail() {
            this.$router.push({
                path: '/resource/detail',
                query: {
                    id: this.objData.enforce_obj_id
                }
            })
        },
        showStaticItem(index) {
          if (index === 5) {
            this.showVideoDialog = true;
          }
        },
        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}/${fileId}/open`);
                            }
                        });
                    }
                    if (notEmpty(obj.check_desc)) {
                        res.push(obj.check_desc);
                    }
                    // res.push('检查情况说明...');
                });
            }
            item.recordImgs = images;
            item.recordDesc = res;
        },
        async getJobDetail () {
            const list = await getPlaceTypes();
            if (list && list.length > 0) {
                this.placeType = list;
            }
            if (this.jobId) {
                getOneJob(this.jobId).then(res => {
                    if (res) {
                        let jobResultPictures = [];
                        if (res.job_result_pictures && res.job_result_pictures.length > 0) {
                            res.job_result_pictures.split(',').map(id => {
                                jobResultPictures.push(handleProblemImgs(id));
                            });
                        }
                        res.jobResultPictures = jobResultPictures;
                        this.objData = res;
                        this.job_status = res.job_status === 'ARCHIVED'
                        if (res.job_status == 'TODO') {
                          this.staticDatas[0].name = '检查预估耗时'
                        }
                        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 = '';
                                        if (item.check_result) {
                                          obj.checkResult = item.check_result === 1 ? '合格' : (item.check_result === 2 ? '不合格' : '不涉及');
                                        }
                                        if (item.item_type === '1') {
                                            obj.enforce_obj_class = item.enforce_obj_class || '其它'
                                            obj.item_content = obj.item_content || obj.item_name;
                                        }
                                        this.handleItemRecords(obj);
                                        items.push(obj)
                                    })
                                    node.items = items
                                }
                            })
                            this.nodes = res.check_nodes;
                            this.getSendMsg();
                        }
                        this.setNoCheckList(res)
                        // const end = moment().format('YYYY-MM');
                        // const start = moment().subtract(3, 'month').format('YYYY-MM');
                        getRecent(res.enforce_obj_id).then(result => {
                            if (result && result.data) {
                              const list = result.data;
                              list.map(item => {
                                item.checkDate = item.start_time ? dateFormat('YYYY-mm-dd HH:MM:SS', new Date(item.start_time)) : '';
                                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;
                            }
                        });
                    }

                    getOneJobStatistics(this.jobId).then(result => {
                        if (result) {
                            this.staticDatas[0].value = this.ChangeHourMinutestr(result.checkTime)
                            this.staticDatas[1].value = this.ChangeHourMinutestr(result.commutingTime)
                            this.staticDatas[3].value = result.checkFailedTotal ? `${result.checkFailedTotal}项` : '0项'
                            this.staticDatas[2].value = result.checkItemTotal ? `${result.checkItemTotal}项` : '0项'
                            this.staticDatas[4].value = result.checkOkTotal ? `${result.checkOkTotal}项` : '0项'
                        }
                    });

                    this.loading = false;
                })
            }
    },
    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'
        },
      ]
    },
    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 === 'ARCHIVED') {
        return 'success'
      }
      return 'yellowFont'
    },
    showSendMessageBox() {
        this.showSendMessage = true;
        if (this.$refs.sendMsg) {
            this.$refs.sendMsg.updateSendMsgInfo();
        }
    },
    cancelSendBox(res) {
        if (res) {
            this.getSendMsg();
            this.getJobDetail();
        }
        this.showSendMessage = false;
    },
    generateBasicInfo (res) {
      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.enforce_obj && res.enforce_obj.enforce_obj_name || '-',
          type: 1
        },
        {
          label: '单位地址：',
          value: res.enforce_obj && res.enforce_obj.enforce_obj_address || '-',
          type: 2
        },
        {
          label: '执法机构：',
          value: res.enforce_org_name || '-'
        },
        {
          label: '预约检查：',
          value: this.parseAppointmentStatus(res.appointment_status) || '发送短信',
          type: 3,
          color: this.getAppointmentFontColor(res.appointment_status)
        },
        {
          label: '创建时间：',
          value: formatDate(res.create_time) || '-'
        },
        {
          label: '检查期限：',
          value: res.last_enforce_date || '-'
        },
        {
          label: '检查类型：',
          value: this.parseJobType(res.job_type) || '-'
        },
        {
          label: '任务来源：',
          value: this.parseJobSource(res.job_source) || '-'
        },
        {
          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)
        }
        ];

      if (res.job_status == 'ARCHIVED' && res.enforce_result == 'OVERPASS') {
        this.enforce_result = 'OVERPASS'
        this.basicInfo.push({
          label: '检查结果：',
          value: '不检查'
        })
        this.basicInfo.push({
          label: '',
          value: ''
        })
        return
      }
        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') {
                this.basicInfo.push(fileObj);
                // if (!this.enforce_result) {
                //   this.enforce_result = (res.immediately_file_id > 0 || res.deadline_file_id > 0)?"NOT_PASS":"PASS";
                // }
                let noPass = res.enforce_result != 'PASS';
                if (res.immediately_file_id > 0 || res.deadline_file_id > 0) {
                    noPass = true;
                }
                this.enforce_result = noPass ? 'NO-PASS' : 'PASS';
                let jobRes = this.parseJobResult(res);
                this.basicInfo.push({
                        label: '检查结果：',
                        value: jobRes,
                        type: 6,
                        class: noPass ? 'result2' : 'result1',
                        lg: res.immediately_file_id,
                        xg: res.deadline_file_id
                })
            }
            else {
                fileObj.row = true;
                this.basicInfo.push(fileObj);
            }
        }
    },
    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 + `/${fileId}/open`;
            url = window.btoa(url);
            window.open(this.pdfUrl + url);
        }
    },
    getSendMsg() {
      getJobMessages(this.jobId, {
          page: 1,
          size: 1
      }).then(result => {
        const res = result.data
        if (res && res.length > 0) {
          this.txtInfo = res[0];
          this.basicInfo[3].value = '已发送';
          this.basicInfo[3].color = this.getAppointmentFontColor('success');
        }
      })
    },
    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>
@import '@/styles/variables.scss';
.point {
    cursor: pointer;
}
.result {
    position: relative;
    display: flex;
    align-items: center;
}
.result1 {
    position: absolute;
    color: #42D451;
    width: 80px;
    height: 80px;
    border-radius: 100%;
    transform: rotate(-45deg);
    font-size: 34px;
    border: 2px solid #42D451;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba($color: #42D451, $alpha: 0.1);
}
.result2 {
    position: absolute;
    bottom: -10px;
    left: 50px;
    width: 80px;
    height: 80px;
    border-radius: 100%;
    transform: rotate(-45deg);
    font-size: 24px;
    color: #FB2225;
    border: 2px solid #FB2225;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba($color: #fbc822, $alpha: 0.2);
}
.mt {
    margin-top: 20px;
    padding-bottom: 20px;
}

.statistic {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .statistic-item:not(:first-child) {
      margin-left: 14px;
    }
}

.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>
