<template>
  <browser :component-loading="componentLoading"
           class="enterpriseInfo"
           ref="broTable"
           :api-config="apiConfig"
           :table-config="tableConfig"
           :permissions="permissions"
           :dialog-config="dialogConfig"
           :actions="actions"
           :default-query-params="queryParams"
           :custom-query="true"
           @custom-query="handleQuery"
           @update:query-params="queryParams = $event"
           @update:actions="actions = $event"
           @update:dialog-config="dialogConfig = $event">
    <template #queryPanel="{ queryParams: query }">
      <el-form ref="queryForm" :model="query" label-width="130px">
        <el-row class="query-condition">
          <el-col :span="6">
            <el-form-item label="企业名称" prop="unitName">
              <el-input v-model="query.unitName" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="query.checkStatus" placeholder="请选择" clearable>
                <el-option label="待审批" value="pending">待审批</el-option>
                <el-option label="通过" value="reviewing_done">通过</el-option>
                <el-option label="不通过" value="reviewing_failed">不通过</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="转交时间" prop="deliverTime">
              <el-date-picker
                  v-model="query.deliverTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  :default-time="[new Date(2000, 2, 1, 0, 0, 0),
                              new Date(2000, 2, 1, 23, 59, 59)]">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <el-table-column prop="enterprise.unitName" label="生产经营单位名称" min-width="200"/>
    <el-table-column prop="enterprise.unifiedSocialCode" label="社会统一信用代码" min-width="150"/>
    <el-table-column prop="enterprise.businessRating" label="企业分级" min-width="120">
      <template #default="{row}">
        <span>{{ DICTDISPLAYS.QYFJ_MAP[row.enterprise.businessRating] }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="enterprise.businessCategory" label="企业分类" min-width="120">
      <template #default="{row}">
        <span style="color: #428DFF" v-if="row.enterprise.businessCategory === '1'">{{
            DICTDISPLAYS.QYFL_MAP[row.enterprise.businessCategory]
          }}</span>
        <span style="color: #D4D43A" v-if="row.enterprise.businessCategory === '2'">{{
            DICTDISPLAYS.QYFL_MAP[row.enterprise.businessCategory]
          }}</span>
        <span style="color: #E6A23C" v-if="row.enterprise.businessCategory === '3'">{{
            DICTDISPLAYS.QYFL_MAP[row.enterprise.businessCategory]
          }}</span>
        <span style="color: #F56C6C" v-if="row.enterprise.businessCategory === '4'">{{
            DICTDISPLAYS.QYFL_MAP[row.enterprise.businessCategory]
          }}</span>
      </template>
    </el-table-column>
    <el-table-column label="转交时间" prop="deliverTime" min-width="120"></el-table-column>
    <el-table-column label="转交人" prop="deliverPerson" min-width="120"></el-table-column>
    <el-table-column label="状态" prop="checkStatusName" min-width="120"/>
    <template #tableControlColumn="{data: r}">
      <el-link v-if="r.data.row.checkStatus === 'pending'" type="primary" @click="handDistribution(r.data.row)"
               title="审批">审批
      </el-link>
      <el-link v-else type="primary" @click="reviewDetail(r.data.row)" title="审批">审批详情</el-link>
    </template>
    <template #dialogContent="{ dialogConfig: dc }" v-if="dialogConfig.data.checkStatus">
      <el-row>
        <el-col :span="24">
          <el-form-item label="检查企业:">{{ dc.data.enterprise.unitName }}</el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="转交部门:">{{ dc.data.deliverAgency.agencyName }}</el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="说明:">
            <el-input v-model="dc.data.description" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <MultipleFile :parameters="fileParameters"
                        :files-data="dc.data.evidence.filesData"/>
        </el-col>
      </el-row>
      <el-row>
        <el-divider content-position="left">审核信息</el-divider>
        <el-col :span="8" v-if="dialogConfig.mode === 'review'">
          <el-form-item label="审核结果" prop="checkStatus">
            <el-select v-model="checkStatus" placeholder="请选择" :disabled="dialogConfig.mode === 'detail'">
              <el-option label="通过" :value="'reviewing_done'">通过</el-option>
              <el-option label="不通过" :value="'reviewing_failed'">不通过</el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-else>
          <el-form-item label="审核结果" prop="checkStatus">
            <el-select v-model="dc.data.checkStatus" placeholder="请选择" :disabled="dialogConfig.mode === 'detail'">
              <el-option label="通过" :value="'reviewing_done'">通过</el-option>
              <el-option label="不通过" :value="'reviewing_failed'">不通过</el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="审核意见" prop="verifyDesc">
            <el-input v-model="dc.data.verifyDesc" :disabled="dialogConfig.mode === 'detail'"/>
          </el-form-item>
        </el-col>
      </el-row>
    </template>
    <template #dialog="{ dialogConfig: dc }" v-else>
      <el-dialog :open="dc.show" :title="dc.title" :type="dc.type" v-if="dc.show" :show-footer="false"
                 @update:open="dc.show = false" class="enterprise-dialog">
        <el-form ref="dialogFormRef" :label-width="dc.formLabelWidth" class="businesss-table-dialog-form"
                 label-position="left" :model="dc.data" :rules="dc.rules">
          <enterpriseInfo :dc="dc" @update:open="dc.show = false" @ok="handleDialogOk"/>
        </el-form>
      </el-dialog>
    </template>
  </browser>
</template>

<script setup>
import {reactive, toRefs, watch, computed, ref, onMounted} from 'vue'
import Browser from '@/components/Browser.vue'
import messagesApi from "@/api/lawenforcement/Message.js";
import {useUserStore} from '@/stores/modules/user'
import enterprises from "@/api/lawenforcement/Enterprise.js"
import {ElButton, ElMessage, ElTree} from 'element-plus'
import enterpriseInfo from "@pages/dtsjygl/enterpriseInfo.vue"
import {DEFAULT_ENTERPRISE_DETAIL, DICTDISPLAYS, DICTITEMS} from "@/utils/Constants.js"
import ElDialog from "@/components/ElDialog/index.vue"
import supervisions from "@/api/lawenforcement/SupervisionCheck.js"
import MultipleFile from "@pages/common/MultipleFile.vue";

const userStore = useUserStore()

const state = reactive({
  componentLoading: false,
  permissions: {
    query: true,
    add: false,
    modify: false,
    detail: true,
    delete: false,
    importFile: false,
    exportFile: false,
    exportSelectFile: false,
    downloadTemp: false,
  },
  tableConfig: {
    multipleSelect: false,
    hasControlColumn: true,
    controlWidth: '180',
    defaultSort: {
      prop: 'deliverTime',
      order: 'descending'
    }
  },
  apiConfig: {
    api: enterprises,
    modelId: 'enterpriseId'
  },
  dialogConfig: {
    type: 'fullscreen',
    show: false,
    mode: 'detail',
    loading: false,
    baseTitle: '企业分级分类',
    formLabelWidth: '90px',
    showFooter: false,
    data: {},
    actions: {handleDialogOk: handleDialogOk},
    rules: {
      checkStatus: [{required: true, message: '审批结果不能为空', trigger: 'blur'}],
      verifyDesc: [{required: true, message: '审批意见不能为空', trigger: 'blur'}],
    }
  },
  actions: {
    detail: handleDetail,
  },
  selection: [],
  queryParams: {},
  fileParameters: {
    title: '检查文件',
    mode: 'detail',
    tableTitle: '检查文件',
    headers: {'industry-category': 'PUB', 'Authorization': `Bearer ${userStore.token}`},
    url: '/api/uploads',
    autoUpload: true
  } // ,url: '/api/uploads', autoUpload: true
})

const {
  componentLoading,
  permissions,
  tableConfig,
  apiConfig,
  dialogConfig,
  actions,
  queryParams,
  selection,
  fileParameters
} = toRefs(state)
const checkStatus = ref('reviewing_done')

function handleQuery(query) {
  if (query)
    queryParams.value = query
  tableConfig.value.tableLoading = true
  if (queryParams.value.checkStatus === undefined) {
    queryParams.value.status = "pending,reviewing_done,reviewing_failed"
  }
  queryParams.value.checkType = '督导检查'
  queryParams.value.flag = 'sp'
  supervisions.query(queryParams.value).then(res => {
    if (res.success) {
      tableConfig.value.tableData = res
      tableConfig.value.tableLoading = false
    }
  })
}

const defaultValues = reactive(DEFAULT_ENTERPRISE_DETAIL)

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 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
  })
}

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

