<template>
  <div id="consume-app">
    <div class="page-container consumeFile">
      <div class="xhl-topbar-search">
        <div class="xhl-search-multiple" style="display: flex; align-items: center;  margin-bottom: 16px;">
          <el-select v-model="selectedOption" placeholder="请选择" style="width:120px" >
            <el-option v-for="(option, index) in options" :key="index" :label="option" :value="option"  />
          </el-select>
          <el-input v-model="searchContent" placeholder="请输入搜索内容" style="width: 220px;" />
          <div class="search-buttons">
            <el-button @click="search" type="primary" style="margin-right: 8px;">点击搜索</el-button>
            <el-button @click="reset">重置</el-button>
            <el-button @click="exportData" type="success">导出数据</el-button>
            <el-button @click="importDocument" type="default">导入数据</el-button>
          </div>
        </div>
      </div>
      <div class="xhl-topbar-operate flexBetweenCenter">
        <div class="leftBox">
          <el-button type="primary" size="small" @click="addDocument">添加档案</el-button>
        </div>
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="consumeCode" label="耗材编码" width="160"></el-table-column>
        <el-table-column prop="consumeName" label="耗材名称" width="150"></el-table-column>
        <el-table-column prop="category" label="耗材分类" width="130"></el-table-column>
        <el-table-column prop="barcode" label="商品条码" width="120"></el-table-column>
        <el-table-column prop="brand" label="品牌" width="100"></el-table-column>
        <el-table-column prop="spec" label="规格型号" width="100"></el-table-column>
        <el-table-column prop="price" label="单价" width="80"></el-table-column>
        <el-table-column prop="unit" label="计量单位" width="80"></el-table-column>
        <el-table-column prop="maxQty" label="限领数量(人/月)" width="120"></el-table-column>
        <el-table-column prop="upperStock" label="安全库存上限" width="100"></el-table-column>
        <el-table-column prop="lowerStock" label="安全库存下限" width="100"></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button @click="edit(scope.row)" type="text" :disabled="scope.row.status === '禁用'">编辑</el-button>
            <el-button @click="toggleStatus(scope.row)" type="text">
              {{ scope.row.status === '禁用' ? '启用' : '禁用' }}
            </el-button>
            <el-button @click="remove(scope.row)" type="text" style="color: red;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
  
        layout="total, prev, pager, next, sizes, jumper" :total="totalItems" :page-sizes="[10, 20, 50]"
        :show-sizer="true" />
    </div>
    <el-dialog title="添加/编辑档案" v-bind="showAddDialog">
      <el-form :model="form">
        <el-form-item label="耗材名称" required>
          <el-input v-model="form.consumeName" placeholder="请输入耗材名称" />
        </el-form-item>
        <el-form-item label="耗材编码">
          <el-input v-model="form.consumeCode" placeholder="不填则自动生成" />
        </el-form-item>
        <el-form-item label="耗材分类" required>
          <el-cascader v-model="form.category" :options="categoryOptions" placeholder="请选择耗材分类" />
        </el-form-item>
        <el-form-item label="单价" required>
          <el-input v-model="form.price" placeholder="请输入单价" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>
<script>
import { ref } from 'vue';

