<template>
  <div class="billof-quantities">
    <!-- tabPosition="left" -->
    <el-tabs type="border-card" @tab-change="handleTabChange">
      <el-tab-pane v-for="(item, index) in work_order_type" :key="item.value" :label="item.label">
        <el-card v-if="index < 3" shadow="always">
          <el-form :model="state.queryForm" :inline="true">
            <el-form-item label="版本号" prop="versions">
              <el-select v-model="state.queryForm.versions" placeholder="选择版本号">
                <el-option v-for="item in state.options" :key="item.versions" :label="item.versions"
                  :value="item.versions" />
              </el-select>
            </el-form-item>
            <el-form-item label="表名" prop="sheet">
              <el-select v-model="state.queryForm.sheet" placeholder="选择表名" @change="handleChange">
                <el-option v-for="item in state.sheets" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="openTable(true, index)">一键展开</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="openTable(false, index)">一键收起</el-button>
            </el-form-item>
            <el-form-item>
              <el-upload ref="uploadRef" class="upload-demo" :http-request="importExcel" :show-file-list="false">
                <template #trigger>
                  <el-button v-if="Object.keys(state.versionsData).length === 0 || state.versionsData.status == 'cancel' ||state.versionsData.status == 'back'" type="primary">导入excel</el-button>
                </template>
              </el-upload>
              <el-button v-if="state.versionsData.status == 'draft'" type="primary" con="edit"
                    @click="clickApprovalSheet()">审核</el-button>
                  <el-button v-if="state.versionsData.status == 'waiting' || state.versionsData.status == 'finish'"
                    icon="view" @click="lookApprovalFlow()" type="warning">查看流程</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card v-if="index == 3" shadow="always">
          <el-form :model="state.queryForm" :inline="true">
            <el-form-item label="版本号" prop="versions">
              <el-select v-model="state.queryForm.versions" placeholder="选择版本号" @change="handleChangeVersion">
                <el-option v-for="item in state.options" :key="item.versions" :label="item.versions"
                  :value="item.versions" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button v-if="Object.keys(state.versionsData).length === 0 || state.versionsData.status == 'cancel'" type="primary">导入excel</el-button>
              <el-button v-if="state.versionsData.status == 'draft'" type="primary" con="edit"
                @click="clickApprovalSheet()">审核</el-button>
              <el-button v-if="state.versionsData.status == 'waiting' || state.versionsData.status == 'finish'"
                icon="view" @click="lookApprovalFlow()" type="warning">查看流程</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-table v-if="index < 3" :ref="(el) => (tableRef[index] = el)" :data="state.tableData"
          v-loading="state.loading.list" stripe :row-class-name="state.tableData.length === 0 ? 'table-null' : ''"
          style="width: 100%; margin-bottom: 20px; height: calc(100vh - 305px)" row-key="id" lazy border
          :default-expand-all="true">
          <el-table-column prop="num" label="编号" />
          <el-table-column prop="name" label="工程或费用名称" />
          <el-table-column prop="unit" label="单位" />
          <el-table-column prop="specification" label="规格" />
          <el-table-column prop="quantity" label="数量" />
          <el-table-column prop="remark" label="备注" />
        </el-table>
        <el-table v-if="index == 3" :data="state.tableData"
          style="width: 100%; margin-bottom: 20px; height: calc(100vh - 305px)" row-key="id" border>
          <el-table-column prop="num" label="编号" />
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="specification" label="规格" />
          <el-table-column prop="unit" label="单位" />
          <el-table-column prop="quantity" label="数量" />
          <el-table-column prop="remark" label="备注" />
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup name="billofQuantities">
import { ref, reactive, onMounted, computed, toRefs, getCurrentInstance, nextTick } from 'vue';
import {
  obtainAllVersionNumbers,
  importExcelFile,
  obtainTheList,
  sheetList,
  detailsMaterialAndEquipmentApproval
} from '@/api/design/billofQuantities/index';
import { useUserStoreHook } from '@/store/modules/user';
const userStore = useUserStoreHook();
const currentProject = computed(() => userStore.selectedProject);
const { proxy } = getCurrentInstance();
const { work_order_type } = toRefs(proxy?.useDict('work_order_type'));
const tableRef = ref({});
console.log(work_order_type);

