<template>
  <el-dialog :title="props.title" width="1400px" v-model="dialogVisible" @close="onClose">
    <div class="flex just-between">
      <div>
        <el-form ref="formRef" label-width="110px" label-align="left" :model="listQuery" label-suffix=":"
          style="display: flex; flex-wrap: wrap">
          <el-form-item label="职业危害场所名称" prop="searchName">
            <el-input placeholder="请输入职业危害场所名称" v-model="listQuery.searchName" clearable style="width: 180px" />
          </el-form-item>
          <el-form-item label="上报状态" prop="status">
            <el-select v-model="listQuery.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 type="primary" @click="pageData" class="mr10"><el-icon>
            <Search />
          </el-icon>
          查询
        </el-button>
        <el-button @click="onRest" class="mr10">
          <el-icon>
            <Refresh />
          </el-icon>重置</el-button>
        <el-button class="mr10" @click="onStagingReport" :disabled="gDisabled">
          <el-icon>
            <Upload />
          </el-icon>暂存上报</el-button>
        <el-button @click="onAdd" class="mr10">新增</el-button>
      </div>
    </div>
    <div class="dialog-wrapper-content">
      <el-table border ref="multipleTableRef" id="mergeTable" :data="tableData" style="width: 100%"
        highlight-current-row :header-cell-style="{ background: '#F6F6F6' }" v-loading="tableLoading"
        @selection-change="onSelectionChange" height="100%">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" align="center" width="80" />
        <el-table-column label="企业名称" prop="orgName" align="center" width="200" />
        <el-table-column label="职业危害场所名称" prop="placeName" align="center" />
        <el-table-column label="职业危害因素" prop="factorName" align="center" />
        <el-table-column label="最近检测日期" prop="ckeckDate" align="center" />
        <el-table-column label="最近检测点位数量" prop="pointsQty" align="center" />
        <el-table-column label="最近超标点位数量" prop="exceedingPointsQty" align="center" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-link type="primary" @click="onView(row)">查看</el-link>
            <el-link type="primary" @click="onEdit(row)" style="margin-right: 8px">编辑</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>
    <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="listQuery.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.pageSize"
      layout="total, prev, pager, next, sizes, jumper" :total="listQuery.total"></el-pagination>
  </el-dialog>

  <el-dialog :title="'职业危害场所' + honorTitle" width="1200px" v-model="honorDialogVisible" :before-close="closeDialog">
    <MOSTY.Assort :title="'基础信息'" />
    <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="105px" :model="formData" :inline="true"
      :rules="rules" :disabled="honorTitle === '查看'">
      <el-form-item label="场所名称:" prop="placeName">
        <el-input v-model="formData.placeName" placeholder="请输入场所名称" style="width: 250px"></el-input>
      </el-form-item>
      <!-- <el-form-item label="场所地址:" prop="siteaddress">
        <el-input v-model="formData.siteaddress" placeholder="请输入场所地址" style="width: 250px"></el-input>
      </el-form-item>
      <el-form-item label="所属部门:" prop="departmentname">
        <el-input v-model="formData.departmentname" readonly style="width: 250px">
          <template #append> <el-button class="cursor" @click="ChooesDdld('01')">选择</el-button></template>
        </el-input>
      </el-form-item>
      <el-form-item label="危害因素:" prop="hazardousfactors">
        <el-select v-model="formData.hazardousfactors" placeholder="请选择危害因素" multiple style="width: 250px">
          <el-option v-for="item in props.dicData.D_TB_ZYJK_WHYS" :key="item.value" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注:" prop="bz">
        <el-input v-model="formData.bz" type="textarea" autosize show-word-limit style="width: 1043px"
          maxlength="200" />
      </el-form-item>
      <el-form-item label="场所二维码:" v-if="formData.id" style="width: 100%">
        <MOSTY.ErwmImg v-if="formData.id"
          :url="qrcodeImg(formData.id, 'S', formData.departmentname, `${formData.sitename}(${formData.nbbh})`)"
          :filename='"职业危害场所二维码"' />
      </el-form-item> -->
    </el-form>
    <MOSTY.Assort :title="'检查记录'" />
    <!-- <DetailTable ref="detailTable" :honorTitle="honorTitle" :formId="formData.id" :dicData="props.dicData" /> -->
    <DetailTable ref="detailTable" :honorTitle="honorTitle" :formId="formData.id" :dicData="props.dicData"
      :formData="formData" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="saveForm" v-if="honorTitle !== '查看'" style="margin-right: 10px"
          v-loading="loadingsave">保存</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, watch, nextTick, computed } from "vue"
