<template>
  <browser :component-loading="componentLoading"
           class="enterpriseInfo"
           ref="broTable"
           :api-config="apiConfig"
           :table-config="tableConfig"
           :permissions="permissions"
           :dialog-config="dialogConfig"
           :actions="actions"
           :customQuery="true"
           @custom-query="handleQuery"
           @update:actions="actions = $event"
           @update:query-params="queryParams = $event"
           @update:dialog-config="dialogConfig = $event">

    <template #queryPanel="{ queryParams: queryParams }">
      <el-form ref="queryForm" :model="queryParams" label-width="80px">
        <el-row class="query-condition">
          <el-col :span="6">
            <el-form-item label="视频接入">
              <el-select v-model="queryParams.videoAccess" placeholder="请选择视频接入" clearable>
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="感知设备">
              <el-select v-model="queryParams.perceptionAccess" placeholder="请选择感知设备" clearable>
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="资料上报">
              <el-select v-model="queryParams.infoAccess" placeholder="请选择资料上报" clearable>
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="6">-->
<!--            <el-form-item label="许可信息">-->
<!--              <el-select v-model="queryParams.permitAccess" placeholder="请选择许可信息" clearable>-->
<!--                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"/>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
      </el-form>
    </template>

    <el-table-column prop="agency.agencyName" label="属地" min-width="250"/>
    <el-table-column prop="unitName" label="企业" min-width="350"/>
    <el-table-column prop="industryType" label="行业类型" min-width="200">
      <template #default="{row}">
        <el-span>{{ DICTDISPLAYS.HYLB_MAP[row.industryType] || row.industryType }}</el-span>
      </template>
    </el-table-column>
    <el-table-column prop="videoAccessMsg" label="视频接入" min-width="100"/>
    <el-table-column prop="perceptionAccessMsg" label="感知设备" min-width="100"/>
    <el-table-column prop="infoAccessMsg" label="资料上报" min-width="100"/>
    <el-table-column prop="permitAccessMsg" label="许可信息" min-width="100"/>

    <template #tableControlColumn="{ data: r }">
      <el-link type="primary" @click="handDistribution(r.data.row)" title="在线巡查">在线巡查</el-link>
    </template>

    <template #dialog>
      <el-dialog class="business-dialog" v-model="dialogConfig.show" :show-close="false" :append-to-body="true"
                 fullscreen>
        <template #header>
          <div class="cvi-dialog-header">
            <div class="cvi-dialog-header-title">
              <div class="dialog-line"></div>
              {{ dialogConfig.title }}
            </div>
            <i class="iconfont icon-zyyy_tcgb" @click="dialogConfig.actions.handleClose"></i>
          </div>
        </template>

        <el-form :label-width="dialogConfig.formLabelWidth" :model="dialogConfig.data" :rules="dialogConfig.rules">
          <enterpriseInfo :dc="dialogConfig"/>
        </el-form>
      </el-dialog>

      <el-dialog class="business-dialog" v-model="dialogConfig1.show" :show-close="false" :append-to-body="true"
                 :top="'0px'" width="1200px">
        <template #header>
          <div class="cvi-dialog-header">
            <div class="cvi-dialog-header-title">
              <div class="dialog-line"></div>
              {{ dialogConfig1.title }}
            </div>
            <i class="iconfont icon-zyyy_tcgb" @click="dialogConfig1.actions.handleClose"></i>
          </div>
        </template>

        <el-form label-width="100px" class="browser-businesss-table-dialog-form" :model="dialogConfig1.data"
                 :rules="dialogConfig1.rules">
          <el-divider content-position="left">企业基本信息</el-divider>
          <el-row>
            <el-col :span="8">
              <el-form-item label="属地" prop="orgCode">
                <el-input v-model="dialogConfig1.data.agency.agencyName" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业" prop="unitName">
                <el-input v-model="dialogConfig1.data.unitName" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="统一信用代码" prop="unifiedSocialCode">
                <el-input v-model="dialogConfig1.data.unifiedSocialCode" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营业状态" prop="businessStatus">
                <el-input v-model="DICTDISPLAYS.YYZT_MAP[dialogConfig1.data.businessStatus]" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="行业类型" prop="industryType">
                <el-input v-model="DICTDISPLAYS.HYLB_MAP[dialogConfig1.data.industryType]" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="详细地址" prop="detailedAddress">
                <el-input v-model="dialogConfig1.data.detailedAddress" readonly/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider content-position="left">视频设备</el-divider>
          <el-row>
            <BusinessTable ref="busiTable"
                           :config="spsbTableConfig"
                           :data-res="dialogConfig1.data.spsblist"
                           :permissions="spsbPermissions">
              <el-table-column align="center" header-align="center" prop="cameraName" label="设备名称"/>
              <el-table-column align="center" header-align="center" prop="parentCode" label="父组织编码"/>
              <el-table-column align="center" header-align="center" prop="cameraIndexCode" label="监控点唯一标识"/>

              <template #otherControlButtons="{ data: scope }">
                <el-link type="primary" @click="handleVideo(scope.row)" title="查看">查看</el-link>
              </template>
            </BusinessTable>
          </el-row>
          <el-divider content-position="left">预警信息</el-divider>
          <el-row v-if="dialogConfig1.show">
            <BusinessTable ref="busiTable"
                           v-loading="yjxxTableConfig.tableLoading"
                           :config="yjxxTableConfig"
                           :query-params="yjxxQueryParams"
                           :data-res="dialogConfig1.data.yjxxlist"
                           :permissions="yjxxPermissions"
                           @query-params="handleYjxxQueryParams">
              <el-table-column align="center" header-align="center" prop="cameraName" label="摄像头名称" min-width="150"/>
              <el-table-column align="center" header-align="center" prop="address" label="摄像头地址" min-width="150"/>
              <el-table-column align="center" header-align="center" prop="time" label="抓拍时间" min-width="150"/>
              <el-table-column align="center" header-align="center" prop="eventDesc" label="事件描述" min-width="350"/>

              <template #otherControlButtons="{ data: scope }">
                <el-link type="primary" @click="handleYjxxDetail(scope.row)" title="查看">查看</el-link>
              </template>
            </BusinessTable>
          </el-row>
          <el-divider content-position="left">感知设备</el-divider>
          <el-row>
            <BusinessTable ref="busiTable"
                           :config="gzsbTableConfig"
                           :data-res="dialogConfig1.data.gzsblist">
              <el-table-column align="center" header-align="center" prop="code" label="探测器编码" min-width="150"/>
              <el-table-column align="center" header-align="center" prop="recordHandleStatus" label="有无未处置的探测器报警记录"
                               min-width="150"/>
              <el-table-column align="center" header-align="center" prop="status" label="探测器状态" min-width="150"/>
              <el-table-column align="center" header-align="center" prop="subStatusName" label="探测器子状态名称"
                               min-width="150"/>
              <el-table-column align="center" header-align="center" prop="arrivalTime" label="数据到达时间" min-width="150"/>
              <el-table-column align="center" header-align="center" prop="value" label="实时值" min-width="150"/>
            </BusinessTable>
          </el-row>
          <el-divider content-position="left">自报自查</el-divider>
          <el-row v-if="dialogConfig1.show">
            <BusinessTable ref="busiTable"
                           v-loading="zczbTableConfig.tableLoading"
                           :config="zczbTableConfig"
                           :query-params="zczbQueryParams"
                           :data-res="dialogConfig1.data.zczblist"
                           @query-params="handleZczbQueryParams">
              <el-table-column align="center" header-align="center" prop="unitname" label="单位名称" min-width="150"/>
              <el-table-column align="center" header-align="center" prop="checkusername" label="检查人" min-width="150"/>
              <el-table-column align="center" header-align="center" prop="checktime" label="检查时间" min-width="150"/>
              <el-table-column align="center" header-align="center" prop="checkcontent" label="检查内容" min-width="350"/>
            </BusinessTable>
            <!--            @show-modify="mergeActions.modify"-->
            <!--            @show-detail="mergeActions.detail"-->
          </el-row>
