<template>
  <browser :component-loading="componentLoading"
           class="enterpriseInfo"
           ref="broTable"
           :api-config="apiConfig"
           :table-config="tableConfig"
           :permissions="permissions"
           :dialog-config="dialogConfig"
           :actions="actions"
           :customQuery="true"
           @custom-query="handleQuery"
           @update:actions="actions = $event"
           @update:selection="selection = $event"
           @update:query-params="queryParams = $event"
           @update:dialog-config="dialogConfig = $event">
    <template #queryPanel="{ queryParams: queryParams }">
      <el-form ref="queryForm" :model="queryParams" label-width="80px">
        <el-row class="query-condition">
          <el-col :span="6">
            <el-form-item label="属地" prop="agency">
              <AgencySelector :filterable="true" v-model="queryParams.agency" :lazy-load="true" :multiple="false"
                              placeholder="请选择"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="行业类型" prop="industryType">
              <el-select v-model="queryParams.industryType" placeholder="请选择" clearable>
                <el-option v-for="item in DICTITEMS.HYLB_OPTIONS" :key="item.value" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="巡查类型" prop="xclx">
              <el-select v-model="queryParams.xclx" placeholder="请选择" clearable>
                <el-option v-for="item in DICTITEMS.XCLX_OPTIONS" :key="item.value" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <template #extraButton>
      <el-button class="ins-button" type="warning" @click="handleSelectData">定制巡查</el-button>
      <div class="extra-button" v-for="(item, index) in shopCarts" :key="index" @click="handleShopCart(item)">
        <span class="qys">{{ item.enterprise.length }}</span>
        <img src="../../assets/bigscreen/01.svg" style="width: 100%;height: 100%">
<!--        <font-awesome-icon icon="fa-shopping-cart" style="color: #2063fc; width: 100%;height: 100%"/>-->
      </div>
    </template>

    <el-table-column prop="agency.agencyName" label="属地" min-width="250"/>
    <el-table-column prop="unitName" label="企业" min-width="350"/>
    <el-table-column prop="industryType" label="行业类型" min-width="200">
      <template #default="{row}">
        <el-span>{{ DICTDISPLAYS.HYLB_MAP[row.industryType] || row.industryType }}</el-span>
      </template>
    </el-table-column>
    <el-table-column prop="videoAccessMsg" label="视频" min-width="100"/>
    <el-table-column prop="perceptionAccessMsg" label="感知" min-width="100"/>
    <el-table-column prop="infoAccessMsg" label="资料" min-width="100"/>
    <el-table-column prop="permitAccessMsg" label="许可" min-width="100"/>

    <template #dialog>
      <el-dialog class="business-dialog" v-model="dialogConfig.show" :show-close="false" :append-to-body="true"
                 fullscreen>
        <template #header>
          <div class="cvi-dialog-header">
            <div class="cvi-dialog-header-title">
              <div class="dialog-line"></div>
              {{ dialogConfig.title }}
            </div>
            <i class="iconfont icon-zyyy_tcgb" @click="dialogConfig.actions.handleClose"></i>
          </div>
        </template>

        <el-form :label-width="dialogConfig.formLabelWidth" :model="dialogConfig.data" :rules="dialogConfig.rules">
          <enterpriseInfo :dc="dialogConfig"/>
        </el-form>
      </el-dialog>

      <el-dialog class="business-dialog" v-model="dialogConfig1.show" :show-close="false" :append-to-body="true"
                 :top="'100px'">
        <template #header>
          <div class="cvi-dialog-header">
            <div class="cvi-dialog-header-title">
              <div class="dialog-line"></div>
              {{ dialogConfig1.title }}
            </div>
            <i class="iconfont icon-zyyy_tcgb" @click="dialogConfig1.actions.handleClose"></i>
          </div>
        </template>

        <el-form label-width="100px" :model="dialogConfig1.data" :rules="dialogConfig1.rules" ref="formRef">
          <el-row>
            <el-col :span="24" class="padding-bottom-10">
              <el-table :data="dialogConfig1.data.enterprise" height="300" border>
                <el-table-column header-align="center" align="center" label="属地" prop="agency.agencyName"
                                 min-width="250"/>
                <el-table-column header-align="center" align="center" label="企业名称" prop="unitName" min-width="250"/>
              </el-table>
            </el-col>
            <el-col :span="24">
              <el-form-item label="录入人" prop="createUserName">
                <el-input v-model="dialogConfig1.data.createUserName" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="录入时间" prop="createTime">
                <el-input v-model="dialogConfig1.data.createTime" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="有效期" prop="validTime">
                <el-date-picker v-model="dialogConfig1.data.validTime"
                                type="datetimerange"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                :default-time="[new Date(2000, 2, 1, 0, 0, 0),
                            new Date(2000, 2, 1, 23, 59, 59)]"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <template #footer>
          <div class="cvi-dialog-footer">
            <el-button @click="dialogConfig1.actions.handleClose">取消</el-button>
            <el-button type="primary" @click="dialogConfig1.actions.handleDialogOk">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </template>
  </browser>
</template>

<script setup>
import {reactive, toRefs, computed, ref, nextTick, watch} from 'vue'
import {useUserStore} from '@/stores/modules/user'
import enterprises from '@/api/lawenforcement/Enterprise.js'
import {DEFAULT_ENTERPRISE_DETAIL, DICTDISPLAYS, DICTITEMS} from '@/utils/Constants.js'
import {ElMessage} from 'element-plus'
import moment from 'moment'
import { v4 as uuid } from 'uuid'
import {AREA_DICT} from '@/utils/bigdict.js'
import Browser from '@/components/Browser.vue'
import enterpriseInfo from '@pages/dtsjygl/enterpriseInfo.vue'
import AgencySelector from '@/components/AgencySelector.vue'


