<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="item.index" :label="item.label" :name="item.value">
        <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" v-hasPermi="['tender:segmentedIndicatorPlanning:add']">新增</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-table :data="tableData" row-key="id" border v-loading="loading">
          <el-table-column label="序号" width="80" align="center">
            <template #default="scope">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="content" label="内容" />
          <el-table-column prop="plannedBiddingTime" label="计划招标时间" align="center">
            <template #default="scope">
              <el-date-picker v-model="scope.row.plannedBiddingTime" type="date" value-format="YYYY-MM-DD" placeholder="选择时间" />
            </template>
          </el-table-column>
          <el-table-column prop="price" label="操作" align="center">
            <template #default="scope">
              <el-button type="warning" size="small" @click="handleDetail(scope.row)" v-hasPermi="['tender:segmentedIndicatorPlanning:getMore']"
                >详情</el-button
              >
              <el-button type="primary" size="small" @click="handleSave(scope.row)" v-hasPermi="['tender:segmentedIndicatorPlanning:edit']"
                >修改</el-button
              >
              <el-button type="danger" size="small" @click="delHandle(scope.row)" v-hasPermi="['tender:segmentedIndicatorPlanning:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </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="75%" 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-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"
            ref="treeTableRef"
            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="selectNum" label="选择数量" align="center">
              <template #default="scope">
                <el-input-number
                  :model-value="scope.row.selectNum"
                  @change="
                    (val) => {
                      scope.row.selectNum = val;
                      handleNumberChange(scope.row);
                    }
                  "
                  :precision="2"
                  :step="1"
                  :controls="false"
                  :max="Math.floor(scope.row.quantity)"
                  v-if="scope.row.quantity && scope.row.quantity != 0"
                />
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" 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>
    <el-dialog title="详情" v-model="detailDialog" width="75%" draggable>
      <el-table :data="detailData" v-loading="detailLoading" 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="数量" />
        <el-table-column prop="unitPrice" label="单价" align="center" />
        <el-table-column prop="price" label="总价" align="center">
          <template #default="scope">
            {{ scope.row.price }}
          </template>
        </el-table-column>
      </el-table>
    </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, segmentedIndicatorPlanning, getPlanningList, updatePlanning, delPlanning, getDetailsList } 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 activeTab = 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 loading = ref(false);

//字典获取数据
const getTabsList = async () => {
  const res = await getDicts('subcontracting_type');
  if (res.code == 200) {
    activeTab.value = res.data[0].dictValue;
    tabList.value = res.data.map((item: any) => {
      return {
        label: item.dictLabel,
        value: item.dictValue
      };
    });
    getList();
  }
};
//获取表格数据
const getList = async () => {
  try {
    loading.value = true;
    const params = {
      projectId: currentProject.value?.id,
      ...queryParams.value,
      ...queryForm.value,
      dictName: activeTab.value
    };
    const res = await getPlanningList(params);
    if (res.code == 200) {
      tableData.value = res.rows;
      total.value = res.total;
    }
  } catch (error) {
    console.log(error);
    ElMessage({
      message: '获取数据失败',
      type: 'error'
    });
  } finally {
    loading.value = false;
  }
};
const handleTabChange = (tabs: any) => {
  activeTab.value = tabs;
  getList();
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryForm.value.content = '';
  queryForm.value.name = '';
  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 selectionData = ref<any>([]);
//获取表名
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) => {
  selectionData.value = selection;
};
const handleNumberChange = (row: any) => {
  const selectedIds = selectionData.value.map((item) => item.id);
  nextTick(() => {
    treeTableRef.value.toggleRowSelection(row, true);
  });
  restoreSelections(treeData.value, selectedIds);
};

//寻找节点选择
const restoreSelections = (data, selectedIds) => {
  const traverse = (nodes) => {
    nodes.forEach((node) => {
      if (selectedIds.includes(node.id)) {
        nextTick(() => {
          treeTableRef.value.toggleRowSelection(node, true);
        });
      }
      if (node.children && node.children.length > 0) {
        traverse(node.children);
      }
    });
  };
  traverse(data);
};
watch(
  () => selectionData.value,
  (newVal, oldVal) => {
    console.log(newVal, 55555555555555555);
  }
);

//选择表名
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) {
      res.data.forEach((item: any) => {
        item.selectNum = '';
      });
      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(async (valid, fields) => {
    if (valid) {
      try {
        if (selectionData.value.length == 0) {
          ElMessage({
            message: '请选择项目材料',
            type: 'warning'
          });
          return;
        }
        const newSelectionData = selectionData.value.filter((item) => item.quantity != '' && item.quantity != null);
        if (newSelectionData.some((item) => item.selectNum == '' || item.selectNum == null)) {
          ElMessage.error('存在未填写数量的工程或费用名称，请检查');
          return;
        }
        const limitListBos = newSelectionData.map((item: any) => {
          return {
            limitListId: item.id,
            num: item.selectNum
          };
        });
        const params = {
          projectId: currentProject.value?.id,
          ...form.value,
          dictName: activeTab.value,
          limitListBos
        };
        const res = await segmentedIndicatorPlanning(params);
        if (res.code == 200) {
          ElMessage({
            message: '新增成功',
            type: 'success'
          });
          closeDialog();
          getList();
        }
      } catch (error) {
        console.log(error);
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};
//确定修改
const handleSave = (row: any) => {
  try {
    if (!row.plannedBiddingTime) {
      ElMessage({
        message: '请输入计划招标时间',
        type: 'warning'
      });
      return;
    }
    updatePlanning(row).then((res) => {
      if (res.code == 200) {
        ElMessage({
          message: '修改成功',
          type: 'success'
        });
        getList();
      }
    });
  } catch (error) {
    console.log(error);
    ElMessage({
      message: '修改失败',
      type: 'error'
    });
  }
};
//删除
const delHandle = (row: any) => {
  try {
    const params = { ids: row.id };
    delPlanning(params).then((res) => {
      if (res.code == 200) {
        ElMessage({
          message: '删除成功',
          type: 'success'
        });
        getList();
      }
    });
  } catch (error) {
    console.log(error);
    ElMessage({
      message: '删除失败',
      type: 'error'
    });
  }
};
const detailDialog = ref();
const detailData = ref([]);
const detailLoading = ref(false);

//详情
const handleDetail = (row: any) => {
  detailDialog.value = true;
  getDetails(row);
};
const getDetails = (row: any) => {
  getDetailsList({ id: row.id }).then((res) => {
    if (res.code == 200) {
      detailData.value = res.data;
    }
  });
};

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

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