<template>
  <el-button class="addbtn" type="primary" @click="addjcjl" style="margin-bottom: 10px"
    v-if="props.honorTitle !== '查看'">
    <el-icon>
      <CirclePlus />
    </el-icon>
    <span>新增</span>
  </el-button>

  <el-table ref="multipleTableRef" stripe :data="currPageTableData" style="width: 100%" height="30vh" border
    v-loading="tableLoading">
    <el-table-column label="业务类型" property="businessTypeCode">
      <template #default="{ row }">
        <dict-tag :options="D_TB_RELATED" :value="row.businessTypeCode" :tag="false" />
      </template>
    </el-table-column>
    <el-table-column label="进场人数" property="entryQty"></el-table-column>
    <el-table-column label="是否签订安全协议标识" property="secProtocolFlag">
      <template #default="{ row }">
        <dict-tag :options="D_BZ_SF" :value="row.secProtocolFlag" :tag="false" />
      </template>
    </el-table-column>
    <el-table-column label="是否常驻标识" property="permanenFlag">
      <template #default="{ row }">
        <dict-tag :options="D_BZ_SF" :value="row.permanenFlag" :tag="false" />
      </template>
    </el-table-column>
    <el-table-column label="是否具备相应的单位资质" property="qualificationFlag">
      <template #default="{ row }">
        <dict-tag :options="D_BZ_SF" :value="row.qualificationFlag" :tag="false" />
      </template>
    </el-table-column>
    <el-table-column label="是否涉及危险作业标识" property="involveHazardQpsFlag">
      <template #default="{ row }">
        <span>{{ row.involveHazardQpsFlag === 1 ? "是" : "否" }}</span>
      </template>
    </el-table-column>

    <el-table-column label="操作" width="150px">
      <template #default="scope">
        <!-- <span class="operedit" v-if="props.honorTitle !== '查看'" @click="handleCbj(scope.row, scope.$index)">
          <el-icon> <EditPen /> </el-icon>修改</span
        > -->
        <span class="operedit" v-if="props.honorTitle === '编辑'" @click="handleCbj(scope.row)">
          <el-icon>
            <EditPen />
          </el-icon>修改</span>
        <el-popconfirm v-if="props.honorTitle !== '查看'" confirm-button-text="是" cancel-button-text="否" icon-color="red"
          title="确定要删除?" @confirm="delRow(scope.row, scope.$index)">
          <template #reference>
            <span class="operdel" size="small">
              <el-icon>
                <Delete />
              </el-icon>
              删除</span>
          </template>
        </el-popconfirm>
        <!-- <span class="operesee" @click="handleCbjxq(scope.row, scope.$index)"
          ><el-icon> <Compass /> </el-icon>查看</span
        > -->
      </template>
    </el-table-column>
  </el-table>
  <div class="flex just-center">
    <Pages :pageConfiger="pageConfiger" @changeNo="changeNo" @changeSize="changeSize"></Pages>
  </div>

  <el-dialog :title="jltitle" width="1200px" v-model="dialogVisible" :before-close="closeDialog">
    <!-- 培训计划新增或修改 -->
    <!-- <div class="config"> -->
    <el-form ref="fromRuls" :disabled="jltitle.includes('详情')" :model="ruleForm" :rules="rules" :inline="true"
      label-width="180px" class="mosty-from-wrap">
      <el-form-item label="业务类型:" prop="businessTypeCode">
        <el-select v-model="ruleForm.businessTypeCode" placeholder="请选择业务类型" style="width: 250px">
          <el-option v-for="item in D_TB_RELATED" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="进场人数:" prop="entryQty">
        <el-input v-model="ruleForm.entryQty" type="number" placeholder="请输入进场人数" style="width: 250px"></el-input>
      </el-form-item>
      <el-form-item label="是否签订安全协议标识:" prop="secProtocolFlag">
        <el-select v-model="ruleForm.secProtocolFlag" placeholder="请选择是否签订安全协议标识" style="width: 250px">
          <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否具备相应的单位资质:" prop="qualificationFlag">
        <el-select v-model="ruleForm.qualificationFlag" placeholder="请选择是否具备相应的单位资质" style="width: 250px">
          <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否常驻标识:" prop="permanenFlag">
        <el-select v-model="ruleForm.permanenFlag" placeholder="请选择是否常驻标识" style="width: 250px">
          <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否涉及危险作业标识:" prop="involveHazardQpsFlag">
        <el-select v-model="ruleForm.involveHazardQpsFlag" placeholder="请选择是否涉及危险作业标识" style="width: 250px">
          <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <!-- </div> -->

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSave" v-if="!jltitle.includes('详情')" style="margin-right: 10px"
          v-loading="loadingshow">
          <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span>
        </el-button>
        <el-button @click="closeDialog" type="primary">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span>
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, watch, nextTick, computed } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import Pages from "@/components/aboutTable/Pages/index.vue"
import { disablednowDate } from "@/utils/tools.js"
import { ElMessage } from "element-plus"
import * as MOSTY from "@/components/MyComponents/index"
import * as rule from "@/utils/rules.js"
// import { query } from "express"
const { proxy } = getCurrentInstance()
const { D_TB_RELATED, D_BZ_SF } = proxy.$dict("D_TB_RELATED", "D_BZ_SF")
const props = defineProps({
  honorTitle: String,
  formId: String,
  dicData: Object,
  formData: Object,
  query: Object
})
const dialogVisible = ref(false)
const tableData = ref([])
const tableLoading = ref(false)
const pageConfiger = ref({
  pageSize: 5,
  pageCurrent: 1,
  total: 0
})
const listQuery = reactive({
  // occupationalHazardId: props.formId,
  pageCurrent: 1,
  pageSize: 5
})
const jltitle = ref("")
const ruleForm = ref({})
const loadingshow = ref(false)
const fromRuls = ref(null)
const _D_TB_ZYJK_WHYS = [
  {
    value: "1",
    label: "粉尘"
  },
  {
    value: "2",
    label: "噪声"
  },
  {
    value: "3",
    label: "高温"
  },
  {
    value: "9",
    label: "其他"
  }
]

