<template>
  <div class="p-2">
    <el-tabs type="border-card" @tab-change="handleTabChange">
      <el-tab-pane v-for="(item, index) in tabList" :key="index" :label="item.label">
        <el-card shadow="always">
          <el-form :model="queryForm" :inline="true" ref="queryFormRef">
            <el-form-item label="名称" prop="versions">
              <el-input v-model="queryForm.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="内容" prop="sheet">
              <el-input v-model="queryForm.content" placeholder="请输入内容" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" plain :icon="Plus" @click="openDialog">新增</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-table :data="tableData" 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>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="新增" v-model="dialogVisible" width="70%" draggable>
      <el-row>
        <el-col :span="11">
          <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" clearable />
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <el-input v-model="form.content" placeholder="请输入内容" type="textarea" clearable :rows="4" />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="2"></el-col>
        <el-col :span="11">
          <div class="Region flex gap-2">
            <el-tag type="primary">Tag 1</el-tag>
            <el-tag type="primary">Tag 1</el-tag>
            <el-tag type="primary">Tag 1</el-tag>
          </div>
        </el-col>
      </el-row>
      <el-row style="margin-top: 20px">
        <el-col :span="24">
          <el-card shadow="never">
            <el-form :model="treeForm" :inline="true">
              <el-form-item label="表名" prop="sheet">
                <el-select v-model="treeForm.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(true)">一键展开</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="toggleExpandAll(false)">一键收起</el-button>
              </el-form-item>
            </el-form>
          </el-card>
          <el-table :data="treeData" v-loading="treeLoading" row-key="id" border lazy default-expand-all @selection-change="handleSelection">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="num" label="编号" />
            <el-table-column prop="name" label="工程或费用名称" />
            <el-table-column prop="unit" label="单位" />
            <el-table-column prop="quantity" label="数量" />
            <el-table-column prop="remark" label="单价" align="center" />
            <el-table-column prop="price" label="总价" align="center">
              <template #default="scope">
                {{ scope.row.price }}
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useUserStoreHook } from '@/store/modules/user';
import { getDicts } from '@/api/system/dict/data';
import { Plus } from '@element-plus/icons-vue';
import { FormInstance } from 'element-plus';
import { treeList, sheetList } from '@/api/contract/index';
const userStore = useUserStoreHook();
const currentProject = computed(() => userStore.selectedProject);

const tabList = ref<any[]>([]);
const tableData = ref<any[]>([]);
const queryFormRef = ref();
const formRef = ref();
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
});
const total = ref(0);
const queryForm = ref({
  name: '',
  content: ''
});
const dialogVisible = ref(false);
const form = ref({
  name: '',
  content: ''
});
const rules = ref({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
});

//字典获取数据
const getTabsList = async () => {
  const res = await getDicts('subcontracting_type');
  if (res.code == 200) {
    tabList.value = res.data.map((item: any) => {
      return {
        label: item.dictLabel,
        value: item.dictValue
      };
    });
  }
};
//获取表格数据
const getList = () => {};
const handleTabChange = () => {};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const openDialog = () => {
  dialogVisible.value = true;
  getSheetName();
};
const closeDialog = () => {
  dialogVisible.value = false;
  form.value = {
    name: '',
    content: ''
  };
  formRef.value?.resetFields();
};
const treeData = ref<any[]>([]);
const treeForm = ref({
  sheet: ''
});
const sheets = ref<any[]>([]);
const treeTableRef = ref();
const isExpandAll = ref(false);
const treeLoading = ref(false);
const treeProps = reactive({
  checkStrictly: false
});
//获取表名
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) {
        treeForm.value.sheet = res.data[0];
      } else {
        treeForm.value.sheet = '';
        ElMessage({
          message: '获取表名失败',
          type: 'warning'
        });
      }
      getTreeList();
    }
  } catch (error) {
    console.log(error);
    ElMessage({
      message: '获取表名失败',
      type: 'warning'
    });
  }
};
const handleSelection = (selection: any) => {
  console.log(selection);
};
//选择表名
const changeSheet = () => {
  getTreeList();
};

const toggleExpandAll = (isExpand: boolean) => {
  treeData.value.forEach((row) => {
    treeTableRef.value.toggleRowExpansion(row, isExpand);
  });
  isExpandAll.value = isExpand;
};
//打开获取表数据
const getTreeList = async () => {
  try {
    treeLoading.value = true;
    const params = {
      projectId: currentProject.value?.id,
      sheet: treeForm.value.sheet
    };
    const res = await treeList(params);
    if (res.code == 200) {
      treeData.value = res.data ?? [];
    }
  } catch (error) {
    console.log(error);
    ElMessage({
      message: '获取表格失败',
      type: 'error'
    });
  } finally {
    treeLoading.value = false;
  }
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!');
    } else {
      console.log('error submit!', fields);
    }
  });
};

onMounted(() => {
  getTabsList();
});
</script>

<style scoped lang="scss">
.Region {
  width: 100%;
  height: 100%;
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 10px;
}
</style>
