<template>
  <el-dialog :title="`相关方管理列表（${props.title}）`" width="1400px" v-model="dialogVisible" @close="onClose">
    <!--<el-input placeholder="请输入危险化学品名称" v-model="listQuery.searchName" @clear="pageData" clearable style="width: 250px; margin: 0 10px 10px 0" />
    <el-button type="primary" @click="pageData"
      ><el-icon>
        <Search />
      </el-icon>
      查询
    </el-button>-->
    <el-button @click="onAdd" style="float: right; margin-bottom: 10px" v-if="!route.query.reportView">
      <el-icon>
        <Plus />
      </el-icon>新增</el-button>
    <el-table border :data="tableData" ref="multipleTableRef" id="mergeTable" style="width: 100%" highlight-current-row
      :header-cell-style="{ background: '#F6F6F6' }" v-loading="tableLoading" height="550px">
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column label="序号" type="index" align="center" width="80" />
      <el-table-column label="企业名称" prop="baOrgName" align="center" width="200"> </el-table-column>
      <el-table-column label="相关方名称" prop="rpName" align="center" width="100"></el-table-column>
      <el-table-column label="相关方业务类型" prop="businessTypeName" align="center" width="160"></el-table-column>
      <el-table-column label="进场人员" prop="entryQty" align="center" width="100"></el-table-column>
      <el-table-column label="是否签订安全协议" prop="secProtocolFlag" align="center" width="180">
        <template #default="{ row }">
          {{ row.secProtocolFlag === 1 ? "是" : "否" }}
        </template>
      </el-table-column>

      <el-table-column label="是否具备相应的单位资质" prop="qualificationFlag" align="center" width="180">
        <template #default="{ row }">
          {{ row.qualificationFlag === 1 ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="是否常驻相关方" prop="permanenFlag" align="center" width="180">
        <template #default="{ row }">
          {{ row.permanenFlag === 1 ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="是否涉及危险作业" prop="involveHazardQpsFlag" align="center" width="180">
        <template #default="{ row }">
          {{ row.involveHazardQpsFlag === 1 ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <!-- v-if="!route.query.reportView" -->
          <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 class="operdel" size="small"> 删除</span>
            </template>
          </el-popconfirm>
          <!-- <el-link type="primary" @click="onEdit(row)" style="margin-right: 10px">编辑</el-link>
          <el-link type="primary" @click="onView(row)">查看</el-link> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="flex just-center">
      <Pages :pageConfiger="listQuery" @changeNo="changeNo" @changeSize="changeSize"></Pages>
    </div>
  </el-dialog>

  <el-dialog :title="'相关方管理' + honorTitle" width="1200px" v-model="honorDialogVisible" :before-close="closeDialog">
    <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="210px" :model="fromObj" :inline="true"
      :rules="rules" :disabled="honorTitle === '查看'">
      <el-form-item label="相关方名称:" prop="rpName">
        <el-input v-model="fromObj.rpName" placeholder="请输入相关方名称" style="width: 280px"></el-input>
      </el-form-item>
      <!-- <el-form-item label="年份:" prop="yearly">
        <el-date-picker v-model="fromObj.yearly" type="year" placeholder="选择年份" style="width: 280px" value-format="YYYY"> </el-date-picker>
      </el-form-item>
      <el-form-item label="备注:" style="width: 100%">
        <el-input v-model="fromObj.bz" type="textarea" show-word-limit maxlength="200" style="width: 920px" />
      </el-form-item> -->
    </el-form>
    <MOSTY.Assort :title="'相关方'" />
    <DetailTable ref="detailTable" :honorTitle="honorTitle" :query="props.query" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="saveForm" v-if="honorTitle !== '查看'">保存</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, watch, nextTick } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { ElMessage } from "element-plus"
import Pages from "@/components/aboutTable/Pages/index.vue"
const { proxy } = getCurrentInstance()
const props = defineProps({ title: String, query: Object, rowItem: Object })
const { D_BZ_SF } = proxy.$dict("D_BZ_SF")
import * as rule from "@/utils/rules.js"
import DetailTable from "./XfzstzTable"
import { useRoute } from "vue-router"
const route = useRoute()
const dialogVisible = ref(false)
defineExpose({ dialogVisible })
const tableData = ref([])
const tableLoading = ref(false)
const pageConfiger = reactive({
  pageSize: 10,
  pageCurrent: 1,
  total: 0
})
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 10,
  total: 0,
  searchName: ""
})
const multipleTableRef = ref(null)
const honorTitle = ref("")
const honorDialogVisible = ref(false)
const fromObj = ref({})
const emit = defineEmits(["close"]);

const onClose = () => {
  dialogVisible.value = false
  emit("close")
}

const ruleFormRef = ref(null)
const detailTable = ref(null)
const rules = reactive({
  rpName: [{ required: true, message: "相关方名称不能为空", trigger: "blur" }]
  // siteaddress: [{ required: true, message: "场所地址不能为空", trigger: "blur" }],
  // departmentname: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  // hazardousfactors: [{ required: true, message: "危害因素不能为空", trigger: "blur" }]
})
const pageData = () => {
  tableLoading.value = true
  tableData.value = []
  let params = {
    orgcode: props.rowItem.orgCode,
    year: props.query.year,
    jd: props.query.jd
  }
  getApi({ ...listQuery, ...params }, "/mosty-jcgl/data/rpInfo/detail/list")
    .then(res => {
      if (res) {
        listQuery.total = res.total
        res.records.forEach(item => {
          item.rpTypeList.forEach(list => {
            list.rpName = item.rpName
            tableData.value.push(list)
          })
          // let name = ''
          // let entryQty = 0
          // item.rpTypeList.forEach((list, index) => {
          //   name = list.businessTypeName + ' ' + name
          //   entryQty = list.entryQty > entryQty ? list.entryQty : entryQty
          //   if (index === item.rpTypeList.length - 1) {
          //     list.rpName = item.rpName
          //     list.businessTypeName = name
          //     list.entryQty = entryQty
          //     tableData.value.push(list)
          //   }
          // })
          if (item.rpTypeList.length === 0) {
            tableData.value.push(item)
          }
        })

        onMergeTable()
      }
    })
    .finally(() => {
      tableLoading.value = false
    })
}

const onMergeTable = () => {
  nextTick(() => {
    let colnumIndex = 3,
      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.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(" + 1 + ")")
    tableFirstTdArr.forEach(item => {
      if (item.style.display !== "none") {
        count++
        item.innerHTML = `<div>${count}</div>`
      }
    })
  })
}
//分页
const changeNo = val => {
  listQuery.pageCurrent = val
  pageData()
}
const changeSize = val => {
  listQuery.pageSize = val
  pageData()
}
const onView = e => {
  honorTitle.value = "查看"
  honorDialogVisible.value = true
  getApi({ id: e.sourceId }, "/mosty-jcgl/data/hazardChemicalInfo/chemical/detail").then(res => {
    if (res) {
      res.cmHighlyToxicFlag = res.cmHighlyToxicFlag === 1 ? "1" : "2"
      res.cmEasyMakeToxicFlag = res.cmEasyMakeToxicFlag === 1 ? "1" : "2"
      res.cmEasyMakeExplosiveFlag = res.cmEasyMakeExplosiveFlag === 1 ? "1" : "2"
      res.cmMajorHazardFlag = res.cmMajorHazardFlag === 1 ? "1" : "2"
      res.cmHazchemListFlag = res.cmHazchemListFlag === 1 ? "1" : "0"
      res.cmHazardProcessFlag = res.cmHazardProcessFlag === 1 ? "1" : "0"

      fromObj.value = res
    }
  })
}
const onAdd = () => {
  honorTitle.value = "新增"
  honorDialogVisible.value = true
  fromObj.value.rpName = ""
  nextTick(() => {
    detailTable.value.tableData = []
  })

}

const onEdit = e => {
  honorTitle.value = "编辑"
  honorDialogVisible.value = true

  postApi({}, `/mosty-jcgl/data/rpInfo/queryRpInfo?sourceId=${e.sourceId}`).then(res => {
    if (res) {
      fromObj.value = res
      res.rpTypeList.forEach(item => {
        item.secProtocolFlag += ''
        item.qualificationFlag += ''
        item.permanenFlag += ''
        item.involveHazardQpsFlag += ''

      })
      detailTable.value.tableData = res.rpTypeList
    }

  })
}
const onDel = e => {
  // /
  postApi({}, `/mosty-jcgl/data/rpInfo/delRpInfo?sourceId=${e.sourceId}`).then(res => {
    ElMessage.success("删除成功")
    pageData()
  })
}
const saveForm = async () => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      fromObj.value.rpTypeList = detailTable.value.tableData
      fromObj.value.orgCode = props.rowItem.orgCode
      fromObj.value.orgName = props.rowItem.orgName
      let isXTarr = fromObj.value.rpTypeList.map((item) => { return item.businessTypeCode })
      if (new Set(isXTarr).size !== isXTarr.length) return ElMessage.error("业务类型数据重复，请重新选择业务类型")
      if (honorTitle.value.includes("新增")) {
        fromObj.value.reportingYear = props.query.year
        fromObj.value.reportCycleCode = props.query.jd
        postApi(fromObj.value, "/mosty-jcgl/data/rpInfo/addRpInfo")
          .then(res => {
            proxy.$message.success("新增成功")
            honorDialogVisible.value = false
            pageData()
          })
          .finally(() => {
            // butLoading.value = false
          })
      }
      if (honorTitle.value.includes("编辑")) {
        nextTick(() => {
          fromObj.value["rpTypeList"] = detailTable.value.tableData
          postApi(fromObj.value, "/mosty-jcgl/data/rpInfo/editRpInfo")
            .then(res => {
              proxy.$message.success("保存成功")
              honorDialogVisible.value = false
              pageData()
            })
            .finally(() => {
              // butLoading.value = false
            })
        })
      }

    }
  })
}

onMounted(() => { });
watch(
  () => dialogVisible.value,
  (n, o) => {
    if (n) {
      pageData()
    }
  },
  { deep: true }
  // { immediate: true, deep: true }
);

const closeDialog = () => {
  if (honorTitle.value !== '查看') {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        honorDialogVisible.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    honorDialogVisible.value = false
  }

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