<template>
  <browser :component-loading="componentLoading"
           class="enterpriseInfo"
           ref="broTable"
           :api-config="apiConfig"
           :table-config="tableConfig"
           :permissions="permissions"
           :dialog-config="dialogConfig"
           :actions="actions"
           @update:query-params="queryParams = $event"
           @update:actions="actions = $event"
           @update:dialog-config="dialogConfig = $event">
    <template #queryPanel="{ queryParams: qp }">
      <el-form ref="queryForm" :model="qp" label-width="145px">
        <el-row class="query-condition">
          <el-col :span="6"><el-form-item label="生产经营单位名称"><el-input v-model="qp.unitName" clearable/></el-form-item></el-col>
          <el-col :span="6"><el-form-item label="社会统一信用代码"><el-input v-model="qp.unifiedSocialCode" clearable/></el-form-item></el-col>
          <el-col :span="6"><el-form-item label="营业状态"><DictSelector v-model="qp.businessStatus" dict-code="dm_yyzt" :multiple="false"/></el-form-item></el-col>
          <el-col :span="6"><el-form-item label="监管行业"><el-select v-model="qp.industryType" placeholder="请选择" clearable><el-option v-for="item in DICTITEMS.HYLB_OPTIONS" :key="item.value" :label="item.label" :value="item.value"></el-option></el-select></el-form-item></el-col>
          <el-col :span="6"><el-form-item label="属地"><AgencySelector :filterable="true" v-model="qp.agency" :lazy-load="true" :multiple="false" placeholder="请选择"/></el-form-item></el-col>
          <el-col :span="6"><el-form-item label="动态风险等级"><el-select v-model="qp.dynamicRiskLevel" placeholder="请选择" clearable><el-option v-for="item in DICTITEMS.DTFXDJ_OPTIONS" :key="item.value" :label="item.label" :value="item.value"></el-option></el-select></el-form-item></el-col>
          <el-col :span="6"><el-form-item label="成立日期"><el-date-picker v-model="qp.establishmentDateList" type="daterange" value-format="YYYY-MM-DD" start-placeholder="开始日期" end-placeholder="结束日期"/></el-form-item></el-col>
        </el-row>
      </el-form>
    </template>
    <el-table-column header-align="center" prop="industryType" label="监管行业" min-width="150">
      <template #default="{row}">
        <el-span>{{ DICTDISPLAYS.HYLB_MAP[row.industryType] || row.industryType }}</el-span>
      </template>
    </el-table-column>
    <el-table-column header-align="center" prop="unitName" label="生产经营单位名称" min-width="350"/>
    <el-table-column header-align="center" align="center" prop="unifiedSocialCode" label="社会统一信用代码" min-width="220"/>
    <el-table-column header-align="center" align="center" 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 header-align="center" align="center" prop="dynamicRiskLevel" label="动态风险等级" min-width="150">
      <template #default="{row}">
        <el-span style="color: #428DFF" v-if="row.dynamicRiskLevel === '1'">{{ DICTDISPLAYS.DTFXDJ_MAP[row.dynamicRiskLevel] }}</el-span>
        <el-span style="color: #D4D43A" v-if="row.dynamicRiskLevel === '2'">{{ DICTDISPLAYS.DTFXDJ_MAP[row.dynamicRiskLevel] }}</el-span>
        <el-span style="color: #E6A23C" v-if="row.dynamicRiskLevel === '3'">{{ DICTDISPLAYS.DTFXDJ_MAP[row.dynamicRiskLevel] }}</el-span>
        <el-span style="color: #F56C6C" v-if="row.dynamicRiskLevel === '4'">{{ DICTDISPLAYS.DTFXDJ_MAP[row.dynamicRiskLevel] }}</el-span>
      </template>
    </el-table-column>
    <el-table-column header-align="center" prop="agency.agencyName" label="属地" min-width="250"/>
    <el-table-column header-align="center" align="center" prop="establishmentDate" label="成立日期" min-width="150"/>
    <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>
    <input class="file" v-show="false" id="uploadExcelFileInput" name="file" type="file"
           accept="application/vnd.ms-excel,application/x-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
           @change="uploadFile"/>
  </browser>
</template>

<script setup>
import {reactive, toRefs, watch, computed, ref} from 'vue'
import Browser from '@/components/Browser.vue'
import {useUserStore} from '@/stores/modules/user'
import enterprises from "@/api/lawenforcement/Enterprise.js"
import {ElButton, ElMessage} from 'element-plus'
import DictSelector from "@/components/DictSelector.vue"
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 AgencySelector from "@/components/AgencySelector.vue"
import {AREA_DICT} from "@/utils/bigdict.js"

const userStore = useUserStore()