let userInfo
useUserStore().getUserInfo().then(data => userInfo = data)

const state = reactive({
  queryParams: {},
  componentLoading: false,
  permissions: {
    query: true,
    add: false,
    modify: false,
    detail: true,
    delete: false,
    importFile: false,
    exportFile: false,
    exportSelectFile: false,
    downloadTemp: false,
  },
  tableConfig: {
    controlWidth: '80',
    hasControlColumn: true,
    multipleSelect: true,
    defaultSort: {
      prop: 'dynamicRiskLevel',
      order: 'descending'
    },
  },
  apiConfig: {
    api: enterprises,
    modelId: 'enterpriseId'
  },
  dialogConfig: {
    title: '企业详情',
    show: false,
    mode: 'detail',
    loading: false,
    formLabelWidth: '90px',
    rules: {
      industryType: [{required: true, message: '监管行业不能为空', trigger: 'blur'}],
      unitName: [{required: true, message: '生产经营单位名称不能为空', trigger: 'blur'}],
      shortName: [{required: true, message: '单位简称不能为空', trigger: 'blur'}],
      unifiedSocialCode: [{required: true, message: '社会统一信用代码不能为空', trigger: 'blur'}],
      businessStatus: [{required: true, message: '营业状态不能为空', trigger: 'blur'}],
      orgCode: [{required: false, message: '所属机构不能为空', trigger: 'blur'}],
      legalRepresentative: [{required: true, message: '法定代表人（经营者）姓名不能为空', trigger: 'blur'}],
      contactPhone: [{required: true, message: '联系电话不能为空', trigger: 'blur'}],
      agency: [{required: 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: {
      handleClose: handleClose,
    }
  },
  dialogConfig1: {
    show: false,
    mode: 'detail',
    title: '待巡查企业',
    loading: false,
    data: {},
    actions: {
      handleClose: handleClose1,
      handleDialogOk: handleDialogOk
    },
    rules: {
      validTime: [{required: true, message: '有效期不能为空', trigger: 'change'}],
    },
  },
  actions: {
    detail: handleDetail
  },
  selection: [],
})

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

// 分页查询
function handleQuery(queryParam) {
  tableConfig.value.tableLoading = true
  apiConfig.value.api.queryIns(queryParam).then(res => {
    tableConfig.value.tableLoading = false
    if (res.success) {
      tableConfig.value.tableData = res
    } else {
      ElMessage.error('执法信息查询失败')
    }
  })
}

// 详情查询
const defaultValues = reactive(DEFAULT_ENTERPRISE_DETAIL)

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

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

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 handleClose() {
  dialogConfig.value.show = false
}

// 定制巡查
let shopCarts = ref([])

function handleSelectData() {
  let arr = selection.value
  let data = Array.from(new Map(arr.map(item => [item.enterpriseId, item])).values())
  if (data.length < 1) {
    ElMessage.error('请选择待巡查企业')
    return
  }

  shopCarts.value.push({
    'id': uuid(),
    'enterprise': data,
    'createUserId': userInfo.yhwybs,
    'createUserName': userInfo.xm,
    'createTime': moment().format('YYYY-MM-DD HH:mm:ss')
  })
}

function handleShopCart(data) {
  dialogConfig1.value.data = Object.assign({}, data)
  dialogConfig1.value.show = true
}

function handleClose1() {
  dialogConfig1.value.show = false
}

const formRef = ref()

function handleDialogOk() {
  let _event = actions.value
  formRef.value.validate(valid => {
    if (valid) {
      dialogConfig1.value.data.validStartTime = dialogConfig1.value.data.validTime[0]
      dialogConfig1.value.data.validEndTime = dialogConfig1.value.data.validTime[1]
      dialogConfig1.value.data.enterpriseIds = dialogConfig1.value.data.enterprise.map(item => item.enterpriseId)
      dialogConfig.value.loading = true
      apiConfig.value.api.addIns(dialogConfig1.value.data).then(res => {
        dialogConfig.value.loading = false
        if (res.success) {
          // 移除购物车
          shopCarts.value = shopCarts.value.filter(item => item.id !== dialogConfig1.value.data.id)
          dialogConfig1.value.show = false
          ElMessage.success('操作成功')
          _event.query()
        } else {
          ElMessage.error('操作失败')
        }
      })
    }
  })
}
</script>

<style lang="scss" scoped>
:deep(.el-col-21) {
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
}

.ins-button {
  margin-left: unset !important;
  margin-right: 12px;
}

.extra-button {
  width: 24px !important;
  height: 24px !important;
  margin: 0px 12px 0px 0px !important;
  cursor: pointer;
  position: relative;

  .qys {
    width: 16px;
    height: 16px;
    background: red;
    border-radius: 50%;
    position: absolute;
    top: -6px;
    right: -6px;
    font-size: 12px;
    text-align: center;
    vertical-align: center;
  }

}

.el-dialog {
  margin-bottom: 0;
  border: 0.0625rem solid rgba(255, 255, 255, 1);
  border-radius: 1rem !important;
}

.el-dialog__body {
  height: unset !important;
}

.padding-bottom-10 {
  padding-bottom: 10px;
}
</style>
