<template>
  <el-dialog :title="props.title" width="95%" v-model="dialogVisible" @close="onClose">
    <div class="flex just-between">
      <div>
        <el-form ref="formRef" label-width="110px" label-align="left" :model="querySelect" label-suffix=":"
          style="display: flex; flex-wrap: wrap">
          <el-form-item label="有限空间类别" prop="categoryCode">
            <div style="width: 180px">
              <MOSTY.DictRidioAndSelect placeholder="请选择有限空间类别" :dictData="D_BZ_YXKJLB"
                v-model="querySelect.categoryCode" selectType="select" />
            </div>
          </el-form-item>
          <el-form-item label="上报状态" prop="status">
            <el-select v-model="querySelect.status" style="width: 180px" @change="changeStatus">
              <el-option label="全部" value="" />
              <el-option label="已上报" value="1" />
              <el-option label="未上报" value="2" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button @click="searchs" class="mr10">
          <el-icon>
            <Search />
          </el-icon>搜索</el-button>
        <el-button @click="onRest" class="mr10">
          <el-icon>
            <Refresh />
          </el-icon>重置</el-button>
        <el-button v-if="dataTable.length > 0 && props.rowItem.status == '2' && isAuth" @click="onStagingReport"
          :disabled="gDisabled" class="mr10">
          <el-icon>
            <Upload />
          </el-icon>暂存上报</el-button>
        <!--  v-if="props.rowItem.status == '2' && isAuth" -->
        <el-button @click="onAdd" class="mr10">
          <el-icon>
            <Plus />
          </el-icon>新增</el-button>
      </div>
    </div>
    <el-table ref="multipleTableRef" :row-key="keyid" border :data="dataTable" style="width: 100%;"
      v-loading="tableLoading" :header-cell-style="{ background: '#F6F6F6' }" height="50vh"
      @selection-change="onSelectionChange" @select="handleCheckBox" @select-all="handleCheckBox">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="55" fixed />
      <el-table-column :prop="item.prop" :label="item.label" v-for="(item, index) in columnTable" :key="index">
        <template #default="{ row }" v-if="item.prop === 'hazardFactor'">
          <span
            v-if="row.hazardFactor && row.hazardFactor.split(',').some(num => ['1', '2', '3', '4', '5', '6', '7'].includes(num))">
            {{ changeDanger(row) }}
          </span>
          <span v-else>{{ row.hazardFactor }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <el-link type="primary" @click="onView(row)">查看</el-link>
          <!-- :disabled="gDisabled"
            v-if="props.rowItem.status == '2' && isAuth" -->
          <el-link type="primary" @click="onEdit(row)">编辑</el-link>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
            @confirm="detelChange(row)">
            <template #reference>
              <el-link type="danger">删除</el-link>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex just-center mt10">
      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="querySelect.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="querySelect.pageSize"
        layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
    </div>
  </el-dialog>
  <Dialog @close="detailClose" :title="dialogTitle" v-if="detailVisible" :detail="detail" :dict="{ D_BZ_YXKJLB }"
    :rowItem="props.rowItem" :query="props.params" />
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, nextTick, computed } from "vue"
import { Delete, Edit, Search, Share, Upload } from "@element-plus/icons-vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import * as MOSTY from "@/components/MyComponents/index"
import { getItem } from "@/utils/storage"
import { ElMessage } from "element-plus"
import { filterqx } from "@/utils/auth.js"
import { isString } from '@/utils/tools.js';
import Dialog from "./dialog.vue"
const { proxy } = getCurrentInstance()
const { D_BZ_YXKJLB, D_TB_YHWHYS } = proxy.$dict("D_BZ_YXKJLB", "D_TB_YHWHYS");
const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  params: Object,
  orgCode: String,
  reportStatus: String,
  rowItem: Object,
  dict: Object
})
const emits = defineEmits(["close"])
const dialogVisible = ref(true)
const detailVisible = ref(false)
const detail = ref(null)
const dialogTitle = ref("")
const formRef = ref()
const multipleTableRef = ref(null)
const columnTable = ref([
  { label: "企业名称", prop: "orgName" },
  { label: "场所（设备）名称", prop: "placeEquipmentName" },
  { label: "有限空间类别", prop: "categoryName" },
  { label: "有限空间数量", prop: "lsQty" },
  { label: "有限空间危害因素", prop: "hazardFactor" },
  { label: "有限空间可能造成的事故类别", prop: "accidentCategoryName" }
])
//县级账号
const isTown = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") != "1" && filterqx("isSgs") != "1"
})
const isAuth = computed(() => {
  let code = props.orgCode
  return getItem("deptId").ssdwid == code.replace("XN", "")
})
const gDisabled = computed(() => {
  if (props.orgCode.includes("XN")) {
    return false
  } else if (isTown.value) {
    return props.rowItem.status === "2" ? false : true
  } else return true
})
const total = ref(0)
const dataTable = ref([])
const querySelect = reactive({
  pageCurrent: 1,
  pageSize: 10,
  year: props.params.year,
  orgCode: props.orgCode,
  jd: props.params.jd,
  categoryCode: '',
  status: props.reportStatus || ''
})
const multipleSelection = ref([])
const currentCode = getItem("deptId").ssdwid
const pageData = reactive({
  ids: [],
  notReportIds: []
})
// 处理危险因素代码
const changeDanger = (row) => {
  let strData = []
  row.hazardFactor.split(',').forEach((item) => {
    strData.push(D_TB_YHWHYS.value[parseInt(item) - 1].label)
  })
  let str = strData.join(',')
  return str
}
const handleCheckBox = (selection, row) => {
  if (row) {
    const index = pageData.ids.indexOf(row.sourceId)
    if (index === -1) {
      pageData.ids.push(row.sourceId)
      pageData.notReportIds.splice(pageData.notReportIds.indexOf(row.sourceId), 1)
    } else {
      pageData.notReportIds.push(row.sourceId)
      pageData.ids.splice(pageData.ids.indexOf(row.sourceId), 1)
    }
  } else {
    pageData.ids = selection.map(item => item.sourceId)
    pageData.notReportIds = dataTable.value.filter(item => !selection.some(s => s.sourceId === item.sourceId)).map(item => item.sourceId)
  }
}
const tableLoading = ref(false)
onMounted(() => {
  getDataList()
})
//删除
function detelChange(row) {
  postApi([row.id], '/mosty-jcgl/data/spaceOpsSite/del').then(res => {
    ElMessage.success(`删除成功`);
    getDataList()
  })
}
// 获取表格数据
const getDataList = () => {
  dataTable.value = []
  pageData.ids = []
  postApi(querySelect, "/mosty-jcgl/data/spaceOpsSite/querySpaceOpsSiteData").then(res => {
    if (res) {
      dataTable.value = res.records
      nextTick(() => {
        dataTable.value.forEach(item => {
          if (item.status === "1") {
            multipleTableRef.value.toggleRowSelection(item)
            pageData.ids.push(item.sourceId)
          }
        })
      })

      tableLoading.value = false
      total.value = res.total
    }
  })
}
// 点击操作
const onView = data => {
  detail.value = data
  detail.value.accidentCategoryCode = isString(detail.value.accidentCategoryCode) ? detail.value.accidentCategoryCode.split(",") : detail.value.accidentCategoryCode
  dialogTitle.value = `有限空间作业场所详情`
  detailVisible.value = true
}
const onEdit = data => {
  detail.value = data
  detail.value.accidentCategoryCode = isString(detail.value.accidentCategoryCode) ? detail.value.accidentCategoryCode.split(",") : detail.value.accidentCategoryCode
  dialogTitle.value = `有限空间作业场所编辑`
  detailVisible.value = true
}
const onAdd = () => {
  detail.value = {}
  dialogTitle.value = `有限空间作业场所新增`
  detailVisible.value = true
}
// 选择锅炉类型
const onChangesblx = e => {
  getDataList()
}

