<template>
  <browser class="browser-businesss-table"
           :component-loading="componentLoading"
           :api-config="apiConfig"
           :table-config="tableConfig"
           :permissions="permissions"
           :dialog-config="dialogConfig"
           :actions="actions"
           :customQuery="true"
           @custom-query="handleQuery"
           @update:dialog-config="dialogConfig = $event"
           @update:actions="actions = $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="执法机构" prop="agency">
              <agency-selector :lazyLoad="true" v-model="queryParams.agency"></agency-selector>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业名称" prop="unitName">
              <el-input v-model="queryParams.unitName" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="当前节点" prop="currentNodeCode">
              <el-select v-model="queryParams.currentNodeCode" 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="录入时间" prop="createTime">
              <el-date-picker v-model="queryParams.createTime"
                              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-col>
        </el-row>
      </el-form>
    </template>

    <el-table-column prop="enterprise.unitName" label="企业" min-width="300"/>
    <el-table-column prop="enterprise.unifiedSocialCode" label="统一信用代码" min-width="200"/>
    <el-table-column prop="agency.agencyName" label="执法机构" min-width="200"/>
    <el-table-column prop="currentNodeCode" label="当前节点" min-width="200">
      <template #default="scope">
        <span :class="['node-status', scope.row.currentNodeCode]">
          {{ scope.row.currentNode }}
        </span>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="录入时间" min-width="200"/>

    <template #dialog>
      <el-dialog class="business-dialog" v-model="dialogConfig.show" :show-close="false" :append-to-body="true" :top="'100px'">
        <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="110px" class="browser-businesss-table-dialog-form" :model="dialogConfig.data">
          <el-row>
            <el-divider content-position="left">基础信息</el-divider>
            <el-row>
              <el-col :span="12">
                <el-form-item label="企业名称" prop="unitName">
                  <el-input v-model="dialogConfig.data.enterprise.unitName" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="统一信用代码" prop="unifiedSocialCode">
                  <el-input v-model="dialogConfig.data.enterprise.unifiedSocialCode" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业地址" prop="detailedAddress">
                  <el-input v-model="dialogConfig.data.enterprise.detailedAddress" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="执法机构" prop="agencyName">
                  <el-input v-model="dialogConfig.data.agency.agencyName" readonly/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider content-position="left">检查记录</el-divider>
            <el-row class="width-100">
              <el-col :span="24" class="padding-bottom-10">
                <el-table :data="dialogConfig.data.enforceChecks" height="200" border>
                  <el-table-column header-align="center" align="center" prop="agencyName" label="执法机构" min-width="200"
                                   show-overflow-tooltip/>
                  <el-table-column header-align="center" align="center" prop="officerNames" label="执法人员"
                                   min-width="150"/>
                  <el-table-column header-align="center" align="center" prop="checkStatusMsg" label="检查状态"
                                   min-width="120"/>
                  <el-table-column header-align="center" align="center" prop="checkDate" label="检查日期" min-width="120"/>
                  <el-table-column header-align="center" align="center" prop="checkResultMsg" label="检查结果"
                                   min-width="200" show-overflow-tooltip/>
                  <el-table-column fixed="right" label="操作" width="100" align="center">
                    <template #default="{row}">
                      <el-link type="primary" title="检查明细" @click="handCheckDetail(row)">检查明细</el-link>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
            <el-row class="width-100">
              <el-col :span="24" class="padding-bottom-10">
                <el-table :data="dialogConfig.data.checkItems" height="300" border>
                  <el-table-column header-align="center" align="center" label="检查事项" prop="itemName" min-width="250"/>
                  <el-table-column header-align="center" align="center" label="执法依据" prop="enforcementBasis"
                                   min-width="250"/>
                  <el-table-column header-align="center" align="center" label="处罚依据" prop="punishmentBasis"
                                   min-width="250"/>
                </el-table>
              </el-col>
            </el-row>
          </el-row>
        </el-form>
      </el-dialog>

      <el-dialog class="business-dialog" v-model="dialogConfig1.show" :show-close="false" :append-to-body="true" :top="'100px'">
        <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">
          <el-divider content-position="left">检查明细</el-divider>
          <el-row class="width-100">
            <el-col :span="24" class="padding-bottom-10">
              <el-table :data="dialogConfig1.data.checkItems" height="200" border>
                <el-table-column header-align="center" align="left" label="检查事项" prop="itemName" min-width="350"/>
                <el-table-column header-align="center" align="center" label="检查结果" prop="eligibility" min-width="200">
                  <template #default="{row}">
                    <el-radio-group v-model="row.eligibility" :disabled="true">
                      <el-radio :value="1">合格</el-radio>
                      <el-radio :value="0">不合格</el-radio>
                      <el-radio :value="9">其他</el-radio>
                    </el-radio-group>
                    <el-input type="textarea" :rows="2" v-if="row.eligibility === 9" v-model="row.checkNote"/>
                  </template>
                </el-table-column>
                <el-table-column header-align="center" align="center" label="现场图" prop="xct" min-width="200">
                  <template #default="{row}">
                    <div class="pic-content">
                      <MultiplePicture :parameters="parameters" :formData="row" @on-pic-view="onPicView"/>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            <el-col :span="24">
              <MultipleFile :parameters="fileParameters" :files-data="dialogConfig1.data.filesData"/>
            </el-col>
          </el-row>
        </el-form>
        <PictureView ref="pictureViewRef"/>
      </el-dialog>
    </template>
  </browser>