<!--          <el-divider content-position="left">行政许可</el-divider>-->
<!--          <el-row>-->
<!--            <BusinessTable ref="busiTable"-->
<!--                           v-loading="zczbTableConfig.tableLoading"-->
<!--                           :config="zczbTableConfig"-->
<!--                           :query-params="zczbQueryParams"-->
<!--                           :data-res="dialogConfig1.data.zczblist"-->
<!--                           @query-params="handleZczbQueryParams">-->
<!--              <el-table-column align="center" header-align="center" prop="unitname" label="单位名称" min-width="150"/>-->
<!--              <el-table-column align="center" header-align="center" prop="checkusername" label="检查人" min-width="150"/>-->
<!--              <el-table-column align="center" header-align="center" prop="checktime" label="检查时间" min-width="150"/>-->
<!--              <el-table-column align="center" header-align="center" prop="checkcontent" label="检查内容" min-width="350"/>-->
<!--            </BusinessTable>-->
<!--                        @show-modify="mergeActions.modify"-->
<!--                        @show-detail="mergeActions.detail"-->
<!--          </el-row>-->
        </el-form>

        <template #footer>
          <div class="cvi-dialog-footer">
            <el-button @click="dialogConfig1.actions.handleClose">取消</el-button>
            <el-button type="primary" @click="dialogConfig1.actions.handleDialogOk(dialogConfig1.data)">完成</el-button>
            <el-button type="success" @click="dialogConfig1.actions.handleSubmitForApproval(dialogConfig1.data)"
                       title="报送审批">报送审批
            </el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog class="business-dialog" v-model="dialogConfig2.show" :show-close="false" :append-to-body="true"
                 :top="'60px'" width="1200px">
        <template #header>
          <div class="cvi-dialog-header">
            <div class="cvi-dialog-header-title">
              <div class="dialog-line"></div>
              {{ dialogConfig2.title }}
            </div>
            <i class="iconfont icon-zyyy_tcgb" @click="dialogConfig2.actions.handleClose"></i>
          </div>
        </template>

        <el-row style="padding: 20px">
          <el-col :span="14">
            <div id="camerasPlayer" style="width:100%;height: 100%"></div>
          </el-col>
          <el-col :span="10">
            <el-form ref="form" :model="videoData" label-width="140px">
              <el-form-item label="实时视频监控：">
                <el-button size='default' @click="realPlay(videoData.camera)">开始监控</el-button>
                <el-button size='default' @click="stopPlay(videoData.camera)">停止监控</el-button>
              </el-form-item>
              <el-form-item label="历史监控时间：">
                <el-date-picker size='default'
                                v-model="videoConfig.fallBackTime"
                                type="datetimerange"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                :default-time="[new Date(2000, 2, 1, 0, 0, 0),new Date(2000, 2, 1, 23, 59, 59)]"/>
              </el-form-item>
              <el-form-item label="历史监控回放：">
                <div>
                  <el-button size='default' @click="playbackStart(videoData.camera)">开始回放</el-button>
                  <el-button size='default' @click="stopPlay">停止回放</el-button>
                  <el-button size='default' @click="frameForward">单 帧</el-button>
                </div>
                <div>
                  <el-button size='default' @click="playbackFast" :disabled="videoConfig.single">快 放</el-button>
                  <el-button size='default' @click="playbackSlow" v-show="flowType === 'decoder'">慢 放</el-button>
                </div>
              </el-form-item>
              <el-form-item label="当前倍速：">
                <el-input size='default' readonly v-model="videoConfig.rate"></el-input>
              </el-form-item>
              <el-form-item label="声音：">
                <el-button size='default' @click="openSound">开 启</el-button>
                <el-button size='default' @click="closeSound">关 闭</el-button>
              </el-form-item>
              <el-form-item label="音量条：">
                <el-slider size='small' v-model="videoConfig.volume" @change="setVolume"
                           :disabled="videoConfig.muted"></el-slider>
              </el-form-item>
              <el-form-item label="抓图&录像：">
                <el-button size='default' @click="capture('JPEG')">抓取JPEG</el-button>
                <el-button size='default' @click="recordStart('MP4')">录制MP4</el-button>
                <el-button size='default' @click="recordStop">停止录制</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-dialog>

      <el-dialog class="business-dialog" v-model="dialogConfig3.show" :show-close="false" :append-to-body="true"
                 :top="'60px'" width="1200px">
        <template #header>
          <div class="cvi-dialog-header">
            <div class="cvi-dialog-header-title">
              <div class="dialog-line"></div>
              {{ dialogConfig3.title }}
            </div>
            <i class="iconfont icon-zyyy_tcgb" @click="dialogConfig3.actions.handleClose"></i>
          </div>
        </template>

        <el-form label-width="100px" class="browser-businesss-table-dialog-form" :model="dialogConfig3.data"
                 :rules="dialogConfig3.rules" ref="formRef">
          <el-col :span="24">
            <el-form-item label="巡查人" prop="createUserName">
              <el-input v-model="dialogConfig3.data.createUserName" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="巡查时间" prop="createTime">
              <el-input v-model="dialogConfig3.data.createTime" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="管辖机构" prop="agency">
              <agency-selector :lazyLoad="true" v-model="dialogConfig3.data.agency"></agency-selector>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="简述" prop="description">
              <el-input type="textarea" v-model="dialogConfig3.data.description"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件" prop="annex">
              <MultipleFile :parameters="fileParameters"
                            :files-data="dialogConfig3.data.annexs"
                            @on-change="onChange"
                            @on-remove="onRemove"/>
            </el-form-item>
          </el-col>
        </el-form>

        <template #footer>
          <div class="cvi-dialog-footer">
            <el-button @click="dialogConfig3.actions.handleClose">取消</el-button>
            <el-button type="primary" @click="dialogConfig3.actions.handleDialogOk">确定</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog class="business-dialog" v-model="dialogConfig4.show" :show-close="false" :append-to-body="true"
                 :top="'60px'" width="1200px">
        <template #header>
          <div class="cvi-dialog-header">
            <div class="cvi-dialog-header-title">
              <div class="dialog-line"></div>
              {{ dialogConfig4.title }}
            </div>
            <i class="iconfont icon-zyyy_tcgb" @click="dialogConfig4.actions.handleClose"></i>
          </div>
        </template>

        <el-form :model="dialogConfig4.data" label-width="100px" ref="formRef">
          <el-row>
            <el-col :span="12">
              <el-form-item label="事件描述" prop="eventDesc">
                <el-input v-model="dialogConfig4.data.eventDesc" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="摄像头名称" prop="cameraName">
                <el-input v-model="dialogConfig4.data.cameraName" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="摄像头地址" prop="address">
                <el-input v-model="dialogConfig4.data.address" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="摄像头国标码" prop="internationalCode">
                <el-input v-model="dialogConfig4.data.internationalCode" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经度" prop="lat">
                <el-input v-model="dialogConfig4.data.lat" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="纬度" prop="lng">
                <el-input v-model="dialogConfig4.data.lng" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="街道" prop="street">
                <el-input v-model="dialogConfig4.data.street" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="置信度" prop="confidence">
                <el-input v-model="dialogConfig4.data.confidence" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="抓拍时间" prop="time">
                <el-input v-model="dialogConfig4.data.time" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12"></el-col>
            <el-col :span="12">
              <el-form-item label="抓拍图片" prop="imageUrl">
                <el-image
                    style="width: 300px; height: 200px"
                    :src="dialogConfig4.data.imageUrl"
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-src-list="[dialogConfig4.data.imageUrl]"
                    show-progress
                    :initial-index="4"
                    fit="cover"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="dialogConfig4.data.videoUrl !== null">
              <el-form-item label="前后10s视频" prop="videoUrl">
                <video width="300" height="200" controls>
                  <source :src="dialogConfig4.data.videoUrl" type="video/mp4">
                </video>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
    </template>
  </browser>
