<template>
  <el-dialog :title="props.title" v-model="isShowDetail" width="900px" :before-close="closed">
    <div class="config">
      <el-form ref="ruleForms" label-width="auto" style="display: flex;width: 100% !important;flex-wrap: wrap;"
        :model="info" :disabled="!props.isEdit" label-position="right" :rules="rules" :inline="true">
        <el-form-item label="事故名称" prop="name">
          <el-input v-model="info.name" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="事故类型" prop="accidentCategoryCode">
          <MOSTY.DictTree :zdbh="'D_BZ_SGSJLB'" v-model="info.accidentCategoryCode" :placeholder='"请选择类别:"'
            :disabled='false' style="width: 200px;" @onChange='sglbchange' />
        </el-form-item>
        <el-form-item label="事故责任类型" prop="liabilityTypeCode"
          v-if="info.accidentCategoryCode && !['21', '22', '23', '24'].includes(info.accidentCategoryCode)">
          <MOSTY.DictRidioAndSelect :dictData="D_BZ_SGZRLX" v-model="info.liabilityTypeCode" selectType="select"
            :disabledItem="['03'].includes(info.accidentCategoryCode) ? ['6', '7'] : ['1', '2', '3', '4', '5']"
            style="width: 200px;" @onChange='onChangezrlx' />
        </el-form-item>
        <el-form-item label="事故发生日期" prop="occurDate">
          <el-date-picker v-model="info.occurDate" :disabled-date="disablednowDate1" style="width: 200px" type="date"
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="事故死亡人员数量" prop="deathQty">
          <el-input v-model.Number="info.deathQty" type="number" placeholder="填写整数" clearable style="width: 200px">
            <template #append>人</template> </el-input>
        </el-form-item>
        <el-form-item label="事故重伤人员数量" prop="seriousInjuryQty">
          <el-input v-model.Number="info.seriousInjuryQty" type="number" placeholder="填写整数" clearable
            style="width: 200px">
            <template #append>人</template> </el-input>
        </el-form-item>
        <el-form-item label="事故轻伤人员数量" prop="slightInjuryQty">
          <el-input v-model.Number="info.slightInjuryQty" type="number" placeholder="填写整数" clearable
            style="width: 200px">
            <template #append>人</template> </el-input>
        </el-form-item>
        <el-form-item label="事故直接经济损失" prop="directEconomicLoss">
          <el-input v-model.Number="info.directEconomicLoss" type="number" placeholder="输入金额" clearable
            style="width: 200px">
            <template #append>万元</template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" v-loading="btnloading" @click="onSave(ruleForms)" v-if="props.isEdit"> <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span></el-button>
        <el-button @click="closed"> <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span></el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import * as MOSTY from "@/components/MyComponents/index";
import * as rule from "@/utils/rules.js";
import { createAndClickLink, disablednowDate1 } from "@/utils/tools.js";
import { filterYear } from "@/utils/auth.js"
import { ElMessage } from "element-plus"
const { proxy } = getCurrentInstance()
const ruleForms = ref()
const { D_BZ_SGZRLX, D_BZ_AQRYSCLY } =
  proxy.$dict("D_BZ_SGZRLX", "D_BZ_AQRYSCLY")
const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  detailId: {
    type: String,
    default: ""
  },
  isEdit: {
    type: Boolean,
    default: true
  },
  rowItem: Object,
  query: Object
})
const btnloading = ref(false)
const emits = defineEmits(["close"])
const isShowDetail = ref(true)

const rules = reactive({
  name: [{ required: true, message: "请输入事故名称", trigger: "blur" }],
  accidentCategoryCode: [{ required: true, message: "请选择事故类型", trigger: "blur" }],
  liabilityTypeCode: [{ required: true, message: "请选择事故责任类型", trigger: "blur" }],
  occurDate: [{ required: true, message: "请选择事故发生日期", trigger: "blur" }],
  ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "deathQty"),
  ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "seriousInjuryQty"),
  ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "slightInjuryQty"),
  ...rule.numbernineRule({ validator: true, require: true, iszs: true, firstNum: 11, lastNum: 4 }, "directEconomicLoss")

})
const info = ref({})
const closed = () => {
  if(!ruleForms.value) return
  if (props.isEdit) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        emits("close")
      })
      .catch(() => {
        // catch error
      })
  } else {
    emits("close")
  }

}

function sglbchange(val) {
  info.value.accidentCategoryCode = val.dm;
  info.value.accidentCategoryName = val.label;
}
function onChangezrlx(val, label) {

  info.value.liabilityTypeName = label;
}
// 获取详情
const getDetail = () => {
  getApi({}, `/mosty-jcgl/data/accidentEvents/selectOne/${props.detailId}`).then(res => {
    info.value = res
  })
}


const onSave = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      btnloading.value = true
      if (info.value.id) {
        postApi(info.value, "/mosty-jcgl/data/accidentEvents/edit").then(res => {
          ElMessage({
            message: "修改成功",
            type: "success"
          });
          emits("close", true);
        }).finally(() => {
          btnloading.value = false
        });
      } else {
        let params = {
          ...info.value,
        }
        postApi(params, "/mosty-jcgl/data/accidentEvents/add")
          .then(res => {
            ElMessage({
              message: "新增成功",
              type: "success"
            })
            emits("close", true)
          })
          .finally(() => {
            btnloading.value = false
          })
      }

    } else {
      ElMessage.warning('请输入必填项！！！')
    }
  })
}
onMounted(() => {
  if (props.title.includes("新增")) {
    info.value = {
      orgCode: props.rowItem.orgCode && props.rowItem.orgCode.replace("XN", ''),
      orgName: props.rowItem.orgName,
      statId: props.rowItem.id,
      reportingYear: props.query.year,
      reportCycleCode: String(props.query.jd || '')
    }
  } else if (props.detailId) {
    getDetail()
  } else {
    info.value = {}
  }

})
</script>
<style scoped lang="scss">
.config {
  width: 100%;
  // min-height: 400px;
  padding: 40px;
}
</style>