</template>
<script setup>
import browser from '@/components/Browser.vue'
import AgencySelector from '@/components/AgencySelector.vue'
import MultiplePicture from '@pages/common/MultiplePicture.vue'
import MultipleFile from '@pages/common/MultipleFile.vue'
import PictureView from '@pages/common/PictureView.vue'
import {reactive, ref, toRefs} from 'vue'
import {useUserStore} from '@/stores/modules/user'
import enforcementInfo from '@/api/lawenforcement/EnforcementInfo'
import enforceChecks from '@/api/lawenforcement/EnforceChecks'
import {ElMessage} from 'element-plus'

const userStore = useUserStore()

const state = reactive({
  componentLoading: false,
  permissions: {
    query: true,
    add: false,
    modify: false,
    detail: true,
    delete: false,
    deleteAll: false,
    importFile: false,
    exportFile: false,
    exportSelectFile: false,
    downloadTemp: false
  },
  tableConfig: {
    multipleSelect: false,
    hasControlColumn: true,
    controlWidth: '100'
  },
  apiConfig: {
    api: enforcementInfo,
    api2: enforceChecks,
    modelId: 'enforcementId',
  },
  dialogConfig: {
    show: false,
    mode: 'detail',
    title: '综合执法管理',
    loading: false,
    formLabelWidth: '100',
    data: {
      enterprise: {},
      agency: {},
    },
    actions: {
      handleClose: handleClose
    },
  },
  dialogConfig1: {
    show: false,
    mode: 'detail',
    title: '检查明细详情',
    loading: false,
    data: {
      checkItems: [],
      filesData: [],
    },
    actions: {
      handleClose: handleClose1
    }
  },
  actions: {
    detail: handleDetail,
  },
  parameters: {
    mode: 'add',
    backPic: true
  },
  fileParameters: {
    title: '相关材料',
    mode: 'detail'
  },
  queryParams: {},
})

const {
  componentLoading,
  permissions,
  tableConfig,
  apiConfig,
  dialogConfig,
  dialogConfig1,
  actions,
  parameters,
  fileParameters,
  queryParams
} = toRefs(state)

const options = [
  {value: 'plan_approval', label: '方案待审批'},
  {value: 'plan_approval_failed', label: '方案审批未通过'},
  {value: 'plan_approved', label: '方案审批通过'},
  {value: 'inspecting', label: '检查中'},
  {value: 'inspect_done', label: '检查完成'},
  {value: 'inspect_summarize', label: '总结'},
  {value: 'filed', label: '已立案'},
  {value: 'investigating', label: '调查取证中'},
  {value: 'investigation_done', label: '调查取证完成'},
  {value: 'analyze_judge', label: '分析研判'},
  {value: 'reviewing_failed', label: '法治审核未通过'},
  {value: 'reviewing_done', label: '法治审核完成'},
  {value: 'brainstorm', label: '集体讨论'},
  {value: 'closed', label: '结案'},
  {value: 'done', label: '完成'},
]

