<template>
  <div class="asset-container">
    <div>
      <el-button type="primary" class="add-button" @click="form_add">+添加货物</el-button>
    </div>

    <el-table
      :data="tableData"
      row-key="id"
      border
      style="width: 100%;"
      class="elTable"
      fit
      highlight-current-row
      :tree-props="{ children: 'children'}"
    >
      <el-table-column label="货品名称" min-width="80px" header-align="center" align="center">
        <template slot-scope="scope">
          {{ scope.row.goodsTypeName }}
        </template>
      </el-table-column>
      <el-table-column label="货品编码" min-width="80px" header-align="center" align="center">
        <template slot-scope="scope">
          {{ scope.row.goodsTypeCode }}
        </template>
      </el-table-column>
      <el-table-column label="说明" min-width="80px" header-align="center" align="center">
        <template slot-scope="scope">
          {{ scope.row.describe }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="80px" header-align="center" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="primary" size="mini" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="40%"
      :style="{ maxHeight: '100vh', overflowY: 'auto' }"
    >
      <el-form ref="form" label-position="top" :rules="rules" label-width="80px" :model="formLabelAlign">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货品名称" prop="name">
              <el-input v-model="formLabelAlign.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="上级分类" prop="pid">
              <tree-select
                class="typeSelect"
                :height="300"
                :width="250"
                size="small"
                clearable
                :data="parentDept"
                :placeholder="placeholder"
                style="display:inline-block;"
                :default-props="defaultProps"
                :node-key="nodeKey"
                :checked-keys="defaultCheckedKeys"
                @popoverHide="popoverHide"
                :disabled="disabled"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货品编码" prop="type">
              <el-input v-model="formLabelAlign.type" placeholder="请输入编码">
                <template slot="prepend">{{ deptform.parammaps.goodsTypeCode }}</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="说明">
              <el-input type="textarea" v-model="deptform.parammaps.describe" style="margin-bottom: 20px;" :rows="6"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="dialog-footer">
          <el-button class="add-button" @click="handleCancel">取消</el-button>
          <el-button class="add-button" @click="handleAdd">保存</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { PostDataByName, ExecDataByConfig, failproccess, GetDataByName, transData } from '@/api/common';
import TreeSelect from '@/components/TreeSelect'; // 确保路径正确
import { MessageBox } from 'element-ui';

export default {
  components: { TreeSelect },
  data() {
    return {
      parentDept: [], // 树形数据
      defaultProps: {
        children: 'children',
        label: 'goodsTypeName', // 根据实际字段名调整
      },
      list: [{ deptname: '公司', id: 1, parentid: -1 }],
      nodeKey: 'id', // 节点的唯一标识字段
      defaultCheckedKeys: [], // 默认选中的节点
      disabled: false, // 是否禁用
      editVisible: false, // 编辑模式
      placeholder: '请选择上级分类',
      getGoodsTypeParm: { name: 'GetGoodsTypeList' },
      requestParam: {},
      deleteGoodsType: {
        name: "DeleteGoodsType",
        parammaps: {
          id: -1,
        },
      },
      tableData: [],
      dialogTitle: "",
      deptform: {
        name: "InsertGoodsType",
        parammaps: {
          pid: -1,
          goodsTypeName: "",
          goodsTypeCode: "",
          describe: "",
          enable: 1,
        },
      },
      dialogFormVisible: false,
      formLabelAlign: {
        name: '',
        pid: '',
        type: '',
        id: '',
      },
      rules: {
        name: [
          { required: true, message: '请输入货品名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        pid: [
          { required: true, message: '请选择货品类别', trigger: 'change' },
        ],
        type: [
          { required: true, message: '请输入编码', trigger: 'change' },
        ],
      },
    };
  },
  methods: {
    // 删除操作
    handleDel(row) {
      MessageBox.confirm('名称：' + row.goodsTypeName, '确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.deleteGoodsType.parammaps.id = row.id;
        PostDataByName(this.deleteGoodsType).then(response => {
          if (response.msg !== 'fail') {
            this.get_table_data();
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000,
            });
          } else {
            failproccess(response, this.$notify);
          }
        });
      });
    },

    // 上级分类选择回调
    popoverHide(checkedIds, checkedData) {
      this.formLabelAlign.pid = checkedData.id;
      this.deptform.parammaps.pid = checkedData.id;
      this.deptform.parammaps.goodsTypeCode = checkedData.goodsTypeCode;
    },

    // 保存操作
    handleAdd() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.deptform.parammaps.goodsTypeName = this.formLabelAlign.name;
          const requestParam = this.editVisible ? this.buildUpdateRequest() : this.buildInsertRequest();

          ExecDataByConfig(requestParam).then(response => {
            if (response.msg !== 'fail') {
              this.resetForm();
              this.get_table_data();
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000,
              });
            } else {
              this.$notify({
                title: '失败',
                message: response.data,
                type: 'error',
                duration: 2000,
              });
            }
          });
        } else {
          console.log('表单验证未通过');
        }
      });
    },

    // 构建插入请求参数
    buildInsertRequest() {
      return {
        common: { returnmap: "0" },
        data: [
          {
            name: "CheckGoodsTypeNameUniqueOnInsert",
            type: "v",
            parammaps: { goodsTypeName: this.deptform.parammaps.goodsTypeName },
          },
          {
            name: "CheckGoodsTypeCodeUniqueOnInsert",
            type: "v",
            parammaps: { goodsTypeCode: this.deptform.parammaps.goodsTypeCode + "." + this.formLabelAlign.type },
          },
          {
            name: "InsertGoodsType",
            type: "e",
            parammaps: {
              pid: this.deptform.parammaps.pid,
              goodsTypeName: this.deptform.parammaps.goodsTypeName,
              goodsTypeCode: this.deptform.parammaps.goodsTypeCode + "." + this.formLabelAlign.type,
              describe: this.deptform.parammaps.describe,
              enable: 1,
            },
          },
        ],
      };
    },

    // 构建更新请求参数
    buildUpdateRequest() {
      return {
        common: { returnmap: "0" },
        data: [
          {
            name: "CheckGoodsTypeNameUniqueOnInsert",
            type: "v",
            parammaps: { goodsTypeName: this.deptform.parammaps.goodsTypeName },
          },
          {
            name: "CheckGoodsTypeCodeUniqueOnInsert",
            type: "v",
            parammaps: { goodsTypeCode: this.deptform.parammaps.goodsTypeCode + "." + this.formLabelAlign.type },
          },
          {
            name: "UpdateGoodsType",
            type: "e",
            parammaps: {
              pid: this.deptform.parammaps.pid,
              goodsTypeName: this.deptform.parammaps.goodsTypeName,
              goodsTypeCode: this.deptform.parammaps.goodsTypeCode + "." + this.formLabelAlign.type,
              describe: this.deptform.parammaps.describe,
              enable: 1,
              id: this.formLabelAlign.id,
            },
          },
        ],
      };
    },

    // 重置表单
    resetForm() {
      this.deptform.parammaps = { pid: -1, goodsTypeName: "", goodsTypeCode: "", describe: "", enable: 1 };
      this.formLabelAlign = { name: '', pid: '', type: '', id: '' };
      this.defaultCheckedKeys = [];
      this.dialogFormVisible = false;
      this.editVisible = false;
    },

    // 取消操作
    handleCancel() {
      this.resetForm();
    },

    // 获取表格数据
    get_table_data() {
      GetDataByName(this.getGoodsTypeParm).then((response) => {
        if (response.data && response.data.list) {
          const list = response.data.list.map(item => ({
            ...item,
            pid: parseInt(item.pid),
            id: parseInt(item.id),
          }));
          this.tableData = transData(list, 'id', 'pid', 'children');
          this.parentDept = this.tableData;
        }
      });
    },

    // 打开添加弹窗
    form_add() {
      this.dialogTitle = "添加货品分类";
      this.dialogFormVisible = true;
    },

    // 打开编辑弹窗
    handleEdit(row) {
      this.editVisible = true;
      this.defaultCheckedKeys = [row.pid];
      this.dialogTitle = "修改货品分类";
      this.dialogFormVisible = true;
      this.formLabelAlign = {
        pid: row.pid,
        name: row.goodsTypeName,
        type: row.parentGoodsTypeCode,
        id: row.id,
      };
      this.deptform.parammaps = {
        pid: row.pid,
        goodsTypeName: row.goodsTypeName,
        goodsTypeCode: row.goodsTypeCode,
        describe: row.describe,
        enable: 1,
      };
    },
  },
  created() {
    this.get_table_data();
  },
};
</script>

