<template>
  <el-card class="table-card">
    <template #header>
      <div class="card-header">
        <span class="title">材料费预算明细表</span>
        <div class="flex items-center gap-2">
<!--          <span style="white-space: nowrap">行数:</span>-->
<!--          <el-input-number v-model="addRowCount" :min="1" :max="10" size="small" style="width: 80px" />-->
<!--          <el-button type="primary" size="small" @click="handleAddRows">-->
<!--            <el-icon>-->
<!--              <Plus />-->
<!--            </el-icon>-->
<!--            添加-->
<!--          </el-button>-->
<!--          <el-button type="primary" size="small" @click="handleShowMaterial">        <el-icon>-->
<!--            <Search />-->
<!--          </el-icon>-->
<!--            选择物料-->
<!--          </el-button>-->

          <!-- 新增的下拉按钮 -->
          <el-dropdown trigger="click" @command="handleDropdownCommand">
            <el-button type="primary" size="small">
              添加物料 <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item divided>
                  <div class="custom-dropdown-item" @click.stop="handleAddRows">
                    <span>添加非标准物料：</span>
                    <el-input-number
                      v-model="addRowCount"
                      :min="1"
                      :max="1000"
                      size="small"
                      controls-position="right"
                      style="width: 80px"
                      @click.stop
                    />
                    <span style="margin-left: 4px">个</span>

                  </div>
                </el-dropdown-item>
                <el-dropdown-item command="standard">
                  选择标准物料
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-button type="danger" size="small" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
            <el-icon>
              <Delete />
            </el-icon>
            删除
          </el-button>
        </div>
      </div>
    </template>

    <!-- 表格 -->
    <el-table
      :data="budgetMaterialCostList"
      border
      style="width: 100%"
      :summary-method="getSummaries"
      show-summary
      :span-method="spanMethod"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />

      <!-- 基础信息 -->
      <el-table-column label="基础信息" align="center">
        <el-table-column prop="sortOrder" label="序号" width="80" align="center" />
        <el-table-column prop="materialCode" label="物料号" width="120">
          <template #default="scope">
            <span>{{ scope.row.materialCode }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="materialName" label="物料名称" width="200">
          <template #default="scope">
            <el-input v-model="scope.row.materialName" type="textarea" :rows="1" :disabled="scope.row.materialId !== null" />
          </template>
        </el-table-column>
        <el-table-column prop="unitName" label="单位" width="120">
          <template #default="scope">
            <el-select v-model="scope.row.unitName" placeholder="单位" filterable allow-create default-first-option style="width: 100%" clearable>
              <el-option v-for="unit in unitList" :key="unit.unitName" :label="unit.unitName" :value="unit.unitName" />
            </el-select>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 预算成本 -->
      <el-table-column label="预算成本" align="center">
        <el-table-column prop="unitPrice" label="单价(元)" width="160">
          <template #default="scope">
            <el-input-number v-model="scope.row.unitPrice" :min="0" :precision="2" size="small" @change="calculateBudgetAmount(scope.row)" style="width: 130px" />
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="购置数量" width="160">
          <template #default="scope">
            <el-input-number v-model="scope.row.amount" :min="0" :precision="2" size="small" @change="calculateBudgetAmount(scope.row)" style="width: 130px" />
          </template>
        </el-table-column>
        <el-table-column prop="price" label="金额(元)" width="120">
          <template #default="scope">
            {{ formatNumber(scope.row.price) }}
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 降成本后预算成本 -->
      <el-table-column label="降成本后预算成本" align="center">
        <el-table-column prop="reduceUnitPrice" label="单价(元)" width="160">
          <template #default="scope">
            <el-input-number v-model="scope.row.reduceUnitPrice" :min="0" :precision="2" size="small" @change="calculateReducedAmount(scope.row)" style="width: 130px" />
          </template>
        </el-table-column>
        <el-table-column prop="reduceAmount" label="购置数量" width="160">
          <template #default="scope">
            <el-input-number v-model="scope.row.reduceAmount" :min="0" :precision="2" size="small" @change="calculateReducedAmount(scope.row)" style="width: 130px" />
          </template>
        </el-table-column>
        <el-table-column prop="reducePrice" label="金额(元)" width="120">
          <template #default="scope">
            {{ formatNumber(scope.row.reducePrice) }}
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column prop="reduceProposal" label="降成本方案" min-width="200">
        <template #default="scope">
          <el-input v-model="scope.row.reduceProposal" type="textarea" :rows="2" />
        </template>
      </el-table-column>

      <el-table-column label="操作" width="80" align="center">
        <template #default="scope">
          <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)" icon="Delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 物料选择弹窗 -->
    <el-dialog v-model="showMaterialDialog" title="选择物料" width="1200px">
      <div class="material-dialog-content">
        <!-- 左侧：物料列表 -->
        <div class="material-list-section">
          <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div class="mb-[10px]">
              <el-card shadow="hover">
                <el-form ref="materialQueryParamsRef" :model="materialQueryParams" :inline="true" label-width="100px">
                  <el-form-item label="SAP物料编码" prop="materialCode">
                    <el-input v-model="materialQueryParams.materialCode" placeholder="请输入SAP物料编码" clearable @keyup.enter="handleMaterialQuery" />
                  </el-form-item>
                  <el-form-item label="SAP物料名称" prop="materialName">
                    <el-input v-model="materialQueryParams.materialName" placeholder="请输入SAP物料名称" clearable @keyup.enter="handleMaterialQuery" />
                  </el-form-item>
                  <el-form-item label="物料品牌" prop="materialBrand">
                    <el-input v-model="materialQueryParams.materialBrand" placeholder="请输入物料品牌" clearable @keyup.enter="handleMaterialQuery" />
                  </el-form-item>
                  <el-form-item label="物料型号" prop="materialModel">
                    <el-input v-model="materialQueryParams.materialModel" placeholder="请输入物料型号" clearable @keyup.enter="handleMaterialQuery" />
                  </el-form-item>
                  <!--            <el-form-item label="激活标识" prop="activeFlag">-->
                  <!--              <el-select v-model="queryParams.activeFlag" placeholder="请选择激活标识" clearable>-->
                  <!--                <el-option v-for="dict in active_flag" :key="dict.value" :label="dict.label" :value="dict.value" />-->
                  <!--              </el-select>-->
                  <!--            </el-form-item>-->
                  <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleMaterialQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetMaterialQuery">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
          </transition>

          <!-- 物料表格 -->
          <el-table
            ref="materialTableRef"
            :data="materialList"
            @selection-change="handleMaterialSelectionChange"
            highlight-current-row
            style="width: 100%;"
            v-loading="materialLoading"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="materialCode" label="SAP物料编码" width="120" />
            <el-table-column prop="materialName" label="SAP物料名称" width="150" />
            <el-table-column prop="materialBrand" label="物料品牌" />
            <el-table-column prop="materialModel" label="物料型号" />
            <el-table-column prop="unitName" label="单位" width="80" />
            <el-table-column prop="purchasePrice" label="单价(元)" width="100">
              <template #default="scope">
                {{ formatNumber(scope.row.purchasePrice) }}
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-section">
            <pagination
              v-show="materialTotal > 0"
              :total="materialTotal"
              v-model:page="materialQueryParams.pageNum"
              v-model:limit="materialQueryParams.pageSize"
              @pagination="getMaterialList"
            />
          </div>
        </div>

        <!-- 右侧：已选择物料信息 -->
        <div class="selected-materials-section">
          <div class="selected-header">
            <span class="selected-title">已选择物料</span>
            <span class="selected-count">({{ selectedMaterials.length }})</span>
          </div>
          <div class="selected-list">
            <div v-for="material in selectedMaterials" :key="material.materialCode" class="selected-item">
              <div class="material-info">
                <div class="material-name">{{ material.materialName }}</div>
                <div class="material-details">
                  <span class="material-code">{{ material.materialCode }}</span>
                  <span class="material-spec">{{ material.specification }}</span>
                  <span class="material-unit">{{ material.unit }}</span>
                </div>
                <div class="material-price">¥{{ formatNumber(material.unitPrice) }}</div>
              </div>
              <el-button type="danger" size="small" circle icon="Close" @click="removeSelectedMaterial(material)" />
            </div>
            <div v-if="selectedMaterials.length === 0" class="empty-selected">暂无选择的物料</div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <span class="selected-count">已选择 {{ selectedMaterials.length }} 个物料</span>
          <div>
            <el-button @click="showMaterialDialog = false">取消</el-button>
            <el-button type="primary" @click="confirmMaterialSelection" :disabled="selectedMaterials.length === 0"> 确定 </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { budgetMaterialCostVO } from '@/api/oa/erp/budgetInfo/market/budgetMaterialCost/types';
