<template>
  <el-dialog :title="props.title" width="95%" v-model="dialogVisible" @close="onClose">
    <el-form ref="formRef" label-width="130px" label-align="left" :model="querySelect" label-suffix=":"
      style="flex-wrap: wrap">
      <el-row>
        <el-col :span="5">
          <el-form-item label="事故名称" prop="name">
            <el-input v-model="querySelect.name" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="事故类型" prop="value">
            <MOSTY.DictTree :zdbh="'D_BZ_SGSJLB'" v-model="querySelect.accidentCategoryCode" :placeholder='"请选择事故类别:"'
              :disabled='false' @onChange="handleScly" style="width: 222px;" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="事故责任类型" prop="liabilityTypeCode">
            <MOSTY.DictRidioAndSelect :dictData="D_BZ_SGZRLX" v-model="querySelect.liabilityTypeCode"
              selectType="select" style="width: 200px;" @getselect='onChangezrlx' />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="上报状态" prop="status">
            <el-select v-model="querySelect.status" @change="changeStatus" style="width: 150px;">
              <el-option label="全部" value="" />
              <el-option label="已上报" value="1" />
              <el-option label="未上报" value="2" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <span class="fr">
            <!-- <el-button type="primary" @click="handleCache" v-if="!props.isSfsb && props.isEdit && !props.isProvinces" :disabled="isShowBtn">暂存数据</el-button> -->
            <el-button type="primary" @click="onSearch"><el-icon>
                <Search />
              </el-icon>搜索</el-button>
            <el-button @click="onRest"><el-icon>
                <Refresh />
              </el-icon>重置</el-button>
            <el-button v-if="dataTable.length > 0 && props.rowItem.status == '2' && isbgs" @click="onStagingReport"
              :disabled="gDisabled">
              <el-icon>
                <Upload />
              </el-icon>暂存上报</el-button>
            <!-- v-if="props.rowItem.status == '2' && isbgs" -->
            <el-button @click="onAdd">
              <el-icon>
                <Plus />
              </el-icon>新增</el-button>
          </span>
        </el-col>
      </el-row>
    </el-form>
    <el-table ref="multipleTableRef" :row-key="keyid" border :data="dataTable" style="width: 100%; margin-bottom: 10px"
      height="50vh" v-loading="tableLoading" :header-cell-style="{ background: '#F6F6F6' }"
      @selection-change="onSelectionChange" @select-all="handleCheckBox" @select="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">
      </el-table-column>
      <el-table-column label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <el-link type="primary" @click="handleChange(row, 'view')">查看</el-link>
          <!-- v-if="props.rowItem.status == '2' && isbgs" -->
          <!-- :disabled="gDisabled" -->
          <el-link type="primary" @click="handleChange(row, 'edit')">编辑</el-link>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
            @confirm="onDelete(row)">
            <template #reference>
              <el-link type="danger">删除</el-link>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex just-center">
      <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="querySelect.total"></el-pagination>
    </div>
  </el-dialog>
  <Detail :isEdit="isEdit" @close="detailClose" :title="dialogTitle" v-if="detailVisible" :detailId="detailId"
    :rowItem="props.rowItem" :query="props.params" />
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, computed, nextTick } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import * as MOSTY from "@/components/MyComponents/index"
import { Delete, Edit, Search, Share, Upload } from "@element-plus/icons-vue"
import Detail from "./Detail.vue"
import { getItem } from "@/utils/storage"
import { ElMessage } from "element-plus"
const { proxy } = getCurrentInstance()
const { D_BZ_SGZRLX } = proxy.$dict("D_BZ_SGZRLX")
import { filterqx } from "@/utils/auth.js"

const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  isEdit: {
    type: Boolean,
    default: true
  },
  isProvinces: Boolean,
  params: Object,
  orgCode: String,
  reportStatus: String,
  rowItem: Object
})
const emits = defineEmits(["close"])
const dialogVisible = ref(true)
const detailVisible = ref(false)
const detailId = ref("")
const dialogTitle = ref("")
const formRef = ref()
const multipleTableRef = ref(null)
const isShowBtn = ref(true)
const columnTable = ref([
  { label: "企业名称", prop: "orgName" },
  { label: "事故名称", prop: "name" },
  { label: "事故发生日期", prop: "occurDate" },
  { label: "事故类型", prop: "accidentCategoryName" },
  { label: "事故责任类型", prop: "liabilityTypeName" },
  { label: "事故死亡人员数量", prop: "deathQty" },
  { label: "事故重伤人员数量", prop: "seriousInjuryQty" },
  { label: "事故轻伤人员数量", prop: "slightInjuryQty" },
  { label: "事故直接经济损失", prop: "directEconomicLoss" }
])
const dataTable = ref([])
const isEdit = ref(true)
const isbgs = ref(true)
const querySelect = reactive({
  name: "",
  pageCurrent: 1,
  pageSize: 10,
  total: 0,
  accidentCategoryCode: "",
  // type: "-1",
  status: props.reportStatus
})
const pageData = reactive({
  ids: []
})
//县级账号
const isTown = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") != "1" && filterqx("isSgs") != "1"
})
const gDisabled = computed(() => {
  // return props.orgCode.includes("XN") || isTown.value ? false : true
  // return false
  if (props.orgCode.includes("XN")) {
    return false
  } else if (isTown.value) {
    return props.rowItem.status === "2" ? false : true
  } else return true
})


const tableLoading = ref(false)
const multipleSelection = ref([])
const reportSore = ref([])
const reportChange = reactive({
  notReportIds: [],
  ids: []
})