</template>

<script setup>
import {reactive, toRefs, computed, ref, nextTick} from 'vue'
import {useUserStore} from '@/stores/modules/user'
import enterprises from '@/api/lawenforcement/Enterprise'
import hikVision from '@/api/lawenforcement/HikVision'
import onlinePatrol from '@/api/lawenforcement/OnlinePatrol'
import {DEFAULT_ENTERPRISE_DETAIL, DICTDISPLAYS, DICTITEMS} from '@/utils/Constants.js'
import {AREA_DICT} from '@/utils/bigdict.js'
import {ElMessage} from 'element-plus'
import moment from 'moment'
import BusinessTable from '@/components/BusinessTable.vue'
import DictSelector from '@/components/DictSelector.vue'
import enterpriseInfo from '@pages/dtsjygl/enterpriseInfo.vue'
import Browser from '@/components/Browser.vue'
import AgencySelector from '@/components/AgencySelector.vue'
import MultipleFile from '@pages/common/MultipleFile.vue'
import axios from 'axios'

let userInfo
useUserStore().getUserInfo().then(data => userInfo = data)

const state = reactive({
  queryParams: {},
  componentLoading: false,
  permissions: {
    query: true,
    add: false,
    modify: false,
    detail: true,
    delete: false,
    importFile: false,
    exportFile: false,
    exportSelectFile: false,
    downloadTemp: false,
  },
  tableConfig: {
    hasControlColumn: true,
    controlWidth: '150',
    multipleSelect: false,
    defaultSort: {
      prop: 'dynamicRiskLevel',
      order: 'descending'
    }
  },
  apiConfig: {
    api: enterprises,
    api2: hikVision,
    api3: onlinePatrol,
    modelId: 'enterpriseId'
  },
  dialogConfig: {
    title: '企业详情',
    show: false,
    mode: 'detail',
    loading: false,
    formLabelWidth: '90px',
    rules: {
      industryType: [{required: true, message: '监管行业不能为空', trigger: 'blur'}],
      unitName: [{required: true, message: '生产经营单位名称不能为空', trigger: 'blur'}],
      shortName: [{required: true, message: '单位简称不能为空', trigger: 'blur'}],
      unifiedSocialCode: [{required: true, message: '社会统一信用代码不能为空', trigger: 'blur'}],
      businessStatus: [{required: true, message: '营业状态不能为空', trigger: 'blur'}],
      orgCode: [{required: false, message: '所属机构不能为空', trigger: 'blur'}],
      legalRepresentative: [{required: true, message: '法定代表人（经营者）姓名不能为空', trigger: 'blur'}],
      contactPhone: [{required: true, message: '联系电话不能为空', trigger: 'blur'}],
      agency: [{required: true, message: '属地不能为空', trigger: 'blur'}],
      legalPhone: [{required: true, message: '联系电话不能为空', trigger: 'blur'}],
      legalDuty: [{required: true, message: '法定代表人（经营者）职位不能为空', trigger: 'blur'}],
      regulatedIndustry: [{required: true, message: '国民经济行业分类不能为空', trigger: 'blur'}],
      affiliation: [{required: true, message: '行政隶属关系不能为空', trigger: 'blur'}],
      oilExtract: [{required: true, message: '是否石油开采不能为空', trigger: 'blur'}],
      safetyFocus: [{required: true, message: '列入安全生产监管重点企业不能为空', trigger: 'blur'}],
      largeScale: [{required: true, message: '规模以上生产经营单位不能为空', trigger: 'blur'}],
      safetyLic: [{required: true, message: '企业是否有安全生产许可证不能为空', trigger: 'blur'}],
      opScope: [{required: true, message: '主营业务不能为空', trigger: 'blur'}],
      areaComb: [{required: true, message: '注册地址不能为空', trigger: 'blur'}],
      detailedAddress: [{required: true, message: '注册详细地址不能为空', trigger: 'blur'}],
      opLocAreaComb: [{required: true, message: '经营地址不能为空', trigger: 'blur'}],
      opLocAddress: [{required: true, message: '经营详细地址不能为空', trigger: 'blur'}],
      dynamicRiskLevel: [{required: true, message: '动态风险等级不能为空', trigger: 'blur'}],
      isScaleEnterprise: [{required: true, message: '规模以上生产经营单位不能为空', trigger: 'blur'}]
    },
    data: {},
    actions: {
      handleClose: handleClose,
    }
  },
  dialogConfig1: {
    show: false,
    mode: 'add',
    title: '在线巡查',
    loading: false,
    data: {},
    actions: {
      handleClose: handleClose1,
      handleDialogOk: handleDialog1Ok,
      handleSubmitForApproval: handleSubmitForApproval,
    },
  },
  dialogConfig2: {
    show: false,
    mode: 'detail',
    title: '视频监控',
    loading: false,
    data: {},
    actions: {
      handleClose: handleClose2,
    },
  },
  dialogConfig3: {
    show: false,
    mode: 'add',
    title: '报送审批',
    loading: false,
    data: {
      annexs: []
    },
    actions: {
      handleClose: handleClose3,
      handleDialogOk: handleDialog3Ok,
    },
    rules: {
      createUserName: [{required: true, message: '录入人不能为空', trigger: 'blur'}],
      createTime: [{required: true, message: '录入时间不能为空', trigger: 'blur'}],
      agency: [{required: true, message: '管辖机构不能为空', trigger: 'blur'}],
      description: [{required: true, message: '简述不能为空', trigger: 'blur'}],
      // annex: [{required: true, message: '附件不能为空', trigger: 'change'}],
    },
  },
  dialogConfig4: {
    title: '监控预警详情',
    show: false,
    mode: 'detail',
    loading: false,
    data: {},
    actions: {
      handleClose: handleClose4,
    }
  },
  actions: {
    detail: handleDetail
  },
  videoData: {
    camera: {}
  },
  spsbTableConfig: {
    hasControlColumn: true,
    controlWidth: '80',
    multipleSelect: false,
    usePage: false,
  },
  spsbPermissions: {
    detail: false
  },
  gzsbTableConfig: {
    hasControlColumn: false,
    controlWidth: '80',
    multipleSelect: false,
    usePage: false,
  },
  yjxxQueryParams: {},
  yjxxTableConfig: {
    hasControlColumn: true,
    controlWidth: '80',
    multipleSelect: false,
    tableLoading: false,
    pageSizes: [10, 20, 50, 100],
    pagerLayout: '->, slot, prev, pager, next',
  },
  yjxxPermissions: {
    detail: false
  },
  zczbQueryParams: {},
  zczbTableConfig: {
    hasControlColumn: false,
    controlWidth: '80',
    multipleSelect: false,
    tableLoading: false,
    pageSizes: [10, 20, 50, 100],
    pagerLayout: '->, slot, prev, pager, next',
  },
})

