<template>
  <el-dialog :title="props.title" width="1200px" v-model="dialogVisible" :before-close="onClose">
    <el-form :model="info" :rules="rules" label-width="140px" label-position="right" label-suffix=":"
      :disabled="props.title.includes('查看')" ref="ruleFormRef" style="width: 100% !important;">
      <MOSTY.Assort title="基础信息" />
      <el-row>
        <el-col :span="12">
          <el-form-item label="企业名称">
            <el-input v-model="info.baOrgName" disabled style="width: 300px;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="危险作业类别" prop="hazardOpsCategoryCode">
            <MOSTY.DictRidioAndSelect :dictData="props.dict.D_BZ_WXZYLXNEW" v-model="info.hazardOpsCategoryCode"
              @onChange="onChange" selectType="select" style="width: 300px;" />
          </el-form-item>

        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="危险作业级别" prop="hazardOpsLevelCode">
            <MOSTY.DictRidioAndSelect :dictData="props.dict.D_BZ_WXZYJB" v-model="info.hazardOpsLevelCode"
              selectType="select" style="width: 300px;"
              :disabledItem="['3', '4'].includes(info.hazardOpsCategoryCode) ? [] : ['7'].includes(info.hazardOpsCategoryCode) ? ['1', '0'] : ['1']" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="危险作业数量" prop="hazardOpsQty">
            <el-input-number v-model="info.hazardOpsQty" :precision="0" style="width: 300px;" :min="1" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">

        <el-button type="primary" style="margin-right: 16px;" v-loading="loadingShow" @click="onSave"
          v-if="props.title.includes('编辑') || !info.sourceId"> <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span> </el-button>
        <el-button @click="onClose"> <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span></el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, computed } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import * as rule from "@/utils/rules.js";
const { proxy } = getCurrentInstance();
const props = defineProps({
  title: String,
  id: String,
  isDetail: {
    type: Boolean,
    default: false
  },
  item: Object,
  query: Object,
  dict: Object
});
const emits = defineEmits(["closeDetail"]);
const dialogVisible = ref(true);
const loadingShow = ref(false)
const ruleFormRef = ref()
const info = ref({})
const rules = ref({
  ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "personnelQty"),
  hazardOpsLevelCode: [{ required: true, message: "请选择", trigger: "blur" }],
  hazardOpsCategoryCode: [{ required: true, message: "请选择", trigger: "blur" }],
  factorName: [{ required: true, message: "请选择", trigger: "change" }],
});
const onClose = () => {
  if(!ruleFormRef.value) return
  if (props.title.includes('编辑') || !info.sourceId) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        emits('closeDetail')
      })
      .catch(() => {
        // catch error
      })
  } else {
    emits('closeDetail')
  }

};
onMounted(() => {
  if (props.id) {
    getDetail()
  } else {
    info.value.baOrgName = props.item.orgName
    info.value.baOrgCode = props.item.orgcode
    info.value.orgName = props.item.orgName
    info.value.orgCode = props.item.orgcode
    info.value.reportingYear = new Date().getFullYear().toString()
    info.value.reportCycleCode = isFirstHalfOfYear()
  }
});
function onChange(val) {
  info.value.hazardOpsLevelCode = ''
  info.value.hazardOpsLevelName = ''
}
const isFirstHalfOfYear = () => {
  const now = new Date(); // 获取当前日期
  const month = now.getMonth() + 1; // 获取当前月份（0-11）  1
  //季度
  if (month <= 3) {
    return "1";
  } else if (month > 3 && month <= 6) {
    return "2";
  } else if (month > 6 && month <= 9) {
    return "3";
  } else {
    return "4";
  }
}
const onSave = async () => {
  loadingShow.value = true
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      info.value.hazardOpsCategoryName = props.dict.D_BZ_WXZYLXNEW && props.dict.D_BZ_WXZYLXNEW.find(item => item.value == info.value.hazardOpsCategoryCode)?.label
      info.value.hazardOpsLevelName = props.dict.D_BZ_WXZYJB && props.dict.D_BZ_WXZYJB.find(item => item.value == info.value.hazardOpsLevelCode)?.label
      if (!info.value.sourceId) {
        postApi(info.value, "/mosty-jcgl/data/ops/add")
          .then((res) => {
            ElMessage({
              message: "新增成功",
              type: "success"
            });
            emits("closeDetail", true);
          })
          .finally(() => {
            loadingShow.value = false
          });
      } else {
        postApi(info.value, "/mosty-jcgl/data/ops/edit")
          .then((res) => {
            ElMessage({
              message: "修改成功",
              type: "success"
            });
            emits("closeDetail", true);
          })
          .finally(() => {
            loadingShow.value = false
          });
      }

    } else {
      ElMessage.warning('请输入必填项！！！')
      loadingShow.value = false
    }
  });
}
const getDetail = () => {
  let _url = props.isDetail ? "getDetailById" : "getLsjlDetail"
  getApi({ id: props.id }, `/mosty-jcgl/data/ops/${_url}`)
    .then((res) => {
      info.value = res
    })
}

</script>

<style lang="scss" scoped>
.content {
  .topper {
    display: flex;

    .sub-le {
      flex: 1;
      padding: 15px 15px 5px 15px;
      border-right: 1px solid #ebeef5;
    }
  }

  .bottom {
    padding: 0 15px 10px 15px;
  }
}
</style>