import { listMaterialInfo } from '@/api/oa/erp/budgetInfo/index';
import { getBaseUnitInfoList } from '@/api/oa/base/unitInfo';
import { UnitInfoVO } from '@/api/oa/base/unitInfo/types';
import { MaterialInfoVO, MaterialInfoQuery, MaterialInfoForm } from '@/api/oa/base/materialInfo/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 接收预算ID作为props
const props = defineProps<{
  budgetId: string;
}>();

// 材料费数据
const budgetMaterialCostList = ref<budgetMaterialCostVO[]>([]);
const toDeletedMaterialCostIdList = ref([]);

// 选中的行
const selectedRows = ref([]);

const addRowCount = ref(1);

// 物料选择弹窗
const showMaterialDialog = ref(false);
const materialSearchKeyword = ref('');
const selectedMaterials = ref([]);
const materialTableRef = ref();

// 标志位，用于区分是用户操作还是程序自动操作
const isUpdatingSelection = ref(false);

const materialList = ref<MaterialInfoVO[]>([]);
const materialTotal = ref(0);
const materialLoading = ref(false);

const data = reactive<{ materialQueryParams: MaterialInfoQuery }>({
  materialQueryParams: {
    pageNum: 1,
    pageSize: 10,
    materialCode: undefined,
    materialName: undefined,
    materialBrand: undefined,
    materialModel: undefined,
    unitId: undefined,
    materialParameter: undefined,
    purchasePrice: undefined,
    foreignPrice: undefined,
    stockingPeriod: undefined,
    activeFlag: undefined,
    orderByColumn: undefined,
    isAsc: undefined,
    params: {}
  }
});