export default {
 
  setup() {
    const selectedOption = ref('');
    const searchContent = ref('');
    const tableData = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalItems = ref(0);
    const showAddDialog = ref(false);
    const editingRow = ref(null);

    const form = ref({
      consumeName: '',
      consumeCode: '',
      category: [],
      price: ''
    });

    const options = ['耗材名称', '耗材编码'];
    const categoryOptions = [
      { value: 'electronics', label: '电子产品' },
      { value: 'furniture', label: '家具' },
      { value: 'stationery', label: '文具' }
    ];

    const mockData = [
      {  status: '正常', consumeCode: 'A123', consumeName: '消毒水', category: '消耗品', barcode: '123456789', brand: '品牌A', spec: '100ml', price: '10', unit: '瓶', maxQty: '5', upperStock: '100', lowerStock: '10' },
      {  status: '禁用', consumeCode: 'B456', consumeName: '纸张', category: '文具', barcode: '987654321', brand: '品牌B', spec: 'A4', price: '5', unit: '包', maxQty: '10', upperStock: '50', lowerStock: '5' },
      {  status: '正常', consumeCode: 'C789', consumeName: '电脑', category: '电子产品', barcode: '192837465', brand: '品牌C', spec: 'i5', price: '3000', unit: '台', maxQty: '2', upperStock: '20', lowerStock: '2' }
    ];

    const search = () => {
      tableData.value = mockData.filter(item => {
        return item[selectedOption.value]?.includes(searchContent.value);
      });
    };

    const reset = () => {
      searchContent.value = '';
      selectedOption.value = '';
      tableData.value = mockData.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
    };

    const addDocument = () => {
      form.value = { consumeName: '', consumeCode: '', category: [], price: '' }; 
  
    
    };

    const edit = (row) => {
      form.value = { ...row };
      showAddDialog.value = true;
      editingRow.value = row; 
    };
    const toggleStatus = (row) => {
      row.status = row.status === '禁用' ? '正常' : '禁用';
      console.log(`${row.status === '正常' ? 'Enabled' : 'Disabled'}:`, row);
    };

    const remove = (row) => {
      const index = tableData.value.indexOf(row);
      if (index !== -1) {
        tableData.value.splice(index, 1);
      }
      console.log('Removed', row);
    };
    const save = () => {
      if (editingRow.value) {
        Object.assign(editingRow.value, form.value);
        console.log('Updated item', editingRow.value);
      } else {
        const newItem = { ...form.value, status: '正常',  };
        tableData.value.push(newItem);
        console.log('Added new item', newItem);
      }
      showAddDialog.value = false;
    };
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      tableData.value = mockData.slice((val - 1) * pageSize.value, val * pageSize.value);

    };

    tableData.value = mockData.slice(0, pageSize.value);
    totalItems.value = mockData.length;
    const exportData = () => {

      const dataToExport = tableData.value.map(item => {
        return {
          '耗材名称': item.consumeName,
          '耗材编码': item.consumeCode,
          '耗材分类': item.category,
          '单价': item.price,
          '计量单位': item.unit,
          '状态': item.status,
          '安全库存上限': item.upperStock,
          '安全库存下限': item.lowerStock,
     
        };
      });
      const csvContent = [
        ['耗材名称', '耗材编码', '耗材分类', '单价', '计量单位', '状态', '安全库存上限', '安全库存下限'], 
        ...dataToExport.map(item => [
          item['耗材名称'],
          item['耗材编码'],
          item['耗材分类'],
          item['单价'],
          item['计量单位'],
          item['状态'],
          item['安全库存上限'],
          item['安全库存下限']
        ])
      ];

      const csvString = csvContent
        .map(row => row.join(','))
        .join('\n')
  
      const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', 'consume_data.csv');
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      console.log('数据已导出');
    };

    const importDocument = () => {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = '.csv'; 
      input.onchange = (event) => {
        const file = event.target.files[0];
        if (!file) {
          return;
        }

   
        const reader = new FileReader();
        reader.onload = (e) => {
          const content = e.target.result;
          const rows = content.split('\n');
          const data = rows.map(row => {
            const columns = row.split(',');
            return {
              consumeName: columns[0],
              consumeCode: columns[1],
              category: columns[2],
              price: columns[3],
              unit: columns[4],
              status: columns[5],
              upperStock: columns[6],
              lowerStock: columns[7]
        
            };
          });


          tableData.value = data;
          totalItems.value = data.length;

          console.log('数据导入完成', data);
        };
        reader.readAsText(file);
      };

      input.click();
    };
    return {
      selectedOption,
      searchContent,
      tableData,
      currentPage,
      pageSize,
      totalItems,
      showAddDialog,
      form,
      options,
      categoryOptions,
      search,
      reset,
      addDocument,
      edit,
      toggleStatus,
      remove,
      save,
      exportData,
      importDocument,
      handleCurrentChange
    };
  }
}
</script>

<style scoped>
.page-container {

  padding: 20px;
}
input{
width:200px;
}
.xhl-topbar-search {
  margin-bottom: 20px;
}

.xhl-topbar-operate {
  margin-bottom: 20px;
}

.xhl-search-multiple {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 10px;
}

.search-buttons {
  display: flex;
  gap: 10px;
}

.el-button {
  margin-left: 10px;
}

.leftBox,
.rightBox {
  display: flex;
  gap: 10px;
}

.el-input-group {
  display: flex;
  gap: 10px;
}

.table-image {
  width: 34px;
  height: 34px;
}

.el-dialog {
  max-width: 600px;
  width: 100%;
}

.el-form-item {
  margin-bottom: 15px;
}
</style>