const dialogFormRef = ref(null)

function handleDialogOk(formRef) {
  if (dialogConfig.value.mode === 'review') {
    formRef.validate(valid => {
      if (valid) {
        let data = Object.assign({}, dialogConfig.value.data)
        data.checkStatus = checkStatus.value
        dialogConfig.value.loading = true
        supervisions.modify(data.checkId, data).then(res => {
          if (res.success) {
            ElMessage.success('审核成功')
            dialogConfig.value.loading = false
            dialogConfig.value.show = false
            handleQuery()
          }
        })

      }
    })
  }
}


function handDistribution(object) {
  dialogConfig.value.data = object
  dialogConfig.value.type = null
  dialogConfig.value.formLabelWidth = '120px'
  dialogConfig.value.title = '督导检查审批'
  dialogConfig.value.show = true
  dialogConfig.value.mode = 'review'

}

function reviewDetail(object) {
  dialogConfig.value.data = object
  dialogConfig.value.type = null
  dialogConfig.value.formLabelWidth = '120px'
  dialogConfig.value.title = '督导检查审批详情'
  dialogConfig.value.show = true
  dialogConfig.value.showFooter = false
  dialogConfig.value.mode = 'detail'
}

</script>

<style lang="scss">

.enterpriseInfo .el-dialog {
  margin-bottom: 0;
}

.enterprise-dialog {
  margin-bottom: 0 !important;
}

</style>