const { materialQueryParams } = toRefs(data);

const materialQueryParamsRef = ref<ElFormInstance>();

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

const handleShowMaterial = () => {
  showMaterialDialog.value = true;
  getMaterialList();
};

/** 搜索按钮操作 */
const handleMaterialQuery = () => {
  materialQueryParams.value.pageNum = 1;
  getMaterialList();
};

/** 重置按钮操作 */
const resetMaterialQuery = () => {
  materialQueryParamsRef.value?.resetFields();
  handleMaterialQuery();
};

/** 查询物料信息列表 */
const getMaterialList = async () => {
  materialLoading.value = true;
  const res = await listMaterialInfo(materialQueryParams.value);
  console.log(res);
  materialList.value = res.rows;
  materialTotal.value = res.total;
  updateTableSelection();
  materialLoading.value = false;
};

const handleDropdownCommand = (command) => {
  if (command === 'notStandard') {
    // 处理添加非标准物料
    handleAddRows();
  } else if (command === 'standard') {
    // 处理其他文字选项
    handleShowMaterial();
    // 其他逻辑
  }
};

// 添加行
const handleAddRows = () => {
  const currentSortOrder =
    budgetMaterialCostList.value && budgetMaterialCostList.value.length > 0
      ? Math.max(...budgetMaterialCostList.value.map((item) => item.sortOrder))
      : 0;
  for (let i = 0; i < addRowCount.value; i++) {
    budgetMaterialCostList.value.push({
      sortOrder: currentSortOrder + i + 1,
      materialId: null,
      materialCode: '',
      materialName: '',
      unitId: undefined,
      unitName: '',
      unitPrice: 0,
      amount: 0,
      reduceUnitPrice: 0,
      reduceAmount: 0,
      reducePrice: 0,
      reduceProposal: ''
    });
  }
};

// 搜索处理
const handleSearch = () => {
  // currentPage.value = 1;
  updateTableSelection();
};

