<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="物料编码" prop="materialCode">
        <el-input v-model="queryParams.materialCode" placeholder="请输入物料编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="所属分类">
        <el-select v-model="queryParams.categoryId" placeholder="全部分类" clearable style="width:160px">
          <el-option v-for="c in flatCategories" :key="c.categoryId"
            :label="c.categoryName" :value="c.categoryId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物料编码" prop="materialCode" width="130" />
      <el-table-column label="物料名称" prop="materialName" :show-overflow-tooltip="true" />
      <el-table-column label="所属分类" prop="categoryName" width="130" />
      <el-table-column label="规格" prop="spec" :show-overflow-tooltip="true" width="130" />
      <el-table-column label="型号" prop="modelNo" :show-overflow-tooltip="true" width="130" />
      <el-table-column label="单位" prop="unit" width="70" />
      <el-table-column label="品牌" prop="brand" width="100" />
      <el-table-column label="状态" align="center" width="80">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="140">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" style="color:#f56c6c" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="640px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属分类">
              <el-select v-model="form.categoryId" placeholder="请选择分类" clearable style="width:100%">
                <el-option v-for="c in flatCategories" :key="c.categoryId"
                  :label="c.indentName" :value="c.categoryId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格" prop="spec">
              <el-input v-model="form.spec" placeholder="如：500W/220V" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="modelNo">
              <el-input v-model="form.modelNo" placeholder="如：XD-2023A" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="如：台/件/米" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterial, getMaterial, addMaterial, updateMaterial, delMaterial } from "@/api/bid/material";
import { getCategoryList } from "@/api/bid/category";

export default {
  name: "Material",
  data() {
    return {
      loading: false, multiple: true, total: 0, materialList: [],
      open: false, title: "",
      queryParams: { pageNum: 1, pageSize: 10, materialName: null, materialCode: null, categoryId: null },
      form: {},
      flatCategories: [],
      rules: {
        materialCode: [{ required: true, message: "物料编码不能为空", trigger: "blur" }],
        materialName: [{ required: true, message: "物料名称不能为空", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
    this.loadCategories();
  },
  methods: {
    loadCategories() {
      getCategoryList().then(res => {
        this.flatCategories = this.flattenTree(res.data || [], 0, "");
      });
    },
    flattenTree(nodes, depth, prefix) {
      let result = [];
      for (const n of nodes) {
        result.push({ ...n, indentName: prefix + n.categoryName });
        if (n.children && n.children.length) {
          result = result.concat(this.flattenTree(n.children, depth + 1, prefix + "　"));
        }
      }
      return result;
    },
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(res => {
        this.materialList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    handleQuery() { this.queryParams.pageNum = 1; this.getList(); },
    resetQuery() { this.resetForm("queryForm"); this.handleQuery(); },
    handleSelectionChange(sel) { this.multiple = !sel.length; this.ids = sel.map(s => s.materialId); },
    handleAdd() { this.reset(); this.open = true; this.title = "新增物料"; },
    handleUpdate(row) {
      this.reset();
      getMaterial(row.materialId).then(res => { this.form = res.data; this.open = true; this.title = "修改物料"; });
    },
    handleDelete(row) {
      const ids = row.materialId || (this.ids || []).join(",");
      this.$modal.confirm("确认删除？").then(() => delMaterial(ids)).then(() => { this.getList(); this.$modal.msgSuccess("删除成功"); });
    },
    handleStatusChange(row) { updateMaterial(row); },
    reset() { this.form = { status: "0" }; this.resetForm && this.resetForm("form"); },
    cancel() { this.open = false; this.reset(); },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;
        const action = this.form.materialId ? updateMaterial : addMaterial;
        action(this.form).then(() => { this.$modal.msgSuccess("操作成功"); this.open = false; this.getList(); });
      });
    }
  }
};
</script>
