<template>
  <div class="p-2">
    <el-tabs type="border-card" @tab-change="handleTabChange" v-model="activeTab">
      <el-tab-pane v-for="(item, index) in tabList" :key="index" :label="item.label" :name="item.value">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <el-card shadow="always">
            <el-form :model="queryForm" :inline="true">
              <el-form-item label="版本号" prop="versions">
                <el-select v-model="queryForm.versions" placeholder="选择版本号" @change="changeVersions">
                  <el-option v-for="item in 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="queryForm.sheet" placeholder="选择表名" @change="changeSheet">
                  <el-option v-for="item in sheets" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="toggleExpandAll">{{ isExpandAll ? '一键收起' : '一键展开' }}</el-button>
              </el-form-item>

              <el-form-item>
                <el-upload
                  ref="uploadRef"
                  class="upload-demo"
                  :http-request="importExcel"
                  :show-file-list="false"
                  v-hasPermi="['tender:tenderPlanLimitList:importExcelFile']"
                >
                  <template #trigger>
                    <el-button type="primary">导入excel</el-button>
                  </template>
                </el-upload>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleExport()" v-hasPermi="['tender:tenderPlanLimitList:export']">导出excel</el-button>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="warning"
                  icon="view"
                  @click="handleAudit()"
                  v-if="versionsData.status && versionsData.status == 'draft'"
                  v-hasPermi="['tender:tenderPlanLimitList:getVersionDetail']"
                  >审核</el-button
                >
                <el-button
                  type="warning"
                  icon="view"
                  @click="handleAudit()"
                  v-if="versionsData.status && versionsData.status != 'draft'"
                  v-hasPermi="['tender:tenderPlanLimitList:getVersionDetail']"
                  >查看流程</el-button
                >
              </el-form-item>
            </el-form>
          </el-card>
        </transition>
        <el-card shadow="never" class="mb8">
          <el-table ref="tableRef" v-loading="loading" :data="tableData" row-key="id" border lazy default-expand-all>
            <el-table-column prop="num" label="编号" />
            <el-table-column prop="name" label="工程或费用名称" />
            <el-table-column prop="unit" label="单位" />
            <el-table-column prop="quantity" label="数量">
              <template #default="scope">
                {{ scope.row.children.length > 0 ? '' : scope.row.quantity }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="单价" align="center">
              <template #default="scope">
                <el-input-number
                  :model-value="scope.row.unitPrice"
                  @change="
                    (val) => {
                      scope.row.unitPrice = val;
                      changePrice(scope.row);
                    }
                  "
                  :precision="2"
                  :step="0.1"
                  :controls="false"
                  v-if="scope.row.quantity && scope.row.quantity != 0"
                  :disabled="versionsData.status != 'draft'"
                />
              </template>
            </el-table-column>
            <el-table-column prop="price" label="总价" align="center">
              <template #default="scope">
                {{ scope.row.price != 0 ? Number(scope.row.price).toFixed(2) : null }}
              </template>
            </el-table-column>
            <el-table-column prop="operate" label="操作" align="center">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleSave(scope.row, 'all')"
                  v-if="scope.row.quantity && scope.row.quantity != 0"
                  v-hasPermi="['tender:tenderPlanLimitList:edit']"
                  :disabled="versionsData.status != 'draft'"
                  >确定</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { useUserStoreHook } from '@/store/modules/user';
import { obtainAllVersionNumbers, sheetList, getTableList, updatePrice, importExcelFile } from '@/api/tender/index';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStoreHook();
const currentProject = computed(() => userStore.selectedProject);
const tabList = [
  {
    label: '招采工程量清单',
    value: '2'
  },
  {
    label: '物资设备清单',
    value: '3'
  }
];
const queryForm = ref({
  versions: '',
  sheet: ''
});

const versionsData = ref<any>({});

const activeTab = ref('2');
const sheets = ref([]);
const options = ref([]);
const tableData = ref([]);
const tableRef = ref();
const isExpandAll = ref(false);
const loading = ref(false);
const versionMap = new Map();

// 切换tab
const handleTabChange = (tab: string) => {
  activeTab.value = tab;
  tableData.value = [];
  versionsData.value = {};
  getVersionNums();
};
//切换版本
const changeVersions = (value) => {
  versionsData.value = options.value.find((item) => item.versions == value);
  getSheetName();
};
//切换表格
const changeSheet = (val: any) => {
  getTableData();
};
//展开树
const toggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  console.log(isExpandAll.value);
  tableData.value.forEach((row) => {
    tableRef.value.toggleRowExpansion(row, isExpandAll.value);
  });
};

