<template>
  <div>
    <MOSTY.FromPage :title="props.title" @closeDialog="black">
      <template #content>
        <div class="formBox">
          <el-form ref="ruleFormRef" :model="listQuery" :rules="rules" status-icon :inline="true" label-position="top"
            :disabled="!props.savebtn" style="width: 100% !important;">
            <div style="margin: auto;">
              <el-form-item label="上报名称：" prop="name">
                <el-input v-model="listQuery.name" disabled clearable style="width: 745px"></el-input>
              </el-form-item>
              <el-form-item label="备注：" prop="bz">
                <el-input v-model="listQuery.bz" clearable type="textarea" autosize style="width: 745px" />
              </el-form-item>
              <el-form-item label="驳回原因：" v-if="listQuery.reason" style=" color: red;">
                <span style="color: red">{{ listQuery.reason }}</span>
              </el-form-item>
            </div>
            <MOSTY.Assort :title="'事故事件列表'" />
            <div class="pd10">
              <div style="margin-bottom: 20px;" v-if="props.savebtn && (props.status == '00' || !props.status)">
                <el-button @click="toAdd('add', null)"><el-icon size="small">
                    <Plus />
                  </el-icon>新增</el-button>
              </div>
              <section style="height:40vh">
                <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :tableloading="tableloading"
                  :isSelect="true" :isSort="true" @SortChange="SortChange" style="width: 100%;">
                  <template #type="{ row }">
                    <dict-tag :options="D_BZ_SGSJLB" :value="row.type" :tag="false" />
                  </template>
                  <template #surveyor="{ row }">
                    <span>{{ row.surveyor ? row.surveyor : '--' }}</span>
                  </template>
                  <!-- 操作 -->
                  <template #actions="scope">
                    <span class="operedit" v-if='props.savebtn && (!scope.row.updateCount || scope.row.updateCount < 1)'
                      @click="toAdd('exit', scope.row, scope.$index)">
                      <el-icon>
                        <EditPen />
                      </el-icon>
                      修改</span>
                    <el-popconfirm v-if='props.savebtn && !scope.row.kbId && (props.status == "00" || !props.status)'
                      confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                      @confirm="handledelete(scope.row, scope.$index)">
                      <template #reference>
                        <span class="operdel" size="small">
                          <el-icon>
                            <Delete />
                          </el-icon>
                          删除</span>
                      </template>
                    </el-popconfirm>
                    <span class="operesee" @click="toAdd('see', scope.row, scope.$index)"><el-icon>
                        <View />
                      </el-icon>查看</span>
                  </template>
                </MOSTY.Table>
              </section>
            </div>
            <div v-if="listQuery.id">
              <MOSTY.Assort :title="'事故事件历史记录列表'" />
              <section style="height:40vh">
                <MOSTY.Table :table-columns="tableColumn" :tableData="lsjltableData" :tableloading="tableloadings"
                  :isSelect="true" :isSort="true" @SortChange="SortChange" style="width: 100%;">
                  <template #type="{ row }">
                    <dict-tag :options="D_BZ_SGSJLB" :value="row.type" :tag="false" />
                  </template>
                  <template #surveyor="{ row }">
                    <span>{{ row.surveyor ? row.surveyor : '--' }}</span>
                  </template>
                  <!-- 操作 -->
                  <template #actions="scope">
                    <span class="operesee" @click="toAdd('lsjl', scope.row, scope.$index)"><el-icon>
                        <View />
                      </el-icon>查看</span>
                  </template>
                </MOSTY.Table>
              </section>
            </div>


          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button v-if="props.savebtn && (props.status == '00' || !props.status)" type="primary"
          @click="submit(ruleFormRef)" :loading="loading"> <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span></el-button>
        <el-button @click="black"> <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span></el-button>
      </template>
    </MOSTY.FromPage>

  </div>
  <div v-if="sgsjIsShow" class="dialog-box">
    <Addsgsj @close="sgsjClose" @getList="getListEvent" @changetable="changetable" :title='sgtitle' :zbId="zbId"
      :savebtn="savebtnzb" :rowobj="data.sgsjEditObj" v-if="sgsjIsShow" />
  </div>
</template>

<script setup>
import * as MOSTY from "@/components/MyComponents/index";
import Addsgsj from "./addsgsj.vue";
import { reactive, ref, onMounted, getCurrentInstance } from "vue";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import { dateFormat } from "@/utils/tools.js"
import { getItem } from "@/utils/storage";
const { proxy } = getCurrentInstance();
const { D_BZ_SGSJLB } = proxy.$dict("D_BZ_SGSJLB");
const timeny = ref(dateFormat({ type: "lastmonth" }))
const props = defineProps({
  rowId: String,
  title: String,
  status: String,
  savebtn: {
    default: true,
    type: Boolean
  }
});
const zbId = ref(null)
const tableColumn = ref([
  {
    title: "事故名称",
    prop: "name",
    sortable: true
  },
  {
    title: "事故时间",
    prop: "time",
    sortable: true
  },
  {
    title: "事故主体",
    prop: "subject",
    sortable: true
  },
  {
    title: "事故类型",
    prop: "type",
    slot: true,
    sortable: true
  },
  {
    title: "事故人员",
    prop: "usernames",
    sortable: true
  },
  {
    title: "现场勘察人",
    prop: "surveyor",
    slot: true,
    sortable: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true,
  }
])
const sgsjIsShow = ref(false);
const savebtnzb = ref(false);
const sgtitle = ref('');
const listQuery = ref({
  name: ''
})
const tableloadings = ref(false)
const lsjltableData = ref([])
const editIndex = ref(null);
const loading = ref(false)
const tableData = ref([])
const tableloading = ref(false)
const emit = defineEmits("close");
const ruleFormRef = ref();
const data = reactive({
  editObj: {},
});
const rules = reactive({
  name: [{ required: true, message: "请输入上报名称", trigger: "change" }]
});