// 点击操作
const handleChange = (data, type) => {
  isEdit.value = type == "view" ? false : true
  detailId.value = data.id
  dialogTitle.value = `${type == "view" ? "查看" : "编辑"}事故事件（${data.baOrgName}）`
  detailVisible.value = true
}
const onAdd = () => {
  isEdit.value = true
  dialogTitle.value = `新增事故事件（${props.rowItem.baOrgName}）`
  detailVisible.value = true
}
const handleScly = e => {
  querySelect.accidentCategoryCode = e.dm
  getDataList()
}
function onChangezrlx(e) {
  querySelect.liabilityTypeCode = e.value
  getDataList()
}
//表格选择
const onTableChange = val => {
  isShowBtn.value = val.length >= 1 ? false : true
  pageData.ids = val
}
const onSelectionChange = val => {
  multipleSelection.value = val
}
const onDelete = row => {
  postApi([row.id], "/mosty-jcgl/data/accidentEvents/del").then(res => {

  }).finally(() => {
    ElMessage({
      message: "删除成功",
      type: "success"
    })
    getDataList()
  })
}
// 点击缓存数据
const onStagingReport = () => {
  postApi({ ...reportChange, ...props.params, orgCode: props.orgCode }, "/mosty-jcgl/data/accidentEvents/accidentEventsReportData")
    .then(res => {
      if (res) {
        ElMessage({
          message: "暂存上报数据成功",
          type: "success"
        })
        onRest()
      }
    })
    .finally(() => {
      reportChange.ids = []
      reportChange.notReportIds = []
    })
}
const keyid = row => {
  return row.sourceId
}
//回显示  需要给出row-key相同的数据
const toggleSelection = rows => {
  if (rows) {
    rows.forEach((row) => {
      if (row.status == '1') {
        multipleTableRef.value?.toggleRowSelection(row, true)
      } else {
        multipleTableRef.value?.toggleRowSelection(row, false)
      }
    })
  } else {
    multipleTableRef.value?.clearSelection()
  }
}
// 重置
const onRest = () => {
  querySelect.name = ""
  querySelect.pageCurrent = 1
  querySelect.pageSize = 10
  querySelect.total = 0
  querySelect.accidentCategoryCode = ""
  querySelect.liabilityTypeCode = ""
  reportSore.value = []
  reportChange.ids = []
  reportChange.notReportIds = []
  // querySelect.type = "-1"
  getDataList()
}
const onSearch = () => {
  querySelect.pageCurrent = 1
  querySelect.pageSize = 10
  querySelect.total = 0
  getDataList()
}
// 关闭弹窗
const onClose = () => {
  emits("close")
}
//关闭详情弹窗
const detailClose = val => {
  if (val) {
    getDataList()
  }
  detailVisible.value = false
}
// 切换条数
const handleSizeChange = val => {
  querySelect.pageSize = val
  getDataList()
}
// 切换分页
const handleCurrentChange = val => {
  querySelect.pageCurrent = val
  getDataList()
}
// 根据条件查询
const handleQuery = _id => {
  // querySelect.type = _id
  getDataList()
}
// 获取表格数据
const getDataList = () => {
  tableLoading.value = true
  dataTable.value = []
  querySelect.orgCode = props.orgCode
  querySelect.jd = props.params.jd
  querySelect.year = props.params.year
  postApi(querySelect, "/mosty-jcgl/data/accidentEvents/queryAccidentEventsData").then(res => {
    if (res) {
      dataTable.value = res.records
      tableLoading.value = false
      querySelect.total = res.total

      nextTick(() => {
        dataTable.value.forEach(item => {
          if (item.status === "1") {
            multipleTableRef.value.toggleRowSelection(item)
            if (!reportSore.value.includes(item.sourceId)) reportSore.value.push(item.sourceId)
            // if(!reportChange.ids.includes(item.sourceId)) reportChange.ids.push(item.sourceId)
          }
        })
      })
    }
  })
}
const changeStatus = e => {
  getDataList()
}
const handleCheckBox = (selection, row) => {
  if (row) {
    //单选
    const index = reportChange.ids.indexOf(row.sourceId)
    const index2 = reportChange.notReportIds.indexOf(row.sourceId)
    if (index === -1 && index2 === -1) {
      if (row.status == '1') {
        reportChange.notReportIds.push(row.sourceId)
      } else {
        reportChange.ids.push(row.sourceId)
      }
    } else {
      if (index !== -1) {
        reportChange.ids.splice(index, 1)
      }
      if (index2 !== -1) {
        reportChange.notReportIds.splice(reportChange.notReportIds.indexOf(row.sourceId), 1)
      }
    }
  } else {
    if (selection.length > 0) {
      reportChange.ids = selection.map(item => item.sourceId)
      reportChange.notReportIds = []
    } else {
      reportChange.notReportIds = dataTable.value.map(item => item.sourceId)
      reportChange.ids = []
    }
  }
}
onMounted(() => {
  if (props.rowItem.orgCode == getItem("deptId").ssdwid) {
    isbgs.value = true
  } else {
    isbgs.value = true
  }
  getDataList()
})
</script>

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

::v-deep .el-button--link {
  border: none;
  background: none;
  color: var(--el-color-primary);
  padding: 0;
  margin-left: 10px !important;

  &:hover,
  &:focus {
    background: none;
    border: none;
    opacity: 0.9;
  }
}

::v-deep .el-button--link.is-disabled {
  color: #808596;
  border: none;
  background: none;
}

.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>
