<template>
  <div class="custom-page">
    <!-- 替换为 avue-crud 表格区域 -->
    <avue-crud ref="crudRef" v-model:data="tableData" v-model:page="pagination" :option="options">
      <template #search>
        <!-- 搜索区域 -->
        <div class="search-area">
          <el-input v-model="searchForm.name" placeholder="投入品名称" style="width: 200px; margin-right: 10px"></el-input>
          <el-button type="primary" @click="searchData">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </template>
      <template #menu-left><el-button type="primary" icon="Plus" @click="openDialog">新增</el-button></template>
      <template #menu="scope">
        <custom-table-operate :actions="options.actions" :data="scope" />
      </template>
    </avue-crud>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑投入品' : '新增投入品'" width="600px">
      <el-form ref="formRef" :model="formData" label-width="100px" class="custom-form">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="formData.specification" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="厂家" prop="manufacturer">
          <el-input v-model="formData.manufacturer" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" class="custom-input" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer custom-footer">
          <el-button @click="dialogVisible = false" class="custom-button">取消</el-button>
          <el-button type="primary" @click="submitForm" class="custom-button">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { CRUD_OPTIONS, customRules } from '@/config';

// 写死的初始数据，将括号内容提取到备注列
const initialTableData = [
  {
    id: 1,
    name: '甘蔗专用全生物降解地膜',
    specification: '厚度0.008mm-0.012mm，宽度800mm-1200mm',
    manufacturer: '耿马特斯郎全生物降解材料有限公司',
    remark: '可根据甘蔗种植需求定制',
  },
  {
    id: 2,
    name: '华丰牌加厚地膜',
    specification: '厚度≥0.01mm，宽度75cm-140cm',
    manufacturer: '河南省银丰塑料有限公司',
    remark: '符合新国标',
  },
  {
    id: 3,
    name: '高速贴片式滴灌带',
    specification: '管径16mm-20mm，出水流量：2.0L/h、2.7L/h',
    manufacturer: '库车拉依苏裕丰农民专业合作社（新疆）',
    remark: '多种规格可选',
  },
  {
    id: 4,
    name: '再生滴灌带',
    specification: '500米/卷',
    manufacturer: '宁夏佳稼旺生态农业科技有限公司',
    remark: '以旧换新，50公斤废旧滴灌带兑换500米新带',
  },
  {
    id: 5,
    name: '防草布（PP编织）',
    specification: '宽度1.2m，克重90g/㎡',
    manufacturer: '昆明绿保塑业有限公司',
    remark: '用于果园/经济作物抑草',
  },
];

// 搜索表单
const searchForm = reactive({
  name: '',
});

// avue-crud 实例引用
const crudRef = ref(null);

// 表格数据
const tableData = ref([...initialTableData]);

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: initialTableData.length,
});

// avue-crud 配置项
const options = reactive({
  ...CRUD_OPTIONS,
  addBtn: false,
  searchBtn: false,
  emptyBtn: false,
  column: [
    {
      label: '名称',
      prop: 'name',
    },
    {
      label: '规格',
      prop: 'specification',
    },
    {
      label: '厂家',
      prop: 'manufacturer',
    },
    {
      label: '备注',
      prop: 'remark',
    },
  ],
  actions: [
    {
      name: '编辑',
      icon: 'edit',
      event: ({ row }) => editData(row),
    },
    {
      type: 'danger',
      name: '删除',
      icon: 'delete',
      event: ({ row }) => deleteData(row.id),
    },
  ],
});

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);
const formData = reactive({
  id: null,
  name: '',
  specification: '',
  manufacturer: '',
  remark: '',
});

// 搜索数据
const searchData = () => {
  pagination.currentPage = 1;
  const filteredData = initialTableData.filter((item) => item.name.includes(searchForm.name));
  tableData.value = filteredData;
  pagination.total = filteredData.length;
};

// 重置搜索
const resetSearch = () => {
  searchForm.name = '';
  pagination.currentPage = 1;
  tableData.value = [...initialTableData];
  pagination.total = initialTableData.length;
};

// 打开弹窗
const openDialog = () => {
  isEdit.value = false;
  Object.keys(formData).forEach((key) => {
    if (key !== 'id') {
      formData[key] = '';
    }
  });
  formData.id = tableData.value.length > 0 ? Math.max(...tableData.value.map((item) => item.id)) + 1 : 1;
  dialogVisible.value = true;
};

// 编辑数据
const editData = (row) => {
  isEdit.value = true;
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 删除数据
const deleteData = (id) => {
  tableData.value = tableData.value.filter((item) => item.id !== id);
  pagination.total = tableData.value.length;
  ElMessage.success('删除成功');
};

// 提交表单
const submitForm = () => {
  if (isEdit.value) {
    const index = tableData.value.findIndex((item) => item.id === formData.id);
    if (index !== -1) {
      tableData.value[index] = { ...formData };
      ElMessage.success('编辑成功');
    }
  } else {
    tableData.value.push({ ...formData });
    pagination.total = tableData.value.length;
    ElMessage.success('新增成功');
  }
  dialogVisible.value = false;
};
</script>

<style scoped>
.custom-page {
  padding: 20px;
  height: calc(100vh - 150px);
}

.search-area {
  margin-bottom: 20px;
}
.custom-form {
  padding: 20px;
}

/* 自定义输入框样式 */
.custom-input {
  border-radius: 6px;
  transition:
    border-color 0.3s,
    box-shadow 0.3s;
}

.custom-input:hover {
  border-color: #409eff;
}

.custom-input:focus-within {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 自定义备注输入框样式 */
.custom-input textarea {
  border-radius: 6px;
}

/* 对话框底部按钮区域样式 */
.custom-footer {
  padding: 10px 20px 20px;
}

/* 自定义按钮样式 */
.custom-button {
  border-radius: 6px;
  transition: transform 0.2s;
}

.custom-button:hover {
  transform: translateY(-2px);
}

/* 主按钮悬停效果 */
.custom-button[type='primary']:hover {
  opacity: 0.9;
}
</style>