// 更新表格选择状态
const updateTableSelection = () => {
  isUpdatingSelection.value = true;
  nextTick(() => {
    if (materialTableRef.value) {
      // 清空当前页的选择
      materialTableRef.value.clearSelection();

      // 根据已选择的物料重新设置选择状态
      materialList.value.forEach((row) => {
        const isSelected = selectedMaterials.value.some((selected) => selected.materialCode === row.materialCode);
        if (isSelected) {
          materialTableRef.value.toggleRowSelection(row, true);
        }
      });

      // console.log('更新表格选择状态完成');
      // console.log(
      //   '当前页物料:',
      //   materialList.value.map((m) => m.materialCode)
      // );
      // console.log(
      //   '已选择物料:',
      //   selectedMaterials.value.map((s) => s.materialCode)
      // );
    }
    isUpdatingSelection.value = false;
  });
};

// 物料选择变化
const handleMaterialSelectionChange = (selection: any[]) => {
  // 如果是程序自动更新选择状态，跳过处理
  if (isUpdatingSelection.value) {
    return;
  }

  // 获取当前页的所有物料
  const currentPageMaterials = materialList.value;

  // 处理当前页的选择变化
  currentPageMaterials.forEach((material) => {
    const isSelectedInTable = selection.some((selected) => selected.materialCode === material.materialCode);
    const isSelectedInList = selectedMaterials.value.some((selected) => selected.materialCode === material.materialCode);

    if (isSelectedInTable && !isSelectedInList) {
      // 在表格中选中但不在已选择列表中，添加到已选择列表
      selectedMaterials.value.push(material);
    } else if (!isSelectedInTable && isSelectedInList) {
      // 在表格中未选中但在已选择列表中，从已选择列表中移除
      selectedMaterials.value = selectedMaterials.value.filter((selected) => selected.materialCode !== material.materialCode);
    }
  });

  // console.log('用户操作选择变化');
  // console.log(
  //   '当前页物料:',
  //   currentPageMaterials.map((m) => m.materialCode)
  // );
  // console.log(
  //   '表格选择:',
  //   selection.map((s) => s.materialCode)
  // );
  // console.log(
  //   '已选择物料:',
  //   selectedMaterials.value.map((s) => s.materialCode)
  // );
};

// 删除单行
const handleDelete = (index: number, row: budgetMaterialCostVO) => {
  budgetMaterialCostList.value.splice(index, 1);
  // 重新编号
  budgetMaterialCostList.value.forEach((item, index) => {
    item.sortOrder = index + 1;
  });
  if(row.materialCostId){
    toDeletedMaterialCostIdList.value.push(row.materialCostId);
  }
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的行');
    return;
  }
  selectedRows.value.forEach(selectedRow =>{
     if(selectedRow.materialCostId){
       toDeletedMaterialCostIdList.value.push(selectedRow.materialCostId);
     }
  })

  budgetMaterialCostList.value = budgetMaterialCostList.value.filter((item) => !selectedRows.value.includes(item));
  // 重新编号
  budgetMaterialCostList.value.forEach((item, index) => {
    item.sortOrder = index + 1;
  });
  selectedRows.value = [];
};

// 删除已选择的物料
const removeSelectedMaterial = (material: any) => {
  // console.log('删除物料:', material.materialCode);
  selectedMaterials.value = selectedMaterials.value.filter((selected) => selected.materialCode !== material.materialCode);
  // console.log(
  //   '删除后已选择物料:',
  //   selectedMaterials.value.map((s) => s.materialCode)
  // );
  updateTableSelection();
};

// 确认物料选择
const confirmMaterialSelection = () => {
  if (selectedMaterials.value.length === 0) {
    ElMessage.warning('请选择至少一个物料');
    return;
  }

  // 为每个选中的物料添加一行
  selectedMaterials.value.forEach((material) => {
    const currentSortOrder = budgetMaterialCostList.value.length > 0 ? Math.max(...budgetMaterialCostList.value.map((item) => item.sortOrder)) : 0;
    budgetMaterialCostList.value.push({
      sortOrder: currentSortOrder + 1,
      materialId: material.materialId,
      materialCode: material.materialCode,
      materialName: material.materialName,
      unitName: material.unitName,
      unitPrice: material.purchasePrice,
      amount: 0,
      price: 0,
      reduceUnitPrice: material.unitPrice,
      reduceAmount: 0,
      reducePrice: 0,
      reduceProposal: ''
    });
  });

  // 重新编号
  budgetMaterialCostList.value.forEach((item, index) => {
    item.sortOrder = index + 1;
  });

  showMaterialDialog.value = false;
  selectedMaterials.value = [];
  materialSearchKeyword.value = '';
};