const {
  queryParams,
  componentLoading,
  permissions,
  tableConfig,
  apiConfig,
  dialogConfig,
  dialogConfig1,
  dialogConfig2,
  dialogConfig3,
  dialogConfig4,
  actions,
  videoData,
  spsbPermissions,
  spsbTableConfig,
  yjxxQueryParams,
  yjxxTableConfig,
  yjxxPermissions,
  gzsbTableConfig,
  zczbQueryParams,
  zczbTableConfig,
} = toRefs(state)

const options = [{value: '1', label: '是'}, {value: '0', label: '否'}]

// 分页查询
function handleQuery(queryParams) {
  tableConfig.value.tableLoading = true
  apiConfig.value.api.queryInsStart(queryParams).then(res => {
    tableConfig.value.tableLoading = false
    if (res.success) {
      tableConfig.value.tableData = res
    } else {
      ElMessage.error('执法信息查询失败')
    }
  })
}


// 详情查询
const defaultValues = reactive(DEFAULT_ENTERPRISE_DETAIL)

const districts = computed(() => {
  if (!queryParams.value.opLocCity) return []
  const city = cities.value.find(c => c.value === queryParams.value.opLocCity)
  return city?.children || []
})

const cities = computed(() => {
  if (!queryParams.value.opLocProvince) return []
  const province = AREA_DICT.find(p => p.value === queryParams.value.opLocProvince)
  return province?.children || []
})

