<template>
  <a-row :gutter="1">
    <a-col class="gutter-row" :span="leftWidth">
      <div class="layout">
        <ProjecList v-show="isShowProject" ref="refProjectList" @callback="callbackProject"/>
        <ProjectTaskLeft
          v-show="!isShowProject"
          ref="refProjectTaskLeft"
          @clearFilter="clearFilter"
          @showProject="showProject"
          @fileCallback="fileCallback"
          @actCallback="actCallback"
          @searchByItemName="searchByItemName"
          @reloadData="reloadData"
        />
      </div>
    </a-col>
    <a-col class="gutter-row" :span="24 - leftWidth">
      <div class="layout">
        <ProjecCheckList
          ref="refProjectCheckList"
          @callback="callbackCheck"
          @setLeftWidth="setLeftWidth"
          @addCheckFromLib="addCheckFromLib"
          @setFileList="setFileList"
          @addProjectCheck="addProjectCheck"
          @showProject="showProject"
        />
        <a-drawer
          placement="right"
          :visible="showDrawer"
          :get-container="true"
          width="100%"
          :mask="true"
          @close="closeDrawerEvent"
          :style="{ position: 'absolute', paddingTop: '1px' }"
        >
          <template #title>
            <a-space>
              <span v-show="actTp === 1" style="max-width: 200px">{{ curCheck?.fileName }}&emsp;{{ curCheck?.item }}</span>
            </a-space>
          </template>

          <template #extra>
            <a-space>
              <a-button v-if="actTp === 1" type="primary" @click="saveBatch" :loading="loading" :disabled="loading">保存</a-button>
              <a-button v-else-if="actTp === 2" type="primary" @click="saveCheckAndItems" :loading="loading" :disabled="loading">保存</a-button>
              <a-button v-else type="primary" @click="saveCheckFromLib()" :loading="loading" :disabled="loading">加入项目</a-button>
              <a-button @click="closeDrawerEvent">关闭</a-button>
            </a-space>
          </template>
          <div v-show="actTp === 1" style="margin-bottom: 20px">
            <a-descriptions title="" bordered size="middle">
              <a-descriptions-item label="检查项">{{ curCheck?.content }}</a-descriptions-item>
            </a-descriptions>
          </div>
          <ProjectCheckItems v-show="actTp === 1" ref="refProjectCheckItems" />
          <ProjectAddCheck v-show="actTp === 2" ref="refProjectAddCheck" />
          <CheckMethodList v-show="actTp === 3" ref="refCheckMethodList" />
        </a-drawer>
      </div>
    </a-col>
  </a-row>
