<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"
           @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="130px">
        <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="企业分级">
              <el-select v-model="qp.businessRating" placeholder="请选择" clearable>
                <el-option v-for="item in DICTITEMS.QYFJ_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 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.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-row>
      </el-form>
    </template>
    <el-table-column prop="unitName" label="生产经营单位名称" min-width="200"/>
    <el-table-column prop="unifiedSocialCode" label="社会统一信用代码" min-width="150"/>
    <el-table-column prop="businessRating" label="企业分级" min-width="100">
      <template #default="{row}">
        <el-span>{{ DICTDISPLAYS.QYFJ_MAP[row.businessRating] }}</el-span>
      </template>
    </el-table-column>
    <el-table-column prop="agency.agencyName" label="属地" min-width="200"/>
    <el-table-column prop="businessCategory" label="企业分类" min-width="100">
      <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>
    <template #tableControlColumn="{data: r}">
      <el-link type="primary" @click="handleTune(r.data.row)" title="调整分级分类">调整分级分类</el-link>
    </template>
    <template #dialogContent="{ dialogConfig: dc }" v-if="dialogConfig.mode === 'tune'">
      <el-row style="height: 600px; overflow: auto;">
        <el-form :label-width="dc.formLabelWidth" label-position="left">
          <qyjbxx :dc="dc"/>
        </el-form>
      </el-row>
      <el-row style="padding-top: 15px; box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.2);">
        <el-col :span="12">
          <el-form-item label="企业分级" prop="businessRating">
            <el-radio-group :disabled="dc.mode !== 'add' && dc.mode !== 'modify' && dc.mode !== 'tune'"
                            v-model="dc.data.businessRating">
              <el-radio v-for="item in DICTITEMS.QYFJ_OPTIONS" :key="item.value" :label="item.value">{{
                  item.label
                }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="企业分类" prop="businessCategory">
            <el-radio-group :disabled="dc.mode !== 'add' && dc.mode !== 'modify' && dc.mode !== 'tune'"
                            v-model="dc.data.businessCategory">
              <el-radio v-for="item in DICTITEMS.QYFL_OPTIONS" :key="item.value" :label="item.value">{{
                  item.label
                }}
              </el-radio>
            </el-radio-group>
          </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} 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 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"
import Qyjbxx from "@pages/dtsjygl/enterprise/qyjbxx.vue"

const userStore = useUserStore()

const state = reactive({
  componentLoading: false,
  permissions: {
    query: true,
    add: false,
    modify: false,
    detail: true,
    delete: false,
    importFile: false,
    exportFile: true,
    exportSelectFile: false,
    downloadTemp: false,
  },
  tableConfig: {
    hasControlColumn: true,
    controlWidth: '180',
    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,
    rules: {
      businessRating: [{required: true, message: '企业分级不能为空', trigger: 'blur'}],
      businessCategory: [{required: true, message: '企业分类不能为空', trigger: 'blur'}]
    },
    data: {},
    actions: {handleDialogOk: handleDialogOk}
  },
  actions: {
    add: handleAdd,
    modify: handleModify,
    detail: handleDetail,
    exportData: handleExport
  },
  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)
}

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.type = 'fullscreen'
  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(formRef) {
  if (dialogConfig.value.mode === 'tune') {
    formRef.validate(valid => {
      if (valid) {
        dialogConfig.value.loading = true
        const data = Object.assign({}, {
          businessCategory: dialogConfig.value.data.businessCategory,
          businessRating: dialogConfig.value.data.businessRating,
          operate: 'tune'
        })
        apiConfig.value.api.modify(dialogConfig.value.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: 'fjfl'}))
}

function handleTune(row) {
  dialogConfig.value.show = true
  dialogConfig.value.mode = 'tune'
  dialogConfig.value.type = 'max'
  dialogConfig.value.title = '企业分级分类'
  dialogConfig.value.loading = true
  apiConfig.value.api.findOne(row[apiConfig.value.modelId]).then(res => {
    if (res.success) {
      const data = res.data || {}
      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>