async function handleDetail(row) {
  dialogConfig.value.show = true
  dialogConfig.value.mode = 'detail'
  dialogConfig.value.title = '详情企业信息'
  findOne(row)
}

function findOne(row) {
  dialogConfig.value.loading = true
  let defaultVals = {
    //安全基础管理信息
    productionManageInfoExp: {productionManageSystems: [{systemName: '', systemCompileDate: ''}], productionManagePlans: [{planName: '', planCompileDate: '', planType: ''}]},
    //生产设备设施及公用辅助用房
    productionEquipmentExp: {productionFacilities: [{equipName: '', equipType: '', commissioningDate: ''}], auxiliaryBuildings: [{auxiliaryName: '', floorArea: '', commissioningDate: ''}]},
    //煤行业扩展信息
    coalIndustryExpansion: {},
    //非煤行业扩展信息
    nocoalIndustryExpansion: {},
    //危化行业扩展信息
    dangerFeatureInfo: {majorDangerInfos: {}, majorDangerCraftInfos: {}, dangerInfos: {}},
    //烟花爆竹行业扩展信息
    fireworksAddInfo: {},
    //工贸行业扩展信息
    industryExpandInfos: {}
  }
  dialogConfig.value.data = Object.assign({}, defaultVals)
  apiConfig.value.api.findOne(row[apiConfig.value.modelId]).then(res => {
    if (res.success) {
      const data = res.data || {}
      // 调用字段解析函数
      const fieldsToDeserialize = Object.keys(defaultVals)
      deserializeFields(data, fieldsToDeserialize)
      // 调用默认值设置函数
      Object.keys(defaultVals).forEach(key => {
        if (!data[key]) {
          data[key] = defaultVals[key]
        }
      })
      data.regulatedIndustry = data.regulatedIndustry ? data.regulatedIndustry.split("/") : []
      data.areaComb = data.areaComb ? data.areaComb.split("/") : []
      data.opLocAreaComb = data.opLocAreaComb ? data.opLocAreaComb.split("/") : []
      dialogConfig.value.data = Object.assign({}, data)
    }
    dialogConfig.value.loading = false
  })
}

