<template>
  <div class="bg-[#fff]">
    <a-page-header :backIcon="false">
      <template #extra>
        <a-button type="primary" v-if="params.flag != '1' && params.flag != '2'" :loading="loadingSubmit" @click="toSaveOrSubmit('submit')"
          >提交</a-button
        >
        <a-button type="primary" v-if="params.flag != '1' && params.flag != '2'" :loading="loadingSave" @click="toSaveOrSubmit('save')" class="ml-2"
          >保存</a-button
        >
        <a-button type="primary" @click="router.go(-1)">返回</a-button>
      </template>
    </a-page-header>
    <a-collapse v-model:activeKey="activeKey" :bordered="false">
      <a-collapse-panel key="1" header="监理单位基本信息" :forceRender="true" v-for="(item, index) in jlDw" :key="'jldw' + index">
        <unitMessageForm :ref="(el) => childRef(el, 'jldw', index)" upload=" " :data="item" :isRead="params.flag == '1' || params.flag == '2'" />
        <template #extra v-if="params.type !== 'detail'">
          <a-button type="primary" class="ml-5" v-if="index != 0 && !(params.flag == '1' || params.flag == '2')" @click.prevent="delDw($event, 'jldw', index)" v-show="index > 0">删除</a-button>
          <a-button type="primary" @click.prevent="addDw($event, 'jldw')" v-if="!(params.flag == '1' || params.flag == '2')">添加</a-button>
        </template>
      </a-collapse-panel>
      <a-collapse-panel key="2" header="运输单位基本信息" :forceRender="true" v-for="(item, index) in ysDw" :key="'ysdw' + index">
        <unitMessageForm :ref="(el) => childRef(el, 'ysdw', index)" upload=" " :data="item" :isRead="params.flag == '1' || params.flag == '2'" />
        <template #extra v-if="params.type !== 'detail'">
          <a-button type="primary" class="ml-5" v-if="index != 0 && !(params.flag == '1' || params.flag == '2')" @click.prevent="delDw($event, 'ysdw', index)" v-show="index > 0">删除</a-button>
          <a-button type="primary" @click.prevent="addDw($event, 'ysdw')" v-if="!(params.flag == '1' || params.flag == '2')">添加</a-button>
        </template>
      </a-collapse-panel>
      <a-collapse-panel key="3" header="处置单位基本信息" :forceRender="true" v-for="(item, index) in czDw" :key="'czdw' + index">
        <unitMessageForm :ref="(el) => childRef(el, 'czdw', index)" upload=" " :data="item" :isRead="params.flag == '1' || params.flag == '2'" />
        <template #extra v-if="params.type !== 'detail'">
          <a-button type="primary" class="ml-5" v-if="index != 0 && !(params.flag == '1' || params.flag == '2')" @click.prevent="delDw($event, 'czdw', index)" v-show="index > 0">删除</a-button>
          <a-button type="primary" @click.prevent="addDw($event, 'czdw')" v-if="!(params.flag == '1' || params.flag == '2')">添加</a-button>
        </template>
      </a-collapse-panel>
      <a-collapse-panel key="4" header="接收单位基本信息" :forceRender="true" v-for="(item, index) in jsDw" :key="'jsdw' + index">
        <!-- 详情：转运计划填报 -->
        <zyjhForm :ref="(el) => childRef(el, 'jsdw', index)" upload=" " :data="item" :isRead="params.flag == '1' || params.flag == '2'" />
        <template #extra v-if="params.type !== 'detail'">
          <a-button type="primary" class="ml-5" v-if="index != 0 && !(params.flag == '1' || params.flag == '2')" @click.prevent="delDw($event, 'jsdw', index)" v-show="index > 0">删除</a-button>
          <a-button type="primary" @click.prevent="addDw($event, 'jsdw')" v-if="!(params.flag == '1' || params.flag == '2')">添加</a-button>
        </template>
      </a-collapse-panel>
    </a-collapse>
    <div class="pt-5">
      <!-- 详情：转运计划填报 -->
      <!-- <BasicForm @register="registerForm" /> -->
      <!-- 详情：接收完成填报 -->
      <!-- <template v-if="params.type === 'detail'">
        <a-divider orientation="left" />
        <fillingendInfo :data="item"  v-for="(item, index) in fillingendData" :key="index+'jbxx'"/>
      </template> -->
      <div v-if="params.type === 'detail'" class="p-3">
        <a-divider orientation="left">历史记录</a-divider>
        <a-table :columns="historyColumns" :data-source="zyjhHisList" :pagination="false" bordered size="middle">
          <!--操作栏-->
          <template #action="{ record }">
            <a-button type="link" @click="toDetail(record)">查看</a-button>
          </template>
        </a-table>
      </div>
      <fillingHistoryInfoModal @register="registerModal" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, nextTick } from 'vue';
  import { useRouter } from 'vue-router';
  // import { FormSchema } from '/@/components/Table';
  import { saveOredit, findSzdzg, queryZyjh } from '../api';
  // import { useMessage } from '/@/hooks/web/useMessage';
  import unitMessageForm from '/@/components/customComponent/unitMessageForm.vue';
  import zyjhForm from '/@/components/customComponent/zyjhForm.vue';
  import fillingHistoryInfoModal from '../modal/fillingHistoryInfoModal.vue';
  import { useUserStore } from '/@/store/modules/user';
  import { useModal } from '/@/components/Modal';
  import { historyColumns } from '../data';
  import fillingendInfo from './fillingendInfo.vue';
  const [registerModal, { openModal }] = useModal();
  // Emits声明
  // const { createMessage } = useMessage();
  const emit = defineEmits(['register']);
  const activeKey = ref(['1', '2', '3', '4']);
  const loadingSubmit = ref(false);
  const loadingSave = ref(false);
  const router = useRouter();
  const params = ref<any>(router.currentRoute.value.query);
  const userStore: any = useUserStore();
  const jszgId = ref<any>({ realname: '' });

  const jlDw = ref<any>([{ id: null }]);
  const ysDw = ref<any>([{ id: null }]);
  const czDw = ref<any>([{ id: null }]);
  const jsDw = ref<any>([{ id: null }]);

  const jldwBzd = ref<any>([]);
  const ysdwBzd = ref<any>([]);
  const czdwBzd = ref<any>([]);
  const jsdwBzd = ref<any>([]);

  const baseInfo = ref({});
  const getJSZG = async () => {
    let bm = params.value.wrdkbm;
    if (userStore.userInfo.userType == 'S') bm = '';
    jszgId.value = await findSzdzg({ wrdkbm: bm });
    const res = { szdzgbm: jszgId?.value?.realname };
    // setFieldsValue({ ...res });
    jsDw.value[0].szdzgbm = jszgId?.value?.realname
    // jsdwBzd.value[0].szdzgbm = jszgId?.value?.realname
    baseInfo.value = { ...res }
  };
  getJSZG();
  const fillingendData = ref();
  async function getData() {
    const res = await queryZyjh({ id: params.value.id });
    fillingendData.value = res.jbxxList;

    let list = res.dwxxList
    if (list.length == 0) {
      return
    }
    
    let jldw = ref<any>([]), ysdw = ref<any>([]), czdw = ref<any>([]);
    list.forEach(element => {
      if (element.jgtype == 'jldw') {
        jldw.value.push(element);
      } else if (element.jgtype == 'ysdw') {
        ysdw.value.push(element);
      } else if (element.jgtype == 'czdw') {
        czdw.value.push(element);
      }
    });

    jlDw.value = jldw.value.length == 0?[{id:null}]:jldw.value
    ysDw.value = ysdw.value.length == 0?[{id:null}]:ysdw.value
    czDw.value = czdw.value.length == 0?[{id:null}]:czdw.value

    if (res.jbxxList.length == 0) {
      jsDw.value = [{id:null, szdzgbm: jszgId?.value?.realname}]
    } else {
      res.jbxxList.forEach(element => {
        element.szdzgbm = jszgId?.value?.realname
      });

      jsDw.value = res.jbxxList
    }
    
    zyjhHisList.value = res.zyjhHisList;
    // res.szdzgbm = jszgId?.value?.realname;

    baseInfo.value = { ...res }
  }
  if (params.value.flag != '-1') getData();


  /**
   * 监理单位、运输单位、处置单位、接受详情 添加多个、删除功能
   * @param type 
   */

  function addDw(event, type) {
    event.stopPropagation();
    switch (type) {
      case 'jldw':
        jlDw.value.push({ id: null });
        nextTick(() => {
          callChildMethod(jldwBzd.value, jldwBzd.value.length - 1);
        });
        break;
      case 'ysdw':
        ysDw.value.push({ id: null });
        nextTick(() => {
          callChildMethod(ysdwBzd.value, ysdwBzd.value.length - 1);
        });
        break;
      case 'czdw':
        czDw.value.push({ id: null });
        nextTick(() => {
          callChildMethod(czdwBzd.value, czdwBzd.value.length - 1);
        });
        break;
      case 'jsdw':
        jsDw.value.push({ id: null, szdzgbm: jszgId?.value?.realname });
        nextTick(() => {
          callChildMethod(jsdwBzd.value, jsdwBzd.value.length - 1);
        });
        break;
    
      default:
        break;
    }
  }
  function delDw(event, type, index) {
    event.stopPropagation();
    switch (type) {
      case 'jldw':
        jlDw.value.splice(index, 1)
        jldwBzd.value.splice(index, 1)
        break;
      case 'ysdw':
        ysDw.value.splice(index, 1)
        ysdwBzd.value.splice(index, 1)
        break;
      case 'czdw':
        czDw.value.splice(index, 1)
        czdwBzd.value.splice(index, 1)
        break;
      case 'jsdw':
        jsDw.value.splice(index, 1)
        jsdwBzd.value.splice(index, 1)
        break;
    
      default:
        break;
    }
  }

  const childRef = (el, type, index) => {
    if (!el) return
     
    switch (type) {
      case 'jldw':
        jldwBzd.value[index] = el;
        break;
      case 'ysdw':
        ysdwBzd.value[index] = el;
        break;
      case 'czdw':
        czdwBzd.value[index] = el;
        break;
      case 'jsdw':
        jsdwBzd.value[index] = el;
        break;
    
      default:
        break;
    }
  };

  const callChildMethod = (item, index) => {
    item[index].getFormValueBz();
  };


  // 调接口复制根据flg=1代表提交过的

   async function toSaveOrSubmit(type) {

    const dwxxList = ref<any>([])
    const jbxxList = ref<any>([])
    for (let i = 0; i < jldwBzd.value.length; i++) {
      const element = jldwBzd.value[i];
      let obj = await element.getFormValueBz(type)
      obj.jgtype = 'jldw'
      dwxxList.value.push(obj)
    }

    for (let i = 0; i < ysdwBzd.value.length; i++) {
      const element = ysdwBzd.value[i];
      let obj = await element.getFormValueBz(type)
      obj.jgtype = 'ysdw'
      dwxxList.value.push(obj)
    }

    for (let i = 0; i < czdwBzd.value.length; i++) {
      const element = czdwBzd.value[i];
      let obj = await element.getFormValueBz(type)
      obj.jgtype = 'czdw'
      dwxxList.value.push(obj)
    }
    
    for (let i = 0; i < jsdwBzd.value.length; i++) {
      const element = jsdwBzd.value[i];
      let obj = await element.getFormValueBz(type)
      obj.szdzgbm = jszgId.value.id;
      jbxxList.value.push(obj)
    }
    
    //const jlList =  await jlDw.value[0].getFormValueBz();
    // jlList.jgtype = 'jldw';
    // const ysList = await ysDw.value[0].getFormValueBz();
    // ysList.jgtype = 'ysdw';
    // const czList = await czDw.value[0].getFormValueBz();
    // const jsList = await jsDw.value[0].getFormValueBz();
    // czList.jgtype = 'czdw';

    // return  baseInfo.value

    let values = ref<any>({...baseInfo.value});
    values.value.dwxxList = dwxxList.value;
    values.value.jbxxList = jbxxList.value;
    values.value.id = params.value.id;
    values.value.szdzgbm = jszgId.value.id;

    if (type === 'save') {
      try {
        values.value.flag = 0;
        loadingSave.value = true;
        await saveOredit(values.value);
      } finally {
        loadingSave.value = false;
      }
    }
    if (type === 'submit') {
      try {
        values.value.flag = 1;
        loadingSubmit.value = true;
        await saveOredit(values.value);
        router.go(-1);
      } finally {
        loadingSubmit.value = false;
      }
    }
  }
  const zyjhHisList = ref([]);
  const toDetail = (record) => {
    openModal(true, {
      record: record.his ? JSON.parse(record.his) : {},
    });
  };
</script>

<style lang="less" scoped>
  :deep(.ant-input-number) {
    width: 100%;
  }
</style>
