<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">
          <el-icon>
            <Plus />
          </el-icon>新增</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" width="250" />
        <el-table-column label="应急预案名称" prop="emergencyPlanName" width="120" />
        <el-table-column label="应对风险类别" prop="accidentCategoryName" width="120" />
        <el-table-column label="实战演练数量" property="actualDrillQty"></el-table-column>
        <el-table-column label="实战演练参与人员数量" property="actualDrillPersonQty"></el-table-column>
        <el-table-column label="桌面推演数量" property="desktopDeducQty"></el-table-column>
        <el-table-column label="桌面推演参与人员数量" property="desktopDeducPersonQty"></el-table-column>
        <el-table-column label="演练评估次数" property="emergencyDrillEvaluationQty"></el-table-column>
        <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)">编辑</el-link>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
              @confirm="onDel(row)">
              <template #reference>
                <span style="color: red;" size="small"> 删除</span>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="flex just-center">
      <MOSTY.Pages :pageConfiger="listQuery" @changeNo="changeNo" @changeSize="changeSize"></MOSTY.Pages>
    </div>
  </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="115px" :model="formData" :inline="true"
      :rules="rules" :disabled="honorTitle === '查看'">
      <el-form-item label="应急预案名称:" prop="emergencyPlanName">
        <el-input v-model="formData.emergencyPlanName" placeholder="请输入应急预案名称" style="width: 250px"></el-input>
      </el-form-item>
      <el-form-item label="统计年度" prop="reportingYear">
        <el-select clearable v-model="formData.reportingYear" style="width: 250px">
          <el-option v-for="item in filterYear(5)" :key="item.value" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上报季度" prop="reportCycleCode">
        <el-select clearable placeholder="请选择季度" v-model="formData.reportCycleCode" :disabled="honorTitle !== '新增'">
          <el-option v-for="item in props.dicData.D_BZ_QUARTER" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="应急预案类别" prop="emergencyPlanCategoryCode">
        <MOSTY.DictRidioAndSelect :dictData="props.dicData.D_BYJYALBDM" v-model="formData.emergencyPlanCategoryCode"
          selectType="select" style="width: 250px" @getselect="onChange1" />
      </el-form-item>
      <el-form-item label="应对风险类别" prop="accidentCategoryCode" v-if="formData.emergencyPlanCategoryCode === '1'">
        <MOSTY.DictRidioAndSelect :dictData="[{ label: '综合', value: '综合' }]" v-model="formData.accidentCategoryCode"
          selectType="select" style="width: 250px" @onChange="onChange2" :multiple="true" />
      </el-form-item>
      <el-form-item label="应对风险类别" prop="accidentCategoryCode"
        v-if="['2'].includes(formData.emergencyPlanCategoryCode)">
        <el-cascader v-model="formData.accidentCategoryCode" :options="specialDangerOptsComputed"
          :props="specialDangerProps" collapseTags clearable @change="onChange2" />
      </el-form-item>
      <el-form-item label="应对风险类别" prop="accidentCategoryCode"
        v-if="['3'].includes(formData.emergencyPlanCategoryCode)">
        <MOSTY.DictRidioAndSelect :dictData="props.dicData.D_BZ_KNZCDSGLB" autoDel
          v-model="formData.accidentCategoryCode" selectType="select" :multiple="true" style="width: 250px"
          @onChange="onChange3" />
      </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" style="width: 250px">
        </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%">
        <div class="erweim">
          <img :src="qrcodeImg(formData.id, 'S', '应急预案二维码')" alt="" id="htmlsmewmzywhcs" />
          <el-link @click="onloadewm1(formData)">点击下载应急预案二维码图片</el-link>
        </div>
      </el-form-item> -->
    </el-form>
    <!-- <MOSTY.Assort :title="'检查记录'" /> -->
    <DetailTable ref="detailTable" v-if="honorDialogVisible" :honorTitle="honorTitle" :sourceId="formData.sourceId"
      :dicData="props.dicData" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="saveForm" v-loading="butLoading" v-if="honorTitle !== '查看'"
          style="margin-right: 10px">保存</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 DetailTable from "./XfzstzTable"
import { filterqx } from "@/utils/auth.js"
import { ElMessage } from "element-plus"
import { getItem } from "@/utils/storage"
import { filterYear } from "@/utils/auth.js";
import { isString } from '@/utils/tools.js';
const emits = defineEmits(["close"])
const { proxy } = getCurrentInstance() //