function deserializeFields(data, fields) {
  fields.forEach(field => {
    if (data[field]) {
      try {
        data[field] = JSON.parse(data[field])
      } catch (e) {
        console.error(`Failed to parse ${field}:`, e)
      }
    }
  })
}

function handleClose() {
  dialogConfig.value.show = false
}

//-----------------------在线巡查-----------------------

function handDistribution(row) {
  dialogConfig1.value.show = true
  dialogConfig1.value.mode = 'add'
  dialogConfig1.value.title = '在线巡查'
  dialogConfig1.value.loading = false
  dialogConfig1.value.formLabelWidth = '200px'
  row.spsblist = {}
  row.gzsblist = {}
  row.yjxxlist = {}
  row.zczblist = {}
  dialogConfig1.value.data = row
  findRegionsCameras(row)
  handleYjxx(row)
  handleGzsb(row)
  handleSelfInsAndSelfReportInfo(row)
}

function handleClose1() {
  dialogConfig1.value.show = false
}

function handleDialog1Ok(row) {
  let params = new FormData()
  params.append('enterpriseId', row.enterpriseId)
  params.append('agencyId', row.agency.agencyId)
  params.append('isNormal', '0')
  params.append('description', '在线巡查无异常')
  params.append('createUserId', userInfo.yhwybs)
  params.append('createUserName', userInfo.xm)
  params.append('createTime', moment().format('YYYY-MM-DD HH:mm:ss'))
  dialogConfig.value.loading = true
  let _event = actions.value
  apiConfig.value.api3.addOnlinePatrolAndFileData(params).then(res => {
    if (res.success) {
      dialogConfig.value.loading = false
      dialogConfig1.value.show = false
      ElMessage.success('操作成功')
      _event.query()
    } else {
      dialogConfig.value.loading = false
      throw new Error('操作失败')
    }
  })
}

//-----------------------视频相关信息--------------------
function findRegionsCameras(row) {
  let qyxx = JSON.parse(JSON.stringify(row))
  let params = {
    uscc: qyxx.unifiedSocialCode,
  }
  apiConfig.value.api.camera(params).then(res => {
    if (res.code === 0) {
      dialogConfig1.value.data.spsblist = {
        "code": 0,
        "success": true,
        "data": res.data
      }
    }
  })
}

//-----------------------预警信息-----------------------
function handleYjxx(row) {
  yjxxQueryParams.value.unifiedSocialCode = row.unifiedSocialCode
  yjxxQueryParams.value.pageSize = 10
  yjxxQueryParams.value.pagesize = 10
  yjxxQueryParams.value.page = 1
  // findYjxx()
}

function handleYjxxQueryParams(val) {
  Object.assign(yjxxQueryParams.value, val)
  findYjxx()
}

function findYjxx() {
  apiConfig.value.api.warn(yjxxQueryParams.value).then(res => {
    if (res.code === 0) {
      dialogConfig1.value.data.yjxxlist = res
      console.log(dialogConfig1.value.data.yjxxlist)
    }
  })
}