//获取版本号
const getVersionNums = async () => {
  try {
    const params = {
      projectId: currentProject.value?.id,
      workOrderType: activeTab.value,
      pageSize: 1000,
      pageNum: 1
    };

    const res = await obtainAllVersionNumbers(params);
    if (res.code == 200) {
      options.value = res.data;
      if (res.data.length > 0) {
        res.data.forEach((item: any) => {
          versionMap.set(item.versions, item);
        });
        queryForm.value.versions = res.data[0].versions;
        versionsData.value = options.value.find((item) => item.versions == queryForm.value.versions);
        getSheetName();
      } else {
        queryForm.value.versions = '';
        // getSheetName();
      }
    }
  } catch (error) {
    console.log(error);
  }
};
//获取表名
const getSheetName = async () => {
  try {
    const params = {
      projectId: currentProject.value?.id,
      versions: queryForm.value.versions
    };
    const res = await sheetList(params);
    if (res.code == 200) {
      sheets.value = res.data;
      if (res.data.length > 0) {
        queryForm.value.sheet = res.data[0];
      } else {
        queryForm.value.sheet = '';
      }
      getTableData();
    }
  } catch (error) {
    console.log(error);
  }
};
//获取表格数据
const getTableData = async () => {
  try {
    loading.value = true;

    const params = {
      projectId: currentProject.value?.id,
      versions: queryForm.value.versions,
      sheet: queryForm.value.sheet,
      type: activeTab.value
    };
    const res = await getTableList(params);
    if (res.code == 200) {
      tableData.value = res.data;
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};
//导入
const importExcel = (options: any): any => {
  let formData = new FormData();
  formData.append('file', options.file);
  loading.value = true;
  importExcelFile(
    { projectId: currentProject.value?.id, sheet: queryForm.value.sheet, versions: queryForm.value.versions, type: activeTab.value },
    formData
  )
    .then((res) => {
      const { code } = res;
      if (code == 200) {
        proxy.$modal.msgSuccess(res.msg || '导入成功');
        getTableData();
      } else {
        proxy.$modal.msgError(res.msg || '导入失败');
      }
    })
    .catch((err) => {
      proxy.$modal.msgError(err.msg || '导入失败');
    })
    .finally(() => {
      loading.value = false;
    });
};
//导出
const handleExport = () => {
  proxy?.download(
    '/tender/tenderPlanLimitList/export',
    {
      projectId: currentProject.value?.id,
      sheet: queryForm.value.sheet,
      versions: queryForm.value.versions,
      type: activeTab.value
    },
    `招标一览表${queryForm.value.sheet}.xlsx`
  );
};
const modifyPrice = new Map();

const changePrice = (row: any) => {
  modifyPrice.set(row.id, row);
  // if (!row.unitPrice) {
  //   modifyPrice.delete(row.id);
  // }
};
//修改单价
const handleSave = (row?: any, type?: any) => {
  try {
    if (type == 'single') {
      loading.value = true;
      const list = [{ ...row, type: activeTab.value }];
      updatePrice(list).then((res) => {
        if (res.code == 200) {
          ElMessage({
            message: '修改成功',
            type: 'success'
          });
          getTableData();
        }
      });
    }
    if (type == 'all') {
      loading.value = true;
      const list = [];
      modifyPrice.forEach((item) => {
        list.push({ ...item, type: activeTab.value });
      });
      updatePrice(list).then((res) => {
        if (res.code == 200) {
          ElMessage({
            message: '修改成功',
            type: 'success'
          });
          getTableData();
        }
      });
    }
  } catch (error) {
    ElMessage({
      message: '修改失败',
      type: 'error'
    });
  } finally {
    loading.value = false;
  }
};

/** 审核按钮操作 */
const handleAudit = async () => {
  let id = versionMap.get(queryForm.value.versions).id;
  console.log(id);
  if (activeTab.value == '2') {
    proxy?.$tab.openPage('/approval/tenderBidd/indexEdit', '招采工程量清单审核', {
      id: id,
      type: 'update'
    });
  }
  if (activeTab.value == '3') {
    proxy?.$tab.openPage('/approval/tenderBidd/indexEdit2', '物资设备清单审核', {
      id: id,
      type: 'update'
    });
  }
};

//监听项目id刷新数据
const listeningProject = watch(
  () => currentProject.value?.id,
  (nid, oid) => {
    getVersionNums();
  }
);
onUnmounted(() => {
  listeningProject();
});
onMounted(() => {
  getVersionNums();
});
</script>

<style scoped lang="scss"></style>
