<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="检查日期" show-overflow-tooltip property="ckeckDate"></el-table-column>
    <el-table-column label="检测危害因素" property="factorCode">
      <template #default="{ row }">
        <dict-tag :options="_D_TB_ZYJK_WHYS" :value="row.factorCode" :tag="false" />
      </template>
    </el-table-column>
    <!-- <el-table-column label="检查周期" property="inspectionCycle">
      <template #default="{ row }">
        <dict-tag :options="props.dicData.D_TB_JCZQ" :value="row.inspectionCycle" :tag="false" />
      </template>
    </el-table-column> -->
    <el-table-column label="检测点位数量" property="pointsQty"></el-table-column>
    <!-- <el-table-column label=" 检测点位数量" property="pointsQty"></el-table-column> -->
    <el-table-column label="超标点位数量" property="exceedingPointsQty"></el-table-column>
    <!-- <el-table-column label="涉及人数" property="numberPeopleInvolved"></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="1000px" v-model="dialogVisible" :close-on-click-modal="false"
    :before-close="closeDialog">
    <!-- 培训计划新增或修改 -->
    <div class="config">
      <el-form ref="fromRuls" :disabled="jltitle.includes('详情')" :model="ruleForm" :rules="rules" label-width="150px"
        class="demo-ruleForm.value xfzstz-table" inline>
        <el-form-item label="检查日期：" prop="ckeckDate">
          <el-date-picker v-model="ruleForm.ckeckDate" :disabled-date="disablednowDate" style="width: 250px" type="date"
            format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="检测危害因素:" prop="factorCode">
          <el-select v-model="ruleForm.factorCode" placeholder="请选择危害因素" 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-option v-for="item in _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="checkNumberPoints">
          <el-input v-model.number="ruleForm.checkNumberPoints" type="number" style="width: 250px" />
        </el-form-item> -->
        <el-form-item label=" 检测点位数量:" prop="pointsQty">
          <el-input-number style="width: 250px" v-model="ruleForm.pointsQty" precision="0" :min="0" :max="999999999" label="label"></el-input-number>
        </el-form-item>
        <el-form-item label="超标点位数量:" prop="exceedingPointsQty">
          <el-input v-model.number="ruleForm.exceedingPointsQty" type="number" style="width: 250px" />
        </el-form-item>
        <!-- <el-form-item label="涉及人数:" prop="numberPeopleInvolved">
          <el-input v-model.number="ruleForm.numberPeopleInvolved" placeholder="请输入涉及人数" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="检查周期:" prop="inspectionCycle">
          <el-select v-model="ruleForm.inspectionCycle" placeholder="请选择检查周期" style="width: 250px">
            <el-option v-for="item in props.dicData.D_TB_JCZQ" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="备注:" prop="bz" style="width: 100%">
          <el-input v-model="ruleForm.bz" type="textarea" autosize show-word-limit style="width: 730px" maxlength="200" />
        </el-form-item>
        <el-form-item label="检测报告附件:" style="width: 100%" prop="file">
          <MOSTY.Upload :widthNumber="730" :limit="5" :nopicer="true" :isImg="false" :ShowfileList="true" v-model="ruleForm.file" :showinput="true"></MOSTY.Upload>
        </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, defineExpose, 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"
const { proxy } = getCurrentInstance();
const props = defineProps({
  honorTitle: String,
  formId: String,
  dicData: Object,
  formData: 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 currPageTableData = computed(() => {
  return tableData.value.slice((pageConfiger.value.pageCurrent - 1) * pageConfiger.value.pageSize, pageConfiger.value.pageCurrent * pageConfiger.value.pageSize)
})
//规则校验
const rules = reactive({
  ckeckDate: [{ required: true, message: "检查日期不能为空", trigger: "blur" }],
  inspectionCycle: [{ required: true, message: "检查周期不能为空", trigger: "blur" }],
  factorCode: [{ required: true, message: "检查危害因素不能为空", trigger: "blur" }],
  ...rule.numberzzsRule({ validator: true, require: true, num: 9999999 }, "numberPeopleInvolved"),
  ...rule.numberzzsRule({ validator: true, require: true, num: 9999999 }, "checkNumberPoints"),
  pointsQty: [
    {
      validator: (rule, value, callback) => {
        if(value === 0) value = '0'
        if (!value) {
          callback(new Error("请输入 检测点位数量"))
        } else if (value < 0 || !/^[0-9]{0,9}$/.test(value)) {
          callback(new Error(`最多输入9位整数`))
        } else {
          callback()
        }
      },
      trigger: "blur",
      required: true
    }
  ],
  exceedingPointsQty: [
    {
      validator: (rule, value, callback) => {
        if (!value && value != 0) {
          callback(new Error("超标点位数量不能为空"))
        } else if (value > ruleForm.value.checkNumberPoints) {
          callback(new Error("超标点位数量必须小于检测点位数量"))
        } else {
          callback()
        }
      },
      trigger: "blur",
      required: true
    }
  ]
})
const clearData = () => {
  tableData.value = []
}
defineExpose({ tableData, clearData })

const closeDialog = () => {
  if(!fromRuls.value) return
  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
  }

}

const getTableData = () => {
  // console.log(3333, props.formData)
  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
  // 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)
  // pageConfiger.value.total = tableData.value.length || 0
}
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
      ruleForm.value.factorName = _D_TB_ZYJK_WHYS.find(item => item.value == ruleForm.value.factorCode).label
      if (jltitle.value.includes("新增")) tableData.value.push(JSON.parse(JSON.stringify(ruleForm.value)))
      // pageConfiger.value.total = tableData.value.length || 0
      tableData.value = JSON.parse(JSON.stringify(tableData.value))
      dialogVisible.value = false

    }
  })
}

onMounted(() => {
  tableData.value = []
})
// 本地pageSize
watch(() => tableData.value, () => {
  pageConfiger.value.total = tableData.value.length || 0
})
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>
.xfzstz-table {
  padding: 20px;
}
</style>