function handleYjxxDetail(val) {
  dialogConfig4.value.show = true
  dialogConfig4.value.data = Object.assign({}, val)
}

function handleClose4() {
  dialogConfig4.value.show = false
}

//-----------------------感知设备-----------------------
function handleGzsb(row) {
  findGzsb(row)
}

function findGzsb(row) {
  axios.get('/public/authenticated/monitor/unit/pulling/prober-status', {
    params: {
      socialCode: row.unifiedSocialCode
    }
  }).then(res => {
    if (res.data.code === 200) {
      dialogConfig1.value.data.gzsblist = {
        "code": 0,
        "success": true,
        "data": res.data.data
      }
    }
  })
}

//-----------------------自报自查------------------------
function handleSelfInsAndSelfReportInfo(row) {
  zczbQueryParams.value.unifiedSocialCode = row.unifiedSocialCode
  zczbQueryParams.value.pageSize = 10
  zczbQueryParams.value.pagesize = 10
  zczbQueryParams.value.page = 1
  //findSelfInsAndSelfReportInfo()
}

function handleZczbQueryParams(val) {
  Object.assign(zczbQueryParams.value, val)
  findSelfInsAndSelfReportInfo()
}

function findSelfInsAndSelfReportInfo() {
  apiConfig.value.api.selfInsAndSelfReport(zczbQueryParams.value).then(res => {
    if (res.code === 0) {
      let data = JSON.parse(res.data)
      if (data.code === '200') {
        let currentPage = 1
        if (data.data.totalCount > data.data.limit) {
          let result = data.data.offset / data.data.limit;
          if (result % 1 !== 0) { // 检查是否有小数部分
            currentPage = Math.ceil(result)
          }
        }
        let res = {
          "code": 0,
          "success": true,
          "data": data.data.list,
          "total": Number(data.data.totalCount),
          "page": currentPage,
          "limit": data.data.limit,
          "totalPages": data.data.totalPage,
          "relation": "eq"
        }
        dialogConfig1.value.data.zczblist = res
      }
    }
  })
}

//-----------------------视频相关信息---------------------
function handleVideo(row) {
  dialogConfig2.value.show = true
  dialogConfig2.value.mode = 'detail'
  dialogConfig2.value.title = '视频监控'
  dialogConfig2.value.loading = false
  dialogConfig2.value.data = {}
  videoData.value.camera = row
  nextTick(() => createPlayer())
}

function handleClose2() {
  dialogConfig2.value.show = false
}

//-----------------------海康视频监控-----------------------
// 创建播放器实例
let videoConfig = reactive({fallBackTime: [], single: false, rate: 1, volume: 50, muted: true})
let player

function createPlayer() {
  player = new window.JSPlugin({szId: 'camerasPlayer', szBasePath: '/js'})
  window.addEventListener('resize', () => player.JS_Resize())
}

let videoFlowType = !!window.MediaSource ? 'mse' : 'decoder'
let flowType = ref(videoFlowType)
let token = ''
function realPlay(data) {
  let params = {
    cameraIndexCode: data.cameraIndexCode,
    streamType: 0,
    protocol: 'wss',
    transMode: 1,
  }
  apiConfig.value.api2.getCamerasPreview(params).then(res => {
    if (res.code === 0) {
      let data = JSON.parse(res.data)
      console.log("播放流信息")
      console.log(data)
      if (data === null) return
      if (data.code === '0') {
        videoData.value.realplay = data.data.url
        let playURL = videoData.value.realplay
        let index = player.currentWindowIndex
        let playMode = videoFlowType === 'mse' ? 0 : 1
        player.JS_Play(playURL, {playURL, playMode, keepDecoder:0, token}, index).then(
            () => {
              videoConfig.single = true
              console.log('realPlay success')
            },
            e => {
              console.error(e)
            }
        )
      }
    }
  })
}

function stopPlay() {
  player.JS_Stop().then(
      () => {
        videoConfig.rate = 0
      },
      e => {
        console.error(e)
      }
  )
}

function playbackStart(data) {
  if (videoConfig.fallBackTime === null || videoConfig.fallBackTime.length !== 2) {
    ElMessage.error('请选择回放时间')
    return
  }
  let params = {
    cameraIndexCode: data.cameraIndexCode,
    protocol: 'wss',
    transMode: 1,
    fallBackTime: videoConfig.fallBackTime
  }
  apiConfig.value.api2.getCamerasPlayback(params).then(res => {
    if (res.code === 0) {
      let data = JSON.parse(res.data)
      console.log("回放流信息")
      console.log(data)
      if (data === null) return
      if (data.code === '0') {
        videoData.value.playback = data.data.url
        let playURL = videoData.value.playback
        let index = player.currentWindowIndex
        let playMode = videoFlowType === 'mse' ? 0 : 1
        // let startTime = data.data.list[0].beginTime
        // let endTime = data.data.list[0].endTime
        let s = videoConfig.fallBackTime[0].split(' ')
        let e = videoConfig.fallBackTime[1].split(' ')
        let startTime = s[0] + 'T' + s[1] + 'Z'
        let endTime = e[0] + 'T' + e[1] + 'Z'
        player.JS_Play(playURL, {playURL, playMode, keepDecoder:0, token}, index, startTime, endTime).then(
            () => {
              videoConfig.single = false
              videoConfig.rate = 1
              console.log('playback success')
            },
            e => {
              console.error(e)
            }
        )
      }
    }
  })
}