// tableData
// 版本号
const state = reactive({
  work_order_type: 0,
  // 版本号
  version_num: '',
  options: [], // 版本号选项
  sheets: [], // sheet选项
  queryForm: {
    projectId: currentProject.value?.id,
    versions: '',
    sheet: '',
    pageSize: 20,
    pageNum: 1
  },
  loading: {
    versions: false,
    sheets: false,
    list: false
  },
  error: null,
  // 前三个
  tableData: [],
  // 版本号
  versionsData: {}
});
// tab切换
const handleTabChange = (tab) => {
  console.log('tab',tab);
  state.tableData = [];
  state.options = [];
  state.sheets = [];
  state.queryForm.sheet = '';
  state.queryForm.versions = '';
  state.work_order_type = tab;
  if (tab <= 2) {
    getVersionNums();
  } else {
    getVersionNums(false);
  }
};
onMounted(async () => {
  await getVersionNums();
});
// 获取版本号
async function getVersionNums(isSheet = true) {
  try {
    state.loading.versions = true;
    state.error = null;

    const res = await obtainAllVersionNumbers({
      projectId: currentProject.value?.id,
      workOrderType: state.work_order_type,
      pageSize: 1000,
      pageNum: 1
    });

    const { code, rows } = res || {};
    if (code === 200) {
      state.options = rows || [];
      if (state.options.length > 0) {
        state.queryForm.versions = state.options[0].versions;
        // if (state.work_order_type == 3) {
        state.versionsData = state.options[0] || [];
          // console.log('state.versionsData', state.versionsData);
        // }
        // 等待表名加载完成
        console.log(isSheet, state.sheets.length);
        if (isSheet) {
          await handleSheetName();
        } else {
          await handleQueryList(isSheet);
        }
      }
    } else {
      await handleQueryList(isSheet);
    }
  } catch (err) {
    state.error = `获取版本号时发生错误: ${err.message}`;
    console.error(state.error, err);
  } finally {
    state.loading.versions = false;
  }
}

// 获取表名
async function handleSheetName() {
  if (!state.queryForm.versions) {
    console.warn('版本号不存在，无法获取表名');
    return;
  }

  try {
    state.loading.sheets = true;
    state.error = null;

    const { data } = await sheetList({
      projectId: currentProject.value?.id,
      workOrderType: state.work_order_type,
      versions: state.queryForm.versions
    });

    state.sheets = data || [];
    if (state.sheets.length > 0) {
      state.queryForm.sheet = state.sheets[0];
    }

    // 获取列表数据
    await handleQueryList();
  } catch (err) {
    state.error = `获取表名时发生错误: ${err.message}`;
    console.error(state.error, err);
  } finally {
    state.loading.sheets = false;
  }
}

// 获取列表
async function handleQueryList(isSheet = true) {
  if (isSheet && !state.queryForm.sheet) {
    console.warn('表名不存在，无法获取列表数据');
    return;
  }

  try {
    state.loading.list = true;
    state.error = null;

    const result = await obtainTheList(state.queryForm);

    if (result?.code === 200) {
      state.tableData = result.data || [];
    } else {
      state.error = `获取列表数据失败: 错误码 ${result?.code}`;
      console.error(state.error);
    }
  } catch (err) {
    state.error = `获取列表数据时发生错误: ${err.message}`;
    console.error(state.error, err);
  } finally {
    state.loading.list = false;
  }
}
// 上传excel
function importExcel(options) {
  console.log(options);
  let formData = new FormData();
  formData.append('file', options.file);
  state.loading.list = true;
  importExcelFile({ workOrderType: state.work_order_type, projectId: currentProject.value?.id }, formData)
    .then((res) => {
      const { code } = res;
      if (code == 200) {
        proxy.$modal.msgSuccess(res.msg || '导入成功');
        // 更新列表
        if (state.work_order_type == 3) {
          getVersionNums(false);
        } else {
          getVersionNums();
        }
      } else {
        proxy.$modal.msgError(res.msg || '导入失败');
      }
    })
    .catch((err) => {
      proxy.$modal.msgError(err.msg || '导入失败');
    })
    .finally(() => {
      state.loading.list = false;
    });
}
// 切换表名
function handleChange(sheet) {
  state.queryForm.sheet = sheet;
  handleQueryList();
}
// 切换版本号
function handleChangeVersion(versions) {
  state.queryForm.versions = versions;
  state.versionsData = state.options.find((e) => e.versions == versions);
  console.log('state.versionsData', state.versionsData);
  state.sheets = [];
  handleQueryList();
}
// 在 openTable 方法中通过索引获取对应的表格实例
function openTable(flag, index) {
  nextTick(() => {
    // 通过索引获取当前标签页的表格实例
    const currentTable = tableRef.value[index];
    console.log(currentTable, index);
    if (currentTable) {
      handleArr(state.tableData, flag, currentTable);
    }
  });
}
function handleArr(arr, flag, table) {
  arr.forEach((i) => {
    table.toggleRowExpansion(i, flag);
    if (i.children) {
      handleArr(i.children, flag, table);
    }
  });
}

// 审批
function clickApprovalSheet(row) {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/approval/billofQuantities/indexEdit`+state.work_order_type,
    query: {
      id: state.queryForm.versions,
      type: 'update'
    }
  });
}
// 审核流程
function lookApprovalFlow(row) {
  proxy.$router.push({
    path: `/approval/billofQuantities/indexEdit`+state.work_order_type,
    query: {
      id: state.queryForm.versions,
      type: 'view'
    }
  });
}
</script>
<style>
.billof-quantities {
  padding: 20px;
}
</style>
