<template>
  <a-page-header style="border: 1px solid rgb(235, 237, 240)" @back="router.go(-1)">
    <template #backIcon>
      <div><a-button type="primary">返回</a-button></div>
    </template>
    <template #title>
      <div></div>
    </template>
  </a-page-header>
  <a-collapse v-model:activeKey="activeKey">
    <a-collapse-panel key="1" header="环境监测基本信息">
      <Environment ref="mgst" :type="type" :data="data" :isRead="type == 'view'" />
      <template #extra><a-button type="primary" v-if="type != 'view'" @click.prevent="saveMgst($event)">保存</a-button></template>
    </a-collapse-panel>
    <a-collapse-panel header="检测单位信息" v-for="(item, index) in unitList" :key="2 + index">
      <TestingUnit :ref="(el) => testUnit(el, index)" :data="item" :isRead="type == 'view'" />
      <template #extra v-if="type != 'view'">
        <a-button type="primary" @click.prevent="addUnit($event)">添加</a-button>
        <a-button type="primary" class="ml-5" v-if="index != 0" @click.prevent="del($event, index)">删除</a-button>
      </template>
    </a-collapse-panel>
  </a-collapse>
</template>

<script setup lang="ts">
  import { ref, nextTick } from 'vue';
  import Environment from './components/environment.vue';
  import TestingUnit from './components/TestingUnit.vue';
  import { useRouter } from 'vue-router';
  import { addGljl } from './api';
  const activeKey = ref(['1', '2', '3', '4', '5']);
  let router = useRouter();
  const wrdkid = ref(router.currentRoute.value.query.wrdkid);
  const data = ref<any>({});
  const type = ref(router.currentRoute.value.query.type);
  const unitList = ref([{ id: null }]);
  if (type.value == 'view') {
    data.value = JSON.parse(sessionStorage.getItem('data') || {});
    unitList.value = data.value.jcdwList || [{ id: null }];
  }
  // 保存环境检测的
  const mgst = ref<any>(null);
  async function saveMgst(e) {
    e.stopPropagation();
    const res = await mgst?.value.getFormValue();
    res.wrdkid = wrdkid.value;
    res.jcdwList = [];
    res.type = 0;
    // 循环获取监测单位的值
    unitS.value.forEach(async (v, index) => {
      const resJcdw: any = await unitS.value[index].getFormValue();
      res.jcdwList.push(resJcdw);
    });

    setTimeout(async () => {
      if (res.jcdwList.length != unitS.value.length) return;
      await addGljl(res);
      router.go(-1);
    }, Math.random() * 1000);

    // 走接口
  }

  // 保存检测单位
  const unitS = ref<any>([]);
  const testUnit = (el, index) => {
    if (el) unitS.value[index] = el;
  };
  const callChildMethod = (index) => {
    unitS.value[index].getFormValue();
  };
  function addUnit(event) {
    event.stopPropagation();
    unitList.value.push({ id: null });
    nextTick(() => {
      callChildMethod(unitList.value.length - 1);
    });
  }
  async function del(event, index) {
    event.stopPropagation();
    nextTick();
    unitList.value.splice(index, 1);
    unitS.value.splice(index, 1);
  }
</script>