const props = defineProps({ title: String, query: Object, rowItem: Object, dicData: Object, reportStatus: String })
const dialogVisible = ref(false)
defineExpose({ dialogVisible })
const tableData = ref([])
const butLoading = ref(false)
const tableLoading = ref(false)
const pageConfiger = reactive({
  pageSize: 10,
  pageCurrent: 1,
  total: 0
})
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({
  emergencyPlanName: [{ required: true, message: "应急预案名称不能为空", trigger: "blur" }],
  emergencyPlanCategoryCode: [{ required: true, message: "应急预案类别不能为空", trigger: "blur" }],
  accidentCategoryCode: [{ 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 specialDangerOpts = ref([])
const specialDangerOptsComputed = computed(() => {
  const first = formData.value.accidentCategoryCode?.[0]
  /** 禁用父级 */
  let disabeldParentStr = first?.[0]
  return specialDangerOpts.value.map(item => {
    if (disabeldParentStr === '00') {
      if (item.value > 19) item.disabled = true
    } else if (disabeldParentStr === '20') {
      if (item.value < 20 || item.value == '00') item.disabled = true
    } else {
      item.disabled = false
    }
    return item
  })

})
/** 获取字典树 */
const getDicTree = (zdbh) => {
  return new Promise((resolve, reject) => {
    getApi({ zdbh: zdbh, }, "/mosty-base/sysDict/getDictTree").then(res => {
      const toNeedArr = (arr) => {
        if (!Array.isArray(arr)) return []
        return arr.map(item => {
          return {
            label: item.zdmc,
            value: item.dm,
            children: toNeedArr(item.itemList)
          }
        })
      }
      const treeArr = toNeedArr(res.itemList)
      resolve(treeArr)
    })
  })
}
const specialDangerProps = { multiple: true }
const currentCode = getItem("deptId").ssdwid

const tableIdsLength = ref(0)
//县级账号
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 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()
  pageData()
}
// 切换分页
const handleCurrentChange = val => {
  listQuery.pageCurrent = val
  sorgeIds()
  pageData()
}
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/emergencyPlanInfo/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 => {
          if (item.drills.length > 0) {
            item.drills.forEach(list => {
              list.emergencyPlanCategoryCode = item.emergencyPlanCategoryCode
              list.emergencyPlanCategoryName = item.emergencyPlanCategoryName
              list.accidentCategoryName = item.accidentCategoryName
              list.accidentCategoryCode = item.accidentCategoryCode
              list.id = item.id
              list.sourceId = item.sourceId
              tableData.value.push({ status: item.status, ...list, orgName: item.orgName || list.baOrgCode })
            })
          } else {
            tableData.value.push(item)
          }

        })

        onMergeTable()

        nextTick(() => {
          tableData.value.forEach(item => {
            if (item.status === "1") {
              multipleTableRef.value.toggleRowSelection(item, true)
              if (!reportSore.value.includes(item.sourceId)) {
                reportSore.value.push(item.sourceId)
              }
            }
          })
          // }
        })

        return

        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") {
              if (!reportSore.value.includes(item.sourceId)) {
                reportSore.value.push(item.sourceId)
                multipleTableRef.value.toggleRowSelection(item)
              }
              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 closeDialog = () => {
  if (honorTitle.value !== '查看') {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        honorDialogVisible.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    honorDialogVisible.value = false
  }

};
const onAdd = () => {
  formData.value = {
    baOrgCode: props.rowItem.baOrgCode,
    baOrgName: props.rowItem.baOrgName,
    orgCode: props.rowItem.orgCode && props.rowItem.orgCode.replace('XN', ''),
    orgName: props.rowItem.orgName,
    statId: props.rowItem.id,
    reportingYear: props.rowItem.reportingYear, // 默认当年
    reportCycleCode: String(props.rowItem.reportCycleCode || '')
  }
  honorTitle.value = "新增"
  honorDialogVisible.value = true
  nextTick(() => {
    detailTable.value.tableData = []
  })

}
const onEdit = e => {
  honorTitle.value = "编辑"
  formData.value = {
    ...e,
    reportCycleCode: e.reportCycleCode ? e.reportCycleCode.toString() : null,
  }
  formData.value.hazardousfactors = formData.value.hazardousfactors ? formData.value.hazardousfactors.split(",") : null
  formData.value.accidentCategoryCode = isString(formData.value.accidentCategoryCode) ? formData.value.accidentCategoryCode.split(",") : formData.value.accidentCategoryCode
  // formData.value.reportCycleCode = formData.value.reportCycleCode ? formData.value.reportCycleCode.toString() : null
  honorDialogVisible.value = true


}
const onView = e => {
  honorTitle.value = "查看"
  formData.value = e
  formData.value.hazardousfactors = formData.value.hazardousfactors ? formData.value.hazardousfactors.split(",") : null
  formData.value.accidentCategoryCode = isString(formData.value.accidentCategoryCode) ? formData.value.accidentCategoryCode.split(",") : formData.value.accidentCategoryCode
  formData.value.reportCycleCode = formData.value.reportCycleCode ? formData.value.reportCycleCode.toString() : null
  honorDialogVisible.value = true
}

const onDel = e => {
  postApi({}, `/mosty-jcgl/data/emergencyPlanInfo/del?sourceId=${e.sourceId}`).then(res => {
    ElMessage.success("删除成功")
    pageData()
  })
}

const onMergeTable = () => {
  nextTick(() => {
    let colnumIndex = 4,
      tableFirstTd = "",
      tableCurrentTd = "",
      tableSpanNum = 0,
      tableTdArr = document.querySelectorAll("#mergeTable .el-table__body tr td:nth-child(" + colnumIndex + ")")

    for (let i = 0; i < tableTdArr.length; i++) {
      if (i === 0) {
        tableFirstTd = tableTdArr[0]
        tableSpanNum = 1
      } else {
        tableCurrentTd = tableTdArr[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)
          tableCurrentTd.nextSibling.style.display = "none"
          tableFirstTd.nextSibling.setAttribute("rowSpan", tableSpanNum)
          // tableCurrentTd.previousSibling.previousSibling.previousSibling.previousSibling.style.display = "none"
          // tableFirstTd.previousSibling.previousSibling.previousSibling.previousSibling.setAttribute("rowSpan", tableSpanNum)
          tableCurrentTd.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.style.display = "none"
          tableFirstTd.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.setAttribute("rowSpan", tableSpanNum)
        } else {
          tableFirstTd = tableTdArr[i]
          tableSpanNum = 1
        }
      }
    }

    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 onChange1 = val => {
  formData.value.emergencyPlanCategoryCode = val.value
  formData.value.emergencyPlanCategoryName = val.label
  formData.value.accidentCategoryCode = ""
  formData.value.accidentCategoryName = ""
}
const onChange2 = (e, val) => {
  let startLabel = ''
  let endLabel = ''
  let num = ''
  e.forEach((itemEs, index) => {
    specialDangerOpts.value.forEach(items => {
      if (items.value === itemEs[0]) {
        if (items.value === '00') num = parseInt(itemEs[1]) - 1
        if (items.value === '20') num = parseInt(itemEs[1]) - 21
        if (index === 0) startLabel = items.label
        endLabel = endLabel + '-' + items.children[num].label
      }
    })
  })
  formData.value.accidentCategoryName = startLabel + endLabel 
  formData.value.accidentCategoryCode = e
}
const onChange3 = (e, val) => {
  formData.value.accidentCategoryCode = e
  formData.value.accidentCategoryName = val.toString()
}
const saveForm = async () => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      butLoading.value = false

      // formData.value.accidentCategoryCode = formData.value.accidentCategoryCode ? formData.value.accidentCategoryCode.toString() : ''
      formData.value.drills = detailTable.value.tableData
      formData.value.baOrgCode = props.rowItem.baOrgCode
      formData.value.orgCode = props.rowItem.orgCode
      const params = {
        ...formData.value,
        accidentCategoryCode: formData.value.accidentCategoryCode ? formData.value.accidentCategoryCode.toString() : ''
      }
      if (honorTitle.value.includes("新增")) {

        postApi(params, "/mosty-jcgl/data/emergencyPlanInfo/add")
          .then(res => {
            proxy.$message.success("新增成功")
            honorDialogVisible.value = false
            pageData()
          })
          .finally(() => {
            butLoading.value = false
          })
      }
      if (honorTitle.value.includes("编辑")) {

        postApi(params, "/mosty-jcgl/data/emergencyPlanInfo/editPlan")
          .then(res => {
            proxy.$message.success("保存成功")
            honorDialogVisible.value = false
            pageData()
          })
          .finally(() => {
            butLoading.value = false
          })
      }
    }
  })
}

const onSelectionChange = val => {
  let ids = []
  val.forEach(item => {
    if (!item) return
    if (!ids.includes(item.sourceId)) ids.push(item.sourceId)
  })
  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/emergencyPlanInfo/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 }
)

onMounted(() => {
  getDicTree("D_BZ_ACCIDENT_TYPE").then(res => {
    specialDangerOpts.value = res || []
  })
})

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