</template>
<script lang="ts" setup name="ProjectItemIndex">
  import { ref, nextTick, onMounted } from 'vue';
  import { VXETable } from 'vxe-table';
  import ProjecList from './components/ProjecList.vue';
  import ProjecCheckList from './components/ProjecCheckList.vue';
  import ProjectCheckItems from './components/ProjectCheckItems.vue';
  import ProjectAddCheck from './components/ProjectAddCheck.vue';
  import CheckMethodList from './components/CheckMethodList.vue';
  import ProjectTaskLeft from './components/ProjectTaskLeft.vue';

  import { defHttp } from '/@/utils/http/axios';
  import { getDictItemsByCode } from '/@/utils/dict/index';
  import { useUserStore } from '/@/store/modules/user';
 

  const actTp = ref(1);
  const addOrUpdateBatchUrl = '/audit/auditProjectItem/addOrUpdateBatch';
  const addCheckAndItemsUrl = '/audit/auditProjectItem/addCheckAndItems';
  const saveProjectCheckUrl = '/audit/auditTask/saveProjectCheck';

  const showDrawer = ref(false);
  const refProjectList = ref();
  const refProjectCheckList = ref();
  const refProjectTaskLeft = ref();
  const refProjectCheckItems = ref();
  const refProjectAddCheck = ref();
  const refCheckMethodList = ref();

  const isShowProject = ref(true);
  const leftWidth = ref(24);
  const loading = ref(false);
  const curProject = ref();
  const curCheck = ref();
  const curFileData = ref();

  function iniData() {
    refProjectList.value.iniData(1);
  }

  async function callbackProject(project) {
    leftWidth.value = 6;
    curProject.value = project;
    isShowProject.value = false;
    await refProjectCheckList.value.iniData(project);
  }

  function closeDrawerEvent() {
    showDrawer.value = false;
    refProjectAddCheck.value.clearForm();
  }

  const saveBatch = async () => {
    loading.value = true;
    try {
      const retData = refProjectCheckItems.value.getData();
      const newRow = retData?.newRow || [];
      const updateRow = retData?.updateRow || [];
      const allRows = mergeArrays(newRow, updateRow);

      const params = {
        items: allRows,
        checkid: curCheck.value?.checkid,
        pid: curProject.value.id,
      };

      await defHttp.post({ url: addOrUpdateBatchUrl, params });
    } catch (error) {
      console.error('Error saving batch:', error);
    } finally {
      loading.value = false;
    }
  };

  const saveCheckAndItems = async () => {
    //loading.value = true;
    try {
      const { check, newRow = [], updateRow = [] } = (await refProjectAddCheck.value.getData()) || {};
      const { content, des, actIds, item, complineContent, fileUploadPath, citemid, id } = check;

      const newCheck = {
        checkMethodItems: mergeArrays(newRow, updateRow),
        id,projectid: curProject.value.id,
        content,des,actIds,
      };
      const itemForm = {
        id: citemid,
        item: item,
        content: complineContent,
        fileUploadPath,
        checkMethods: [newCheck],
      };
      await defHttp.post({ url: addCheckAndItemsUrl, params: itemForm });
      await callbackProject(curProject.value);
    } catch (error) {
      console.error('Error saving check and items:', error);
    } finally {
      loading.value = false;
    }
  };

  function mergeArrays(...arrays) {
    return arrays.reduce((accumulator, currentArray) => {
      return Array.isArray(currentArray) ? accumulator.concat(currentArray) : accumulator;
    }, []);
  }

  function setLeftWidth(isClose) {
    leftWidth.value = isClose ? 0 : 6;
  }

  const callbackCheck = async (check) => {
    actTp.value = 1;
    showDrawer.value = true;
    curCheck.value = check;
    const tpOptions = await getDictItemsByCode('check_item_tp');
    await refProjectCheckItems.value.iniData(check, curProject.value, tpOptions);
  };

  async function addProjectCheck(data) {
    actTp.value = 2;
    showDrawer.value = true;
    const tpOptions = await getDictItemsByCode('check_item_tp');
    let newData = data || {};
    newData['fileId'] = curFileData.value?.value;
    newData['fileName'] = curFileData.value?.label;
    newData['filePath'] = curFileData.value?.filePath;

    nextTick(async () => {
      await refProjectAddCheck.value.clearForm();
      await refProjectAddCheck.value.iniData(tpOptions, newData, curProject.value);
    });
  }

  async function addCheckFromLib(checkIds) {
    actTp.value = 3;
    showDrawer.value = true;
    nextTick(async () => {
      await refCheckMethodList.value.iniData(curProject.value, checkIds);
    });
  }

  const saveCheckFromLib = async () => {
    const { delIds, newIds,comeFrom } = await refCheckMethodList.value.getSelectIds();
    if (newIds.length === 0 && delIds.length === 0) {
      VXETable.modal.message({ content: '请选择记录', status: 'warning' });
      return;
    }

    if (newIds.length > 0) {
      const params = {
        projectid: curProject.value.id,
        checkids: newIds,
        comeFrom:comeFrom
      };
      await defHttp.post({ url: saveProjectCheckUrl, params });
    }

    if (delIds && delIds.length > 0) {
      await refProjectCheckList.value.deleteProjectCheckByIds(delIds.join(','));
    }

    await refProjectCheckList.value.iniData(curProject.value);
  };

  const setFileList = async (fileList, actList) => {
    // if(fileList.length==0) {
    //     leftWidth.value = 0
    // } else {
    //     leftWidth.value = 7
    // }
    nextTick(async () => {
      await refProjectTaskLeft.value.iniData(curProject.value, fileList, actList);
    });
  };

  const showProject = async () => {
    isShowProject.value = true;
    leftWidth.value = 24;
  };

  const fileCallback = async (fileData) => {
    curFileData.value = fileData;
    await refProjectCheckList.value.showFileData(fileData);
  };

  const actCallback = async (actData) => {
    await refProjectCheckList.value.showActData(actData);
  };

  const clearFilter = async () => {
    curFileData.value = {};
    await refProjectCheckList.value.clearFilter();
  };

  const searchByItemName = async (row) => {
    await refProjectCheckList.value.searchByItemName(row.name);
  };

  const reloadData = async () => {
    await refProjectCheckList.value.clearFilter();
    await refProjectCheckList.value.iniData(curProject.value);
  };

  onMounted(async () => {
    await nextTick();
    iniData();
  });
</script>

<style scope>
  .layout {
    background: #fff;
    margin: 5px;
    overflow: hidden;
    height: 80vh;
  }
</style>