//规则校验
const rules = reactive({
  businessTypeCode: [{ required: true, message: "业务类型不能为空", trigger: "blur" }],
  secProtocolFlag: [{ required: true, message: "是否签订安全协议标识不能为空", trigger: "change" }],
  permanenFlag: [{ required: true, message: "是否常驻标识不能为空", trigger: "change" }],
  qualificationFlag: [{ required: true, message: "是否具备相应的单位资质不能为空", trigger: "change" }],
  involveHazardQpsFlag: [{ required: true, message: "是否涉及危险作业标识不能为空", trigger: "change" }],
  ...rule.numberzzsRule({ validator: true, require: true, num: 9999999 }, "entryQty")
})
defineExpose({ tableData })

const closeDialog = () => {
  if (!jltitle.value.includes('详情')) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        tableData.value = JSON.parse(JSON.stringify(tableData.value))
        dialogVisible.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    tableData.value = JSON.parse(JSON.stringify(tableData.value))
    dialogVisible.value = false
  }

}
function closeDialogs() {
  tableData.value = JSON.parse(JSON.stringify(tableData.value))
  dialogVisible.value = false
}
const localSetDataByPage = () => {

}
/** 本地分页 */
const currPageTableData = computed(() => {
  return tableData.value.slice((pageConfiger.value.pageCurrent - 1) * pageConfiger.value.pageSize, pageConfiger.value.pageCurrent * pageConfiger.value.pageSize)
})
const getTableData = () => {
  return
  tableLoading.value = true
  postApi(listQuery, "/mosty-jcgl/OccupationalHazardCheckRecords/queryTbOccupationalHazardCheckRecordsByOccupationalHazardId").then(res => {
    if (res.records) {
      tableLoading.value = false
      tableData.value = res.records
      pageConfiger.value.total = res.total
    } else {
      tableData.value = []
      tableLoading.value = false
    }
  })
}
const changeNo = val => {
  listQuery.pageCurrent = val
  pageConfiger.value.pageCurrent = val
  getTableData()
}
const changeSize = val => {
  listQuery.pageSize = val
  pageConfiger.value.pageSize = val
  getTableData()
}
function addjcjl() {
  jltitle.value = "相关方新增"
  dialogVisible.value = true

  nextTick(() => {
    fromRuls.value.resetFields()
    fromRuls.value.clearValidate()
    ruleForm.value = {
      file: null
    }
  })
}
function handleCbj(row, index) {
  jltitle.value = "相关方修改"
  dialogVisible.value = true
  ruleForm.value = row
  // jltitle.value = "相关方修改"
  // dialogVisible.value = true
  // // ruleForm.value = row;
  // getApi({}, `/mosty-jcgl/OccupationalHazardCheckRecords/getTbOccupationalHazardCheckRecordsById/${row.id}`).then(res => {
  //   if (res) {
  //     ruleForm.value = res
  //   }
  // })
}
function handleCbjxq(row, index) {
  jltitle.value = "相关方详情"
  dialogVisible.value = true
  getApi({}, `/mosty-jcgl/OccupationalHazardCheckRecords/getTbOccupationalHazardCheckRecordsById/${row.id}`).then(res => {
    if (res) {
      ruleForm.value = res
    }
  })
  // ruleForm.value = row;
}
function delRow(val, index) {
  // let ids = [val.id];
  // postApi(ids, "/mosty-jcgl/OccupationalHazardCheckRecords/delTbOccupationalHazardCheckRecordsByIds").then((res) => {
  //   ElMessage.success("删除成功");
  //   getTableData();
  // });
  tableData.value.splice(index, 1)
}
const handleSave = async () => {
  await fromRuls.value.validate((valid, fields) => {
    if (valid) {

      // loadingshow.value = true;
      // console.log(113, ruleForm.value)
      // ruleForm.value.file = ruleForm.value.file ? ruleForm.value.file.toString() : null //sourceId
      /** 是否 有重复业务 */
      const isReapt = tableData.value.find(item => item.businessTypeCode == ruleForm.value.businessTypeCode)
      if (isReapt && jltitle.value.includes('新增')) return ElMessage.error("业务类型数据重复，请重新选择业务类型")
      // if(isReapt && jltitle.value.includes('修改') && isReapt.sourceId != ruleForm.value.sourceId) return ElMessage.error("业务类型数据重复，请重新选择业务类型")
      ruleForm.value.businessTypeName = D_TB_RELATED.value.find(item => item.value == ruleForm.value.businessTypeCode).label
      if (jltitle.value.includes('新增')) {
        tableData.value.push(JSON.parse(JSON.stringify(ruleForm.value)))
      }
      tableData.value = JSON.parse(JSON.stringify(tableData.value))
      dialogVisible.value = false

      return

    }
  })
}
watch(() => tableData.value, () => {
  pageConfiger.value.total = tableData.value.length || 0
})
onMounted(() => {
  tableData.value = []
})

watch(
  () => props.formId,
  (n, o) => {
    if (n) {
      // occupationalHazardId: props.formId,
      listQuery.occupationalHazardId = n
      getTableData()
    }
  },
  { deep: true }
  // { immediate: true, deep: true }
)
</script>

<style lang="scss" scoped></style>