// 格式化数字
const formatNumber = (value: number) => {
  if (!value) return '0.00';
  return parseFloat(value).toFixed(2);
};

// 格式化数字,元转换为万元
const format2TenThousandNumber = (value: number) => {
  if (!value) return '0.00';
  return (parseFloat(value) / 10000).toFixed(2);
};

// 计算预算金额
const calculateBudgetAmount = (row: any) => {
  const unitPrice = parseFloat(row.unitPrice) || 0;
  const quantity = parseFloat(row.amount) || 0;
  row.price = unitPrice * quantity;
};

// 计算降成本后金额
const calculateReducedAmount = (row: any) => {
  const unitPrice = parseFloat(row.reduceUnitPrice) || 0;
  const quantity = parseFloat(row.reduceAmount) || 0;
  row.reducePrice = unitPrice * quantity;
};

// 合计方法
const getSummaries = (param: any) => {
  const { columns, data } = param;
  const sums: any[] = [];
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '';
      return;
    }
    if (
      column.property === 'sortOrder' ||
      column.property === 'materialCode' ||
      column.property === 'unitName' ||
      column.property === 'unitPrice' ||
      column.property === 'reduceUnitPrice' ||
      column.property === 'reduceProposal'
    ) {
      sums[index] = '';
      return;
    }
    if (column.property === 'materialName') {
      sums[index] = '合计(元)';
      return;
    }

    const values = data.map((item: any) => Number(item[column.property]));
    if (!values.every((value: number) => Number.isNaN(value))) {
      sums[index] = values.reduce((prev: number, curr: number) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0);
      if (column.property === 'price' || column.property === 'reducePrice') {
        sums[index] = formatNumber(sums[index]);
      } else {
        sums[index] = formatNumber(sums[index]);
      }
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

//合并单元格方法
const spanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  // 判断是否为合计行（summary-method添加的行）
  if (!row && rowIndex === budgetMaterialCostList.value.length) {
    // 合并前四列
    if (columnIndex < 4) {
      // 第一列显示合并后的内容，其他列隐藏
      return columnIndex === 0 ? [1, 4] : [0, 0];
    }
  }
  return [1, 1];
};

// 获取总金额（供父组件调用）
const getTotalAmount = () => {
  const totalBudgetAmount = budgetMaterialCostList.value.reduce((sum, item) => sum + Number(item.price), 0);
  const totalReducedAmount = budgetMaterialCostList.value.reduce((sum, item) => sum + Number(item.reducePrice), 0);
  return {
    budgetAmount: totalBudgetAmount,
    reducedAmount: totalReducedAmount
  };
};

const unitList = ref<UnitInfoVO[]>([]);
/** 查询单位信息列表 */
const getUnitList = async () => {
  const res = await getBaseUnitInfoList();
  unitList.value = res.data;
};

onMounted(() => {
  getUnitList();
});
// 暴露方法给父组件
defineExpose({
  getTotalAmount,
  budgetMaterialCostList,
  toDeletedMaterialCostIdList
});
</script>

<style scoped>
.material-cost {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}

.actions {
  margin-bottom: 20px;
}

.actions .el-button {
  margin-right: 10px;
}

.search-section {
  margin-bottom: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-count {
  color: #606266;
  font-size: 14px;
}

.material-dialog-content {
  display: flex;
  gap: 20px;
  height: 600px;
}

.material-list-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.selected-materials-section {
  width: 300px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.selected-header {
  padding: 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  gap: 8px;
}

.selected-title {
  font-weight: 600;
  color: #303133;
}

.selected-count {
  color: #909399;
  font-size: 12px;
}

.selected-list {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.selected-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  margin-bottom: 8px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.material-info {
  flex: 1;
}

.material-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.material-details {
  display: flex;
  gap: 8px;
  font-size: 12px;
  color: #606266;
  margin-bottom: 4px;
}

.material-code {
  color: #409eff;
  font-weight: 500;
}

.material-spec {
  color: #909399;
}

.material-unit {
  color: #909399;
}

.material-price {
  font-size: 14px;
  color: #e6a23c;
  font-weight: 600;
}

.empty-selected {
  text-align: center;
  color: #909399;
  padding: 40px 20px;
  font-size: 14px;
}

.pagination-section {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}
</style>
