<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:selection="handleSelectData"
           @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" :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}">
        <span>{{ DICTDISPLAYS.QYFJ_MAP[row.businessRating] }}</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="handDistribution(r.data.row,'single')" title="转交">转交</el-link>
    </template>
    <template #dialogContent="{ dialogConfig: dc }" v-if="dialogConfig.mode === 'tune'">
      <el-row>
        <el-col :span="24">
          <el-form-item label="检查企业:">{{ dc.data.unitName }}</el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="转交部门:">
            <AgencySelector :root-id="rootId" v-model="agencyData" :multiple="false" placeholder="请选择"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="说明:">
            <el-input v-model="dc.data.description"></el-input>
          </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 {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 AgencySelector from "@/components/AgencySelector.vue"
import supervisions from "@/api/lawenforcement/SupervisionCheck.js"
import messagesApi from "@/api/lawenforcement/Message.js";

const userStore = useUserStore()
const rootId = ref(userStore.deptInfo.agencyLevel === 3 ? userStore.deptInfo.parent.agencyId : userStore.deptInfo.agencyId)
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,
    selectable: (row) => {
      return row.enterpriseId
    },
    controlWidth: '180',
    defaultSort: {
      prop: 'businessCategory',
      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}
  },
  actions: {
    detail: handleDetail,
  },
  selection: [],
  queryParams: {}
})

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

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 agencyData = ref(null)
const dialogFormRef = ref(null)

function handleDialogOk(formRef) {
  if (dialogConfig.value.mode === 'tune') {
    if (agencyData.value !== null && agencyData.value.agencyId !== null && agencyData.value.agencyId !== undefined) {
      if (agencyData.value.agencyCode === '01610100000000000') {
        ElMessage.error("不能转交给上级机构！")
        return
      } else if (agencyData.value.agencyCode === userStore.userInfo.gajgjgdm) {
        ElMessage.error("不能转交本辖区！")
        return
      } else {
        dialogConfig.value.data.agency = agencyData.value
        dialogConfig.value.data.checkType = '交叉互查'
        console.log(dialogConfig.value.data)
        supervisions.add(dialogConfig.value.data).then(res => {
          if (res.success) {
            messagesApi.sendMessage({
              title: '交叉互查完成',
              content: '您有新的交叉互查执法信息待处理!',
              routeUrl: '/xzzfgl/ddjcjh/ddjcrwgl',
              businessKey: dialogConfig.value.data.enterprise.enterpriseId,
              receiverIds: ['111111']
            }).then(rs => {
            })
            ElMessage.success("转交成功")
            dialogConfig.value.show = false
          }
        })
      }

    } else {
      ElMessage.error("请选择转交部门")
    }
  }
}


function handleSelectData(value) {
  selection.value = value

}

function handDistributionAll() {
  handDistribution(selection.value, 'multiple')

}

function handDistribution(enterprises, type) {
  let qymc = ''
  let object = {
    type: type,
    description: ''
  }
  if (type === 'multiple') {
    enterprises.forEach(enterprise => {
      qymc = qymc + enterprise.unitName + ','
    })
    let lastIndex = qymc.lastIndexOf(','); // 找到最后一个逗号的位置
    if (lastIndex !== -1) { // 确保找到了逗号
      object.unitName = qymc.substring(0, lastIndex) + qymc.substring(lastIndex + 1); // 替换最后一个逗号
    }
    // object.unitName = qymc
    object.enterprises = enterprises
  } else {
    object.enterprise = enterprises
    object.unitName = enterprises.unitName
  }

  dialogConfig.value.data = object
  dialogConfig.value.type = null
  dialogConfig.value.formLabelWidth = '120px'
  dialogConfig.value.title = '选择转交机构'
  dialogConfig.value.show = true
  dialogConfig.value.mode = 'tune'

}

</script>

<style lang="scss">

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

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

</style>