function playbackFast() {
  player.JS_Fast().then(
      rate => {
        videoConfig.rate = rate
      },
      e => {
        console.error(e)
      }
  )
}

function playbackSlow() {
  player.JS_Slow().then(
      rate => {
        videoConfig.rate = rate
      },
      e => {
        console.error(e)
      }
  )
}

function frameForward() {
  player.JS_FrameForward(player.currentWindowIndex).then(
      () => {
        videoConfig.rate = 1
      },
      e => {
        ElMessage.warning(videoFlowType + '模式暂不支持单帧播放！')
        console.error(e)
      }
  )
}

function openSound() {
  player.JS_OpenSound().then(
      () => {
        videoConfig.muted = false
      },
      e => {
        console.error(e)
      }
  )
}

function closeSound() {
  player.JS_CloseSound().then(
      () => {
        videoConfig.muted = false
      },
      e => {
        console.error(e)
      }
  )
}

function setVolume(value) {
  let index = player.currentWindowIndex
  player.JS_SetVolume(index, value).then(
      () => {
        console.log('setVolume success', value)
      },
      e => {
        console.error(e)
      }
  )
}

function capture(imageType) {
  let index = player.currentWindowIndex
  player.JS_CapturePicture(index, 'img', imageType).then(
      () => {
        console.log('capture success', imageType)
      },
      e => {
        console.error(e)
      }
  )
}

function recordStart() {
  let index = player.currentWindowIndex
  let fileName = `${moment().format('YYYYMMDDHHmm')}.mp4`
  let typeCode = 5
  player.JS_StartSaveEx(index, fileName, typeCode).then(
      () => {
        console.log('record start ...')
      },
      e => {
        console.error(e)
      }
  )
}

function recordStop() {
  let index = player.currentWindowIndex
  player.JS_StopSave(index).then(
      () => {
        console.log('record stoped, saving ...')
      },
      e => {
        console.error(e)
      }
  )
}

//-----------------------报送审批-----------------------
function handleSubmitForApproval(row) {
  dialogConfig3.value.show = true
  dialogConfig3.value.mode = 'add'
  dialogConfig3.value.title = '报送审批'
  dialogConfig3.value.loading = false
  dialogConfig3.value.formLabelWidth = '200px'
  // 材料信息
  row.annexs = []
  // 录入人
  row.createUserId = userInfo.yhwybs
  row.createUserName = userInfo.xm
  // 录入时间
  row.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
  dialogConfig3.value.data = row
}

// 文件组件上传成功回调
function onChange(data) {
  let tablezjcl = {
    uid: data.uid,
    name: data.name,
    type: data.name.split('.')[1],
    file: data.raw
  }
  dialogConfig3.value.data.annexs.push(tablezjcl)
}

// 文件组件删除文件回调
function onRemove(fileList, id) {
  dialogConfig3.value.data.annexs = fileList
}

const formRef = ref()

function handleDialog3Ok() {
  if (dialogConfig3.value.data.annexs.length <= 0) {
    ElMessage.error('附件不能为空')
    return
  }
  let _event = actions.value
  let params = new FormData()
  params.append('enterpriseId', dialogConfig3.value.data.enterpriseId)
  params.append('agencyId', dialogConfig3.value.data.agency.agencyId)
  params.append('isNormal', '1')
  params.append('description', dialogConfig3.value.data.description)
  params.append('createUserId', dialogConfig3.value.data.createUserId)
  params.append('createUserName', dialogConfig3.value.data.createUserName)
  params.append('createTime', dialogConfig3.value.data.createTime)
  dialogConfig3.value.data.annexs.forEach(item => params.append('files', item.file))
  formRef.value.validate(valid => {
    if (valid) {
      dialogConfig.value.loading = true
      apiConfig.value.api3.addOnlinePatrolAndFileData(params).then(res => {
        if (res.success) {
          dialogConfig.value.loading = false
          dialogConfig3.value.show = false
          dialogConfig1.value.show = false
          ElMessage.success('操作成功')
          _event.query()
        } else {
          dialogConfig.value.loading = false
          throw new Error('操作失败')
        }
      })
    }
  })
}

function handleClose3() {
  dialogConfig3.value.show = false
}

</script>

<style lang="scss">
.el-dialog {
  margin-bottom: 0;
  border: 0.0625rem solid rgba(255, 255, 255, 1);
  border-radius: 1rem !important;
}

.el-dialog__body {
  height: unset !important;
}
</style>
