<template>
  <browser :component-loading="componentLoading"
           class="enterpriseInfo"
           style="height: 600px;"
           :api-config="apiConfig"
           :table-config="tableConfig"
           :permissions="permissions"
           :dialog-config="dialogConfig"
           :actions="actions"
           :customQuery="true"
           @custom-query="customQuery"
           @update:query-params="queryParams = $event"
           @update:actions="actions = $event"
           @update:dialog-config="dialogConfig = $event">
    <template #queryPanel="{ queryParams: queryParams }">
      <el-form ref="queryForm" :model="queryParams" label-width="126px">
        <el-row class="query-condition">
          <el-col :span="8">
            <el-form-item label="属地" prop="agency">
              <agency-selector :lazyLoad="true" v-model="queryParams.agency"></agency-selector>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="企业名称" prop="unitName">
              <el-input v-model="queryParams.unitName" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="社会统一信用代码" prop="unifiedSocialCode">
              <el-input v-model="queryParams.unifiedSocialCode" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="企业分类" prop="businessCategory">
              <el-select v-model="queryParams.businessCategory" placeholder="请选择" clearable><el-option v-for="item in DICTITEMS.QYFL_OPTIONS" :key="item.value" :label="item.label" :value="item.value"></el-option></el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="企业详址" prop="detailedAddress">
              <el-input v-model="queryParams.detailedAddress" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <el-table-column prop="industryType" label="监管行业" min-width="240" v-if="tag === 2">
      <template #default="{row}">
        <el-span>{{ DICTDISPLAYS.HYLB_MAP[row.industryType] || row.industryType }}</el-span>
      </template>
    </el-table-column>
    <el-table-column prop="unitName" label="生产经营单位名称" min-width="350"/>
    <el-table-column prop="unifiedSocialCode" label="社会统一信用代码" min-width="220"/>
    <el-table-column prop="detailedAddress" label="注册详址" min-width="350" :show-overflow-tooltip="true"/>
    <el-table-column prop="mainName" label="负责人" min-width="150"/>
    <el-table-column prop="mainPhone" label="负责人联系方式" min-width="180"/>
    <el-table-column prop="businessStatus" label="营业状态" min-width="150">
      <template #default="{row}">
        <span v-if="row.businessStatus" class="tag-style">{{ DICTDISPLAYS.YYZT_MAP[row.businessStatus] || '' }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="businessCategory" label="企业分类" min-width="150">
      <template #default="{row}">
        <el-span style="color: #428DFF" v-if="row.businessCategory === '1'">{{ DICTDISPLAYS.QYFL_MAP[row.businessCategory] }}</el-span>
        <el-span style="color: #D4D43A" v-if="row.businessCategory === '2'">{{ DICTDISPLAYS.QYFL_MAP[row.businessCategory] }}</el-span>
        <el-span style="color: #E6A23C" v-if="row.businessCategory === '3'">{{ DICTDISPLAYS.QYFL_MAP[row.businessCategory] }}</el-span>
        <el-span style="color: #F56C6C" v-if="row.businessCategory === '4'">{{ DICTDISPLAYS.QYFL_MAP[row.businessCategory] }}</el-span>
      </template>
    </el-table-column>
    <el-table-column prop="agency.agencyName" label="属地" min-width="250"/>

    <template #dialog="{ dialogConfig: dc }">
      <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} from 'vue'
import {DEFAULT_ENTERPRISE_DETAIL, DICTDISPLAYS, DICTITEMS} from '@/utils/Constants.js'
import Browser from '@/components/Browser.vue'
import ElDialog from '@/components/ElDialog/index.vue'
import AgencySelector from '@/components/AgencySelector.vue'
import enterpriseInfo from '@pages/dtsjygl/enterpriseInfo.vue'
import enterprises from "@/api/lawenforcement/Enterprise.js"

const props = defineProps({
  dialogData: {type: Object, default: () => ({})},
  tag: {type: String, default: '2'}
})

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: {
    hasControlColumn: true,
    controlWidth: '100',
    multipleSelect: false,
    defaultSort: {
      prop: 'businessCategory',
      order: 'descending'
    }
  },
  apiConfig: {
    api: enterprises,
    modelId: 'enterpriseId'
  },
  dialogConfig: {
    type: 'fullscreen',
    show: false,
    mode: 'detail',
    loading: false,
    baseTitle: '企业信息',
    formLabelWidth: '90px',
    showFooter: false
  },
  actions: {
    detail: handleDetail
  },
  queryParams: {},
})

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

function customQuery(params) {
  tableConfig.value.tableLoading = true
  let query = Object.assign({}, params, props.dialogData)
  apiConfig.value.api.query(query).then(res => {
    tableConfig.value.tableLoading = false
    if (res.success) tableConfig.value.tableData = res
  }).catch(() => {
    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)
      }
    }
  })
}

async function handleDetail(row) {
  dialogConfig.value.show = true
  dialogConfig.value.mode = 'detail'
  dialogConfig.value.title = '详情企业信息'
  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
  })
}

</script>

<style lang="scss">

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

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

</style>