onMounted(() => {
  listQuery.value = {};
  listQuery.value.name = `${getItem("deptId").ssdwmc}${timeny.value}事故事件月报`
  if (props.rowId) {
    getmain(props.rowId)
  } else {
    getsgkbList()
  }

});
//详情
const getmain = (id) => {
  if (id) {
    getApi(
      { id }, "/mosty-jcgl/sgyb/getInfo").then((res) => {
        if (res) {
          listQuery.value = res;
          zbId.value = res.id
          getsgsjList()
          getlsjlData()
        }
      });
  }
};
//	查询事故事件
function getsgsjList() {
  tableloading.value = true
  getApi({ reportId: listQuery.value.id }, '/mosty-jcgl/accident/getList').then(res => {
    if (res) {
      tableloading.value = false
      tableData.value = res;
    }
  }).catch((err) => {
    tableloading.value = false

  });
}
//	查询历史修改记录列表
function getlsjlData(params) {
  tableloadings.value = true
  getApi({ reportId: listQuery.value.id }, '/mosty-jcgl/accident/getJlbList').then(res => {
    if (res) {
      lsjltableData.value = res;
    }
  }).finally(() => {
    tableloadings.value = false
  });
}

//事故月报上报的时候，查询本单位所有的快报信息
function getsgkbList() {
  tableloading.value = true
  postApi({}, '/mosty-jcgl/accidentKb/getList').then(res => {
    if (res) {
      tableloading.value = false
      tableData.value = res;
      tableData.value.forEach(item => {
        item.kbId = item.id
      })

    }
  }).finally(() => {
    tableloading.value = false
  });
}
// 保存
const submit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      listQuery.value.accidentList = tableData.value
      if (listQuery.value.id) {
        loading.value = false;
        postApi(listQuery.value, '/mosty-jcgl/sgyb/edit').then(res => {
          loading.value = false;
          ElMessage.success("修改成功");
          emit("close", false);
        }).finally(() => {
          loading.value = false;
        });

      } else {

        postApi(listQuery.value, '/mosty-jcgl/sgyb/add').then(res => {
          ElMessage.success("新增成功");
          emit("close", false);
        }).finally(() => {
          loading.value = false;
        });
      }

    } else {
      ElMessage.warning('请输入必填项！！！')
    }
  });
};
//新增事故事件
function toAdd(type, row, index) {
  if (type == 'add') {
    data.sgsjEditObj = {}
    editIndex.value = null;
    sgtitle.value = '事故事件新增'
    savebtnzb.value = true
  } else if (type == 'exit') {
    data.sgsjEditObj = row
    editIndex.value = index;
    sgtitle.value = '事故事件修改'
    savebtnzb.value = true
  } else if (type == 'lsjl') {
    data.sgsjEditObj = row
    data.sgsjEditObj.isLsjl = true
    editIndex.value = index;
    sgtitle.value = '事故事件历史记录详情'
    savebtnzb.value = false
  } else {
    data.sgsjEditObj = row
    editIndex.value = index;
    sgtitle.value = '事故事件查看'
    savebtnzb.value = false
  }
  sgsjIsShow.value = true

}
//刷新事故事件
function changetable() {
  sgsjIsShow.value = false
  getsgsjList()
  getlsjlData()
}
const getListEvent = (val) => {
  if (editIndex.value != null) {
    for (let i = 0; i < tableData.value.length; i++) {
      if (editIndex.value == i) {
        tableData.value[i] = val
      }
    }

  } else {
    tableData.value.push(val);
  }
};

//删除事故事件
function handledelete(row, index) {
  if (listQuery.value.id) {
    getApi({}, `/mosty-jcgl/accident/del/${row.id}`).then(res => {
      ElMessage.success("删除成功");
      getsgsjList()
      getlsjlData()
    })
  } else {
    tableData.value.splice(index, 1);
  }

}
//关闭事故事件弹窗
const sgsjClose = (val, obj) => {
  sgsjIsShow.value = val;
}
const black = () => {
  if (props.savebtn && (props.status == '00' || !props.status)) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        emit("close", false);
      })
      .catch(() => {
        // catch error
      })
  } else {
    emit("close", false);
  }

};
</script>

<style lang="scss" scoped>
::v-deep .el-cascader,
::v-deep .el-select {
  width: 100%;
}

::v-deep .el-form--default.el-form--label-top .el-form-item .el-form-item__label {
  margin-bottom: 8px;
  line-height: 22px;
  width: 120px;
  text-align: right;
}

.el-form--inline.el-form--label-top .el-form-item {
  width: 50%;
  display: flex;
  text-align: center;
  align-items: center;
  margin: 10px auto;
}

.el-form {
  width: 100%;
  display: block;
}

.formBox {
  padding: 30px 120px;
  background-color: #fff;
  height: 750px;
}
</style>