import * as MOSTY from "@/components/MyComponents/index"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { qrcodeImg, isString } from "@/utils/tools.js"
import DetailTable from "./XfzstzTable"
import { filterqx } from "@/utils/auth.js"
import { ElMessage } from "element-plus"
import { getItem } from "@/utils/storage"
const { proxy } = getCurrentInstance()
const props = defineProps({ title: String, query: Object, rowItem: Object, dicData: Object, reportStatus: String })
const dialogVisible = ref(false)
defineExpose({ dialogVisible })
const emits = defineEmits(["close"]);
const tableData = ref([])
const tableLoading = ref(false)
const loadingsave = ref(false)
const multipleTableRef = ref(null)
const listQuery = reactive({
  searchName: "",
  status: "",
  pageCurrent: 1,
  pageSize: 10,
  total: 0
})
const honorTitle = ref("")
const honorDialogVisible = ref(false)
const formData = ref({})
const rules = reactive({
  sitename: [{ required: true, message: "场所名称不能为空", trigger: "blur" }],
  siteaddress: [{ required: true, message: "场所地址不能为空", trigger: "blur" }],
  departmentname: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  hazardousfactors: [{ required: true, message: "危害因素不能为空", trigger: "blur" }]
})
const ruleFormRef = ref(null)
const detailTable = ref(null)
const multipleSelectionIds = ref([])
const reportSore = ref([])
const reportChange = reactive({
  notSourceIds: [],
  sourceIds: []
})
const tableIdsLength = ref(0)
const currentCode = getItem("deptId").ssdwid

