<template>
  <div class="p-2">
    <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:billofquantitiesLimitList: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:billofquantitiesLimitList:export']">导出excel</el-button>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" v-if="reviewStatus && reviewStatus == 'draft'" @click="clickApprovalSheet()">审核</el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              type="warning"
              icon="view"
              v-if="reviewStatus && reviewStatus != 'draft'"
              @click="clickApprovalSheet()"
              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="unitPrice" label="单价" align="center">
          <template #default="scope">
            <el-input-number
              :disabled="reviewStatus != 'draft'"
              :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"
            />
          </template>
        </el-table-column>
        <el-table-column prop="price" label="总价" align="center">
          <template #default="scope">
            <!-- {{ scope.row.children.length > 0 ? scope.row.children.reduce((sum, child) => sum + child.price, 0) : scope.row.price }} -->
            {{ scope.row.price != 0 ? Number(scope.row.price).toFixed(2) : null }}
            <!-- {{ scope.row.price }} -->
          </template>
        </el-table-column>
        <el-table-column prop="operate" label="操作" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              :disabled="reviewStatus != 'draft'"
              @click="handleSave(scope.row, 'all')"
              v-if="scope.row.quantity && scope.row.quantity != 0"
              v-hasPermi="['tender:billofquantitiesLimitList:edit']"
              >确定</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { useUserStoreHook } from '@/store/modules/user';
import { listBillofquantitiesLimitList, obtainAllVersionNumbers, sheetList, updatePrice, importExcelFile } from '@/api/contract/index';
const { proxy } = getCurrentInstance() as any;

const userStore = useUserStoreHook();
const currentProject = computed(() => userStore.selectedProject);
const queryForm = ref({
  versions: '',
  sheet: ''
});
const loading = ref(false);
const options = ref<any[]>([]);
const sheets = ref<any[]>([]);
const tableData = ref<any[]>([]);
const isExpandAll = ref(false);
const reviewStatus = ref('');
const versionObj: any = ref({});
const versionMap = new Map();
//获取版本号
const getVersionNums = async () => {
  try {
    const params = {
      projectId: currentProject.value?.id,
      workOrderType: '1',
      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;
        reviewStatus.value = res.data[0].status;
        getSheetName();
      } else {
        queryForm.value.versions = '';
        ElMessage({
          message: '获取版本号失败',
          type: 'warning'
        });
      }
    }
  } catch (error) {
    console.log(error);
    ElMessage({
      message: '获取版本号失败',
      type: 'warning'
    });
  }
};
//选择版本号
const changeVersions = (val) => {
  options.value.forEach((item) => {
    if (item.versions == val) {
      reviewStatus.value = item.status;
    }
  });
  getSheetName();
};

//选择表名
const changeSheet = () => {
  getTableData();
};

//获取表名
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 = '';
        ElMessage({
          message: '获取表名失败',
          type: 'warning'
        });
      }
      getTableData();
    }
  } catch (error) {
    console.log(error);
    ElMessage({
      message: '获取表名失败',
      type: 'warning'
    });
  }
};
//获取表格
const getTableData = async () => {
  try {
    loading.value = true;
    const params = {
      projectId: currentProject.value?.id,
      versions: queryForm.value.versions,
      sheet: queryForm.value.sheet,
      type: '1'
    };
    const res = await listBillofquantitiesLimitList(params);
    if (res.code == 200) {
      tableData.value = res.data;
    }
  } catch (error) {
    console.log(error);
    tableData.value = [];
    loading.value = false;
  } finally {
    loading.value = false;
  }
};
const modifyPrice = new Map();

const changePrice = (row: any) => {
  modifyPrice.set(row.id, row);
};
//修改单价
const handleSave = (row?: any, type?: any) => {
  try {
    if (type == 'single') {
      loading.value = true;
      const list = [{ ...row, type: '1' }];
      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: '1' });
      });
      updatePrice(list).then((res) => {
        if (res.code == 200) {
          ElMessage({
            message: '修改成功',
            type: 'success'
          });
          getTableData();
        }
      });
    }
  } catch (error) {
    ElMessage({
      message: '修改失败',
      type: 'error'
    });
  } finally {
    loading.value = false;
  }
};
const tableRef = ref<any>();

const toggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  console.log(isExpandAll.value);
  tableData.value.forEach((row) => {
    tableRef.value.toggleRowExpansion(row, isExpandAll.value);
  });
};
//导入
const importExcel = (options: any): any => {
  let formData = new FormData();
  formData.append('file', options.file);
  loading.value = true;
  importExcelFile({ projectId: currentProject.value?.id, versions: queryForm.value.versions, sheet: queryForm.value.sheet, type: '1' }, 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;
    });
};
//监听项目id刷新数据
const listeningProject = watch(
  () => currentProject.value?.id,
  (nid, oid) => {
    getVersionNums();
  }
);
const handleExport = () => {
  proxy?.download(
    '/tender/billofquantitiesLimitList/export',
    {
      projectId: currentProject.value?.id,
      sheet: queryForm.value.sheet,
      versions: queryForm.value.versions,
      type: '1'
    },
    `限价一览表${queryForm.value.sheet}.xlsx`
  );
};
// 审批
const clickApprovalSheet = () => {
  proxy.$tab.closePage(proxy?.$route);
  let id = versionMap.get(queryForm.value.versions).id;
  proxy?.$router.push({
    path: `/approval/contractLimitPrice/indexEdit`,
    query: {
      id: id,
      type: 'update',
      sheets: queryForm.value.sheet
    }
  });
};
onUnmounted(() => {
  listeningProject();
  // console.log(11111111);
});
onMounted(() => {
  getVersionNums();
  // getSheetName();
});
</script>

<style scoped></style>