// 分页查询

function handleQuery(queryParams) {
  queryParams.agencyCode = queryParams.agency?.agencyCode
  queryParams.sort = 'createTime'
  queryParams.dir  = 'desc'
  if (queryParams.createTime && queryParams.createTime.length === 2) {
    queryParams.startTime = queryParams.createTime[0]
    queryParams.endTime = queryParams.createTime[1]
  } else {
    queryParams.startTime = null
    queryParams.endTime = null
  }
  tableConfig.value.tableLoading = true
  apiConfig.value.api.query(queryParams).then(res => {
    tableConfig.value.tableLoading = false
    if (res.success) {
      tableConfig.value.tableData = res
    } else {
      ElMessage.error('执法信息查询失败')
    }
  })
}


// 详情信息
function handleDetail(row) {
  dialogConfig.value.show = true
  dialogConfig.value.mode = 'detail'
  dialogConfig.value.title = '执法信息详情'
  dialogConfig.value.loading = true
  findOne(row)
}

function findOne(row) {
  apiConfig.value.api.findOne(row.enforcementId).then(res => {
    dialogConfig.value.loading = false
    if (res.success) {
      const data = res.data
      // 处理机构信息
      if (!data.agency) data.agency = {}
      // 处理企业ID
      data.enterpriseIds = [data.enterpriseId].filter(Boolean)
      // 更新检查记录
      data.enforceChecks.forEach(item => {
        // 机构信息
        item.agencyName = data.agency.agencyName
        // 人员信息
        item.officerNames = item.officerList.map(item => item.officerName).join(', ')
      })
      // 处理检查项ID
      data.checkItemIds = data.checkItems.map(item => item.itemId)
      // 响应式更新
      dialogConfig.value.data = Object.assign({}, data)
    } else {
      ElMessage.error('执法信息详情查询失败')
    }
  })
}

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

// 检查明细信息
function handCheckDetail(row) {
  dialogConfig1.value.show = true
  dialogConfig.value.loading = true
  findCheckInfoById(row)
}

function findCheckInfoById(row) {
  apiConfig.value.api2.findOne(row.enforceCheckId).then(res => {
    dialogConfig.value.loading = false
    if (res.success) {
      let data = res.data
      dialogConfig1.value.data.checkItems = data.items
      dialogConfig1.value.data.filesData = []
      if (data.dzcls) {
        data.dzcls.forEach(item => dialogConfig1.value.data.filesData.push({id: item.materialsId, url: item.url, name: item.name, type: item.fileType, downloadUrl: item.url}))
      }
    } else {
      ElMessage.error('检查明细详情查询失败')
    }
  })
}

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

const pictureViewRef = ref()

function onPicView(url) {
  pictureViewRef.value.viewPicture(url)
}
</script>
<style lang="scss">
.pic-content {
  .el-upload-list__item-thumbnail, .el-upload-list__item-actions, .el-upload-list__item, .el-upload--picture-card {
    width: 64px !important;
    height: 64px !important;
  }
}
</style>
<style lang="scss" scoped>
.browser-businesss-table {
  .browser-businesss-table-dialog-form {
    padding: 10px 20px 10px 20px;
  }
}

.width-100 {
  width: 100%;
}

.padding-bottom-10 {
  padding-bottom: 10px;
}

.node-status {
  &.plan_approval { color: #409EFF; }
  &.plan_approval_failed { color: #F56C6C; }
  &.plan_approved { color: #67C23A; }
  &.inspecting { color: #E6A23C; }
  &.inspect_done { color: #00BFFF; }
  &.inspect_summarize { color: #9370DB; }
  &.filed { color: #FFA500; }
  &.investigating { color: #20B2AA; }
  &.investigation_done { color: #3CB371; }
  &.analyze_judge { color: #FF6347; }
  &.reviewing_failed { color: #FF4500; }
  &.reviewing_done { color: #4682B4; }
  &.brainstorm { color: #9932CC; }
  &.closed { color: #8FBC8F; }
  &.done { color: #696969;}
}
</style>