<style>
.add-button {
  background-color: #2196f3; /* 绿色背景 */
  color: white; /* 白色文字 */
  padding: 10px 20px; /* 内边距 */
  border: none; /* 无边框 */
  border-radius: 5px; /* 圆角 */
  cursor: pointer; /* 鼠标悬停时显示手型 */
  font-size: 16px; /* 字体大小 */
  transition: background-color 0.3s ease; /* 背景颜色过渡效果 */
  padding: 8px 12px;
  margin: 15px 30px;
}

.add-button:hover {
  background-color: #1e88e5; /* 鼠标悬停时的背景颜色 */
}

.add-button:active {
  background-color: #1976d2; /* 按钮点击时的背景颜色 */
}

.required-label {
  color: red; /* 红色 */
  margin-right: 4px; /* 与文字间距 */
}

.form-item-name {
  white-space: nowrap;
  margin-bottom: 12px;
  font-size: 15px;
  width: 100%; /* 宽度占满父容器 */
}

.add-item {

  position: absolute;
  top: 35%; /* 垂直居中 */
  left: 50%; /* 水平居中 */
  transform: translate(-50%, -50%); /* 偏移修正 */
  margin: 0 !important; /* 移除默认的外边距 */
}

.add-item .el-dialog__header {
  text-align: left; /* 标题左对齐 */
}

.select-label {
  color: red; /* 红色 */
  margin-right: 4px; /* 与文字间距 */
}

.form-select-name {
  margin-right: 20px;
  width: 40%;
}

/* 输入框样式 */
.input-field {
  width: 120px; /* 调整为80%宽度 */
  height: 50px; /* 调整高度 */
}

/* 下拉框样式 */
.select-field {
  width: 30%;
  height: 50px;
}

/* 表单容器样式 */
.form-container {
  padding: 20px;
}

/* 表单行样式 */
.form-row {
  display: flex;
  justify-content: space-between;

}

/* 表单项样式 */
.form-item {
  width:40%;
  display: flex;
  flex-direction: column;
  gap: 10px; /* 调整内部间距 */
}

.dialog-footer{
  right:10px;
  position:absolute;
  bottom:10px;
}

</style>