const state = reactive({
  componentLoading: false,
  permissions: {
    query: true,
    add: false,
    modify: true,
    detail: true,
    delete: true,
    importFile: true,
    exportFile: true,
    exportSelectFile: false,
    downloadTemp: true,
    canDeleteCustom: (row) => {return row.delFlag !== 1},
    canModifyCustom: (row) => {return row.delFlag !== 1}
  },
  tableConfig: {
    hasControlColumn: true,
    controlWidth: '150',
    multipleSelect: false,
    defaultSort: {
      prop: 'dynamicRiskLevel',
      order: 'descending'
    }
  },
  apiConfig: {
    api: enterprises,
    modelId: 'enterpriseId'
  },
  dialogConfig: {
    type: 'fullscreen',
    show: false,
    mode: 'detail',
    loading: false,
    baseTitle: '企业信息',
    formLabelWidth: '90px',
    showFooter: false,
    rules: {
      industryType: [{ required: true, message: '监管行业不能为空', trigger: 'blur' }],
      unitName: [{ required: true, message: '生产经营单位名称不能为空', trigger: 'blur' }],

   uired: 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: {handleDialogOk: handleDialogOk}
  },
  actions: {
    add: handleAdd,
    modify: handleModify,
    detail: handleDetail,
    exportData: handleExport,
    importData: handleImport,
    downloadTemplate: downloadTemplate
  },
  queryParams: {}
})

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

const defaultValues = reactive(DEFAULT_ENTERPRISE_DETAIL)

function handleAdd() {
  dialogConfig.value.show = true
  dialogConfig.value.mode = 'add'
  dialogConfig.value.title = '新增企业信息'
  dialogConfig.value.loading = false
  dialogConfig.value.data = Object.assign({}, defaultValues,
      {administrativeLicenseInfos: [{licenseNum: "", issuingOffice: "", validFrom: "", validEnd: "", licenseTypes: [], qtPicList: [], xkzPicList: []}]}
  )
}

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

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

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.title = '详情企业信息'
  findOne(row)
}

async function handleModify(row) {
  dialogConfig.value.show = true
  dialogConfig.value.mode = 'modify'
  dialogConfig.value.title = '编辑企业信息'
  findOne(row)
}

const dialogFormRef = ref(null)
function handleDialogOk() {
  const data = Object.assign({}, dialogConfig.value.data)
  const regulatedIndustry = data.regulatedIndustry
  if (regulatedIndustry && regulatedIndustry.length > 0) {
    regulatedIndustry.forEach((o, i) => {
      if (i === 0) data.econCategory = o
      if (i === 1) data.econCategoryTypea = o
      if (i === 2) data.econCategoryTypeb = o
      if (i === 3) data.econCategoryTypec = o
    })
    data.regulatedIndustry = regulatedIndustry.join('/')
  }
  const areaComb = data.areaComb
  if (areaComb && areaComb.length > 0) {
    areaComb.forEach((o, i) => {
      if (i === 0) data.province = o
      if (i === 1) data.city = o
      if (i === 2) data.county = o
    })
    data.areaComb = areaComb.join('/')
  }
  const opLocAreaComb = data.opLocAreaComb
  if (opLocAreaComb && opLocAreaComb.length > 0) {
    opLocAreaComb.forEach((o, i) => {
      if (i === 0) data.opLocProvince = o
      if (i === 1) data.opLocCity = o
      if (i === 2) data.opLocArea = o
    })
    data.opLocAreaComb = opLocAreaComb.join('/')
  }
  // 将指定字段转换为 JSON 字符串
  const fieldsToSerialize = Object.keys(defaultValues)
  fieldsToSerialize.forEach(field => {
    if (data[field]) {
      data[field] = JSON.stringify(data[field])
    }
  })
  if (!data.agency?.agencyId) delete data.agency
  data.administrativeLicenseInfos.forEach(administrativeLicense => {
    console.log(administrativeLicense.qtPicList)
    if (administrativeLicense.qtPicList.length > 0)
      administrativeLicense.qtPics = administrativeLicense.qtPicList.map(item => item.path).join(",")
    if (administrativeLicense.xkzPicList.length > 0)
      administrativeLicense.xkzPics = administrativeLicense.xkzPicList.map(item => item.path).join(",")
    if (administrativeLicense.licenseTypes.length > 0)
      administrativeLicense.licenseType = administrativeLicense.licenseTypes.join(",")
  })
  dialogFormRef.value.validate(valid => {
    if (valid) {
      dialogConfig.value.loading = true
      if (dialogConfig.value.mode === 'add') {
        apiConfig.value.api.add(data).then(res => {
          if (res.success) {
            ElMessage.success('操作成功')
            dialogConfig.value.show = false
            actions.value.query()
          } else {
            throw new Error('操作失败')
          }
          dialogConfig.value.loading = false
        }).catch(() => dialogConfig.value.loading = false)
      } else if (dialogConfig.value.mode === 'modify') {
        apiConfig.value.api.modify(data[apiConfig.value.modelId], data).then(res => {
          if (res.success) {
            ElMessage.success('操作成功')
            dialogConfig.value.show = false
            actions.value.query()
          } else {
            throw new Error('操作失败')
          }
          dialogConfig.value.loading = false
        }).catch(() => dialogConfig.value.loading = false)
      }
    }
  })
}

function handleProvinceChange () {
  queryParams.value.opLocCity = ''
  queryParams.value.opLocArea = ''
}

function handleCityChange () {
  queryParams.value.opLocArea = ''
}

const broTable = ref(null)
function handleExport(){
  broTable.value.busiTable.exportExcelFileForAllData('/api/lawenforcement/enterprises/export', '企业信息', Object.assign({}, queryParams.value, {tag: 'cx'}))
}

async function handleImport() {
  let fileObj = document.getElementById('uploadExcelFileInput')
  fileObj.click()
}

function uploadFile(e) {
  tableConfig.value.tableLoading = true
  let file = e.target.files[0]
  let params = new FormData()
  params.append('file', file)
  apiConfig.value.api.importExcelFile(params).then(res => {
    if (res.success) {
      ElMessage.success('导入成功')
      actions.value.query()
    }
    tableConfig.value.tableLoading = false
  }).catch(() => {tableConfig.value.tableLoading = false})
  document.getElementById('uploadExcelFileInput').value = ''
}

function downloadTemplate() {
  const link = document.createElement('a')
  link.href = '/files/企业信息导入模板.xlsx'
  link.download = '企业信息导入模板.xlsx'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

</script>

<style lang="scss">

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

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

</style>