const keyid = row => {
  return row.sourceId
}
//搜索
function searchs() {
  querySelect.pageCurrent = 1
  querySelect.pageSize = 10
  total.value = 0
  getDataList()
}
// 重置
const onRest = () => {
  querySelect.pageCurrent = 1
  querySelect.pageSize = 10
  querySelect.categoryCode = ""
  querySelect.status = ""
  total.value = 0
  getDataList()
}
// 关闭弹窗
const onClose = () => {
  emits("close", true)
}
//关闭详情弹窗
const detailClose = val => {

  detailVisible.value = false
  getDataList()
}
// 切换条数
const handleSizeChange = val => {
  querySelect.pageSize = val
  getDataList()
}
// 切换分页
const handleCurrentChange = val => {
  querySelect.pageCurrent = val
  getDataList()
}
const onSelectionChange = val => {
  multipleSelection.value = val
}
const onStagingReport = () => {
  postApi({ ids: pageData.ids, notReportIds: pageData.notReportIds, ...props.params, orgCode: props.orgCode, status: querySelect.status }, "/mosty-jcgl/data/spaceOpsSite/SpaceOpsSiteReportData").then(res => {
    if (res) {
      ElMessage({
        message: "暂存上报数据成功",
        type: "success"
      })
      getDataList()
    }
  })
}
const changeStatus = e => {
  getDataList()
}
</script>

<style lang="scss" scoped>
::v-deep .el-link.el-link--primary.is-disabled {
  color: #808596;
  cursor: not-allowed;
}

.content {
  .topper {
    display: flex;

    .sub-le {
      flex: 1;
      padding: 15px 15px 5px 15px;
      border-right: 1px solid #ebeef5;
    }
  }

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