//县级账号
const isTown = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") != "1" && filterqx("isSgs") != "1"
})
const gDisabled = computed(() => {
  return props.rowItem.status === "2" && props.query.orgCode.includes(currentCode) ? false : true
})
const onClose = () => {
  dialogVisible.value = false
  emits('close', true)
}
const onDelete = row => {
  getApi({}, `/mosty-jcgl/data/hazardPlace/delHazardPlace?sourceId=${row.sourceId}`).then(res => {
    if (res) {
      ElMessage({
        message: "删除成功",
        type: "success"
      })
      pageData()
    }
  })
}
const onRest = () => {
  listQuery.searchName = ""
  listQuery.status = ""
  listQuery.pageCurrent = 1
  listQuery.pageSize = 10
  listQuery.total = 0
  reportSore.value = []
  reportChange.sourceIds = []
  reportChange.notSourceIds = []
  pageData()
}
// 切换条数
const handleSizeChange = val => {
  listQuery.pageSize = val
  sorgeIds()
  getDataList()
}
// 切换分页
const handleCurrentChange = val => {
  listQuery.pageCurrent = val
  sorgeIds()
  getDataList()
}
const pageData = () => {
  tableLoading.value = true
  tableData.value = []
  tableIdsLength.value = 0
  let params = {
    orgCode: props.rowItem.orgCode,
    year: props.query.year,
    jd: props.query.jd
  }
  getApi({ ...listQuery, ...params }, "/mosty-jcgl/data/hazardPlace/detail/list")
    // postApi({ ...listQuery, ...params }, "/mosty-jcgl/data/hazardPlace/queryDataHazardPlaceStatics")
    .then(res => {
      if (res.records) {
        tableLoading.value = true
        listQuery.total = res.total

        res.records.forEach(item => {
          item.detectionLedgerList.forEach(list => {
            list.placeName = item.placeName
            list.status = item.status
            tableData.value.push(list)
          })
          if (item.detectionLedgerList.length === 0) {
            tableData.value.push({
              orgName: item.orgName,
              placeName: item.placeName,
              sourceId: item.sourceId,
              status: item.status,
              detectionLedgerList: []
            })
          }
          // tableData.value.push(item)
        })

        // pageConfiger.total = res.total;
        // res.records.forEach((item) => {
        //   item.hazardousfactors = item.hazardousfactors ? item.hazardousfactors.split(",") : null;
        // });
        // tableData.value = res.records;
        onMergeTable()

        nextTick(() => {
          // if (listQuery.status == "1") {
          tableData.value.forEach(item => {
            if (item.status === "1") {
              multipleTableRef.value.toggleRowSelection(item)
              if (!reportSore.value.includes(item.sourceId)) {
                reportSore.value.push(item.sourceId)
              }
              // if(!reportChange.sourceIds.includes(item.sourceId)) reportChange.sourceIds.push(item.sourceId)
            }
          })
          // }
        })
      }
    })
    .finally(() => {
      tableLoading.value = false
    })
}
//分页
const changeNo = val => {
  listQuery.pageCurrent = val
  pageData()
}
const changeSize = val => {
  listQuery.pageSize = val
  pageData()
}
const onEdit = e => {
  honorTitle.value = "编辑"
  honorDialogVisible.value = true
  // getApi({ id: e.id }, `/mosty-jcgl/occupationalHazard/queryOccupationalHazardById`).then(res => {
  //   res.hazardousfactors = res.hazardousfactors ? res.hazardousfactors.split(",") : null
  //   formData.value = res
  // })
  getApi({}, `/mosty-jcgl/data/hazardPlace/getEditDetailList?sourceId=${e.sourceId}`).then(res => {
    //
    if (res && res.length > 0) {
      formData.value = res[0] || res || {}
      detailTable.value.tableData = formData.value.detectionLedgerList || []
    }

    // res.hazardousfactors = res.hazardousfactors ? res.hazardousfactors.split(",") : null
    // formData.value = res
  })
}
const onView = e => {
  honorTitle.value = "查看"
  honorDialogVisible.value = true
  // postApi({sourceId:e.id}, `/mosty-jcgl/data/hazardPlace/getEditDetailList`).then(res => {
  getApi({}, `/mosty-jcgl/data/hazardPlace/getEditDetailList?sourceId=${e.sourceId}`).then(res => {
    //
    if (res && res.length > 0) {
      formData.value = res[0] || res || {}
      detailTable.value.tableData = formData.value.detectionLedgerList || []
    }

    // res.hazardousfactors = res.hazardousfactors ? res.hazardousfactors.split(",") : null
    // formData.value = res
  })
}
/** 替换 "XN" 为 空字符串 */
const replaceXn = val => {
  if (!val) return ''
  return val.replace('XN', '')
}
const onAdd = () => {
  honorTitle.value = "新增"
  honorDialogVisible.value = true
  formData.value = {
    orgCode: props.rowItem.orgCode,
    orgName: props.rowItem.orgName,
    // statId: props.rowItem.id,
    // reportingYear: props.rowItem.reportingYear,
    // reportCycleCode: String(props.rowItem.reportCycleCode || '')
  }
}
const onMergeTable = () => {
  nextTick(() => {
    /** 职业危害场所列 */
    let colnumIndex = 4,
      tableFirstTd = "",
      tableCurrentTd = "",
      /** 需要合并的行数 */
      tableSpanNum = 0,
      tableTdArr = document.querySelectorAll("#mergeTable .el-table__body tr td:nth-child(" + colnumIndex + ")"),

      // 以下操作列=====
      tableFirstOperTd = "",
      /** 当前操作列 */
      tableCurrOperaTd = "",
      /**操作列 9代表第9列 */
      operaTdArr = document.querySelectorAll("#mergeTable .el-table__body tr td:nth-child(" + 9 + ")");

    for (let i = 0; i < tableTdArr.length; i++) {
      if (i === 0) {
        tableFirstTd = tableTdArr[0]
        tableFirstOperTd = operaTdArr[0]
        tableSpanNum = 1
      } else {
        tableCurrentTd = tableTdArr[i]
        tableCurrOperaTd = operaTdArr[i]
        if (tableFirstTd.innerText === tableCurrentTd.innerText) {
          tableSpanNum++
          tableCurrentTd.style.display = "none"
          tableFirstTd.setAttribute("rowSpan", tableSpanNum)

          tableCurrentTd.previousSibling.style.display = "none"
          tableFirstTd.previousSibling.setAttribute("rowSpan", tableSpanNum)
          tableCurrentTd.previousSibling.previousSibling.style.display = "none"
          tableFirstTd.previousSibling.previousSibling.setAttribute("rowSpan", tableSpanNum)
          tableCurrentTd.previousSibling.previousSibling.previousSibling.style.display = "none"
          tableFirstTd.previousSibling.previousSibling.previousSibling.setAttribute("rowSpan", tableSpanNum)

          /**操作列合并,保持和之前一致
           * @param {Object} currTdEle 当前ele
           * @param {Object} firstTd 第一个需要合并的元素
           */
          const setOperColSpan = (currTdEle, firstTd) => {
            currTdEle.style.display = "none"
            firstTd.setAttribute("rowSpan", tableSpanNum)
          }
          setOperColSpan(tableCurrOperaTd, tableFirstOperTd)
        } else {
          tableFirstTd = tableTdArr[i]
          tableSpanNum = 1
          tableFirstOperTd = operaTdArr[i] // 操作列和之前一致
        }
      }
    }

    let count = 0
    let tableFirstTdArr = document.querySelectorAll("#mergeTable .el-table__body tr td:nth-child(" + 2 + ")")
    tableFirstTdArr.forEach(item => {
      if (item.style.display !== "none") {
        count++
        item.innerHTML = `<div>${count}</div>`
      }
    })
    tableIdsLength.value = count
  })
}
const saveForm = async () => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      loadingsave.value = true
      // formData.value.hazardousfactors = formData.value.hazardousfactors ? formData.value.hazardousfactors.toString() : ''
      formData.value.detectionLedgerList = detailTable.value.tableData

      const url = honorTitle.value.includes('新增') ? "/mosty-jcgl/data/hazardPlace/addHazardPlace" : '/mosty-jcgl/data/hazardPlace/editHazardPlace'
      postApi(formData.value, url)
        .then(res => {
          proxy.$message.success("保存成功")
          honorDialogVisible.value = false
          if (detailTable.value) detailTable.value.clearData()
          pageData()
        })
        .finally(() => {
          loadingsave.value = false
          //
        })
    }
  })
}
function closeDialog(params) {
  if(!ruleFormRef.value) return
  if (honorTitle.value !== '查看') {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        honorDialogVisible.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    honorDialogVisible.value = false
  }
}
const onSelectionChange = val => {
  nextTick(() => {
    let tableTdArr = document.querySelectorAll("#mergeTable .el-table__body tr td:nth-child(" + 1 + ")")
    let ids = []
    tableTdArr.forEach((item, i) => {
      // && item.querySelector('.el-checkbox').classList.contains('is-checked')
      if (item.style.display !== "none") {
        if (item.querySelector(".el-checkbox").classList.contains("is-checked")) {
          let id = tableData.value[i].sourceId
          if (!ids.includes(id)) ids.push(id)
        }
      }
    })
    multipleSelectionIds.value = ids

    let dom = document.querySelector("#mergeTable .el-table__header tr th:nth-child(1) .el-checkbox__input")
    if (!dom) return
    if (multipleSelectionIds.value.length === tableIdsLength.value) {
      // multipleTableRef.value.toggleRowSelection()
      dom.classList.add("is-checked")
      dom.classList.remove("is-indeterminate")
    } else {
      if (multipleSelectionIds.value.length === 0) {
        dom.classList.remove("is-checked")
      } else if (multipleSelectionIds.value.length < tableIdsLength.value && multipleSelectionIds.value.length > 0) {
        dom.classList.add("is-indeterminate")
      }
    }
  })
}
const sorgeIds = () => {
  multipleSelectionIds.value.forEach(sourceId => {
    if (!reportChange.sourceIds.includes(sourceId)) reportChange.sourceIds.push(sourceId)
  })
  reportChange.notSourceIds = reportSore.value.filter(sourceId => !reportChange.sourceIds.includes(sourceId))
}
const changeStatus = e => {
  pageData()
}
const onStagingReport = () => {
  sorgeIds()
  postApi({ ...reportChange, ...props.query, orgCode: props.rowItem.orgCode }, "/mosty-jcgl/data/hazardPlace/stagingReportData")
    .then(res => {
      if (res) {
        ElMessage({
          message: "暂存上报数据成功",
          type: "success"
        })
        onRest()
      }
    })
    .finally(() => {
      reportChange.sourceIds = []
      reportChange.notSourceIds = []
    })
}
// onMounted(() => {});
watch(
  () => dialogVisible.value,
  (n, o) => {
    if (n) {
      listQuery.status = props.reportStatus
      pageData()
    }
  },
  { deep: true }
  // { immediate: true, deep: true }
)
</script>

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

.mosty-from-wrap {
  align-items: center;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin: 10px auto;


}
</style>
