<template>
  <div class="global-variable">
    <div class="inquire">
      <div class="condition">
        <p>部件名称：</p>
        <el-input
          v-model="nameOfparts"
          size="small"
          class="search-input"
        ></el-input>
        <el-button type="primary" @click="GETquery" size="small"
          >查询</el-button
        >
      </div>
      <el-button plain size="small" @click="newly">新增</el-button>
    </div>
    <div class="assemblyList">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="unitModuleName" align="center" label="部件模块">
        </el-table-column>
        <el-table-column prop="contentsName" align="center " label="部件名称  ">
        </el-table-column>
        <el-table-column
          prop="associatedFunctionTypeName"
          align="center"
          label="部件类型 "
        >
        </el-table-column>
        <el-table-column prop="contentsType" align="center" label="部件编码">
        </el-table-column>
        <el-table-column prop="createTime" align="center" label="创建时间">
        </el-table-column>
        <el-table-column prop="updateTime" align="center" label="维护时间">
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作">
          <template slot-scope="scope">
            <!-- <el-button @click="handleClick(scope.row)" type="text" size="small"
              >编辑</el-button
            > -->
            <el-button
              v-if="scope.row.associatedFunctionType === 1"
              @click="ONallocation(scope.row)"
              type="text"
              size="small"
              >部件配置</el-button
            >
            <el-button
              v-if="scope.row.associatedFunctionType === 2"
              @click="ONbrand(scope.row)"
              type="text"
              size="small"
              >品牌维护</el-button
            >
            <el-button @click="ONdelete(scope.row)" type="text" size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="pageNum"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total"
        class="fenye"
      >
      </el-pagination>
    </div>

    <el-dialog
      title="新增部件"
      :visible.sync="dialogVisible"
      width="20%"
      :before-close="handleClose"
    >
      <p style="margin-bottom: 20px">
        部件模块：<el-select v-model="modulevalue" placeholder="请选择">
          <el-option
            v-for="item in moduleoptions"
            :key="item.contentsValue"
            :label="item.contentsName"
            :value="item.contentsValue"
          >
          </el-option>
        </el-select>
      </p>
      <p style="margin-bottom: 20px">
        部件名称：<el-select v-model="namevalue" placeholder="请选择">
          <el-option
            v-for="item in nameoptions"
            :key="item.contentsValue"
            :label="item.contentsName"
            :value="item.contentsValue"
          >
          </el-option>
        </el-select>
      </p>
      <p style="margin-bottom: 20px">
        功能类型：<el-select v-model="functionvalue" placeholder="请选择">
          <el-option
            v-for="item in functionoptions"
            :key="item.contentsValue"
            :label="item.contentsName"
            :value="item.contentsValue"
          >
          </el-option>
        </el-select>
      </p>

      <div class="button-container">
        <el-button
          class="but"
          size="small"
          type="primary"
          @click="handleConfirm"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <!-- 关联 -->
    <el-drawer
      title="新增"
      :visible.sync="drawer"
      size="23%"
      :with-header="true"
      @close="handleClose"
      class="drawers"
    >
      <div class="drawersDIV">
        <el-input
          size="small "
          placeholder="请输入品牌"
          v-model="brandvalue"
        ></el-input>
        <span>-</span>
        <el-input
          size="small "
          placeholder="请输入型号"
          v-model="modelvalue"
        ></el-input>
        <el-button
          size="small"
          type="primary"
          style="margin-left: 5px"
          @click="fetchData"
          >查询</el-button
        >
        <el-button size="small" @click="newtype('1')">新增</el-button>
        <el-table :data="relevanceData" border style="width: 100%">
          <el-table-column prop="manufacture" label="品牌"> </el-table-column>
          <el-table-column prop="modelNumber" label="型号"> </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button
                @click="handleClick(scope.row)"
                type="text"
                size="small"
                >编辑</el-button
              >
              <el-button type="text" @click="DELpingpai(scope.row)" size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          @size-change="drawerhandleSizeChange"
          @current-change="drawerhandleCurrentChange"
          :current-page.sync="pageNum"
          :page-size="pageSize"
          :pager-count="5"
          layout="prev, pager, next"
          :total="drawertotal"
          class="fenye"
        >
        </el-pagination>
      </div>
    </el-drawer>

    <el-dialog
      title="新增部件"
      :visible.sync="relevanceVisible"
      width="400px"
      :before-close="handleClose"
    >
      <p class="maintain">
        <span class="two"> 品牌：</span>
        <span class="one"
          ><el-input v-model="brand" size="small"></el-input
        ></span>
      </p>
      <p class="maintain">
        <span class="two"> 型号：</span
        ><span class="one"
          ><el-input v-model="guige" size="small"></el-input
        ></span>
      </p>
      <h3 style="font-weight: 600; margin-bottom: 10px;">轴承参数信息</h3>
      <p class="maintain">
        <span class="two"> 滚动体数量：</span>
        <span class="one">
          <el-input
            :disabled="zcShow != 1"
            v-model="quantity"
            size="small"
            @input="validateDecimal('quantity')"
          ></el-input>
        </span>
      </p>
      <p class="maintain">
        <span class="two"> 滚动体直径/mm：</span>
        <span class="one">
          <el-input
            :disabled="zcShow != 1"
            v-model="diameter"
            size="small"
            @input="validateDecimal('diameter')"
          ></el-input>
        </span>
      </p>
      <p class="maintain">
        <span class="two">节圆直径/mm：</span>
        <span class="one">
          <el-input
            :disabled="zcShow != 1"
            v-model="section"
            size="small"
            @input="validateDecimal('section')"
          ></el-input>
        </span>
      </p>
      <p class="maintain">
        <span class="two"> 接触角°：</span>
        <span class="one">
          <el-input
            :disabled="zcShow != 1"
            v-model="contact"
            size="small"
            @input="validateDecimal('contact')"
          ></el-input>
        </span>
      </p>

      <div class="button-container">
        <el-button class="but" size="small" type="primary" @click="Glsubmit">
          确定
        </el-button>
      </div>
    </el-dialog>
    <!-- 非 -->
    <el-drawer
      title="新增"
      :visible.sync="notdrawer"
      size="22%"
      :with-header="true"
      class="drawers"
    >
      <div class="drawersDIV">
        <el-button
          style="margin-bottom: 10px"
          size="small"
          @click="newtype('2')"
          >新增</el-button
        >
        <el-table :data="nothaveData" border style="width: 100%">
          <el-table-column prop="contentsName" label="属性名称">
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button @click="compile(scope.row)" type="text" size="small"
                >编辑</el-button
              >
              <el-button type="text" @click="DELshuxing(scope.row)" size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>

    <el-dialog
      title="新增部件"
      :visible.sync="maintainVisible"
      width="22%"
      :before-close="handleClose"
    >
      <p class="maintain">
        名称：<span class="one"
          ><el-input v-model="bujianval" size="small"></el-input></span
        ><span class="Sptwo">
          <el-button class="but" size="small" type="primary" @click="submit">
            确定
          </el-button></span
        >
      </p>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDictList,
  createUnitDict,
  getUnitDictConstantsPage,
  delUnitDict,
  createUnitDictProperty,
  getUnitDictConstantsList,
  delUnitDictProperty,
  updateUnitDictProperty,
  saveUnitDictBrandModel,
  getUnitDictBrandModelPage,
  delUnitDictBrandModel,
  updateUnitDictBrandModel,
} from "@/api/maintain.js";

export default {
  data() {
    return {
      nameOfparts: "",
      tableData: [],
      drawer: false,
      notdrawer: false,
      dialogVisible: false,
      maintainVisible: false,
      relevanceVisible: false,
      modulevalue: "",
      moduleoptions: [],
      namevalue: "",
      nameoptions: [],
      functionvalue: "",
      functionoptions: [],
      checked: "0",
      drawervalue: "",
      brand: "",
      guige: "",
      rowList: {},
      bujianval: "",
      nothaveData: [],
      editType: "",
      currentRow: "",
      compilerow: {},
      total: 0,
      drawertotal: 0,
      pageNum: 1,
      pageSize: 10,
      relevanceData: [],
      drawerList: {},
      brandvalue: "",
      modelvalue: "",
      pprow: {},

      quantity: "",
      diameter: "",
      section: "",
      contact: "",
      zcShow: "",
    };
  },
  created() {
    this.GETquery();
    this.GETmokuai();
  },
  methods: {
    validateDecimal(field) {
      this[field] = this[field]
        .replace(/[^0-9.]/g, "") // 只允许输入数字和小数点
        .replace(/^(\d*\.?\d*).*$/, "$1") // 只保留第一个小数点后面的数字
        .replace(/(\..*)\./g, "$1"); // 只能有一个小数点
    },

    load() {
      this.$message.success("加载下一页");
      this.tableData = this.tableData.concat(exampleData);
      //此时也可以调用接口，然后做数组的拼接
    },
    // 查询
    GETquery() {
      const params = {
        contentsName: this.nameOfparts,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      getUnitDictConstantsPage(params).then((res) => {
        this.tableData = res.data.list;
        this.total = res.data.totalSize;
      });
    },
    // 获取属性
    GETmokuai() {
      getDictList({ dictType: 3 }).then((res) => {
        this.moduleoptions = res.data;
      });
      getDictList({ dictType: 4 }).then((res) => {
        this.nameoptions = res.data;
      });
      getDictList({ dictType: 5 }).then((res) => {
        this.functionoptions = res.data;
      });
    },
    // 打开新增
    newly() {
      this.dialogVisible = true;
    },

    // 新增属性
    handleConfirm() {
      // 构建 params 对象
      const params = {
        associatedFunctionType: this.functionvalue,
        contentsDictKey: this.namevalue,
        contentsName:
          this.nameoptions.find((item) => item.contentsValue === this.namevalue)
            ?.contentsName || "", // 赋值nameoptions当前选中的label
        unitModule: this.modulevalue,
        parentId: 0,
      };

      // 验证 params 中的字段是否为空
      if (
        !params.associatedFunctionType ||
        !params.contentsDictKey ||
        !params.contentsName ||
        !params.unitModule
      ) {
        this.$message({
          message: "请确保所有字段都已填写！",
          type: "warning",
        });
        return; // 阻止提交
      }

      // 提交数据
      createUnitDict(params).then((res) => {
        if (res.status === true) {
          this.$message({
            message: "恭喜你，这是一条成功消息",
            type: "success",
          });
          this.dialogVisible = false;
          this.GETquery();
          this.handleClose();
        }
      });
    },

    // 删除
    ONdelete(row) {
      this.$confirm(
        `确定要删除该项吗？（部件模块：${row.unitModuleName}，部件名称：${row.contentsName}）`,
        "删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // Proceed with deletion after confirmation
          const params = {
            contentsType: row.contentsType,
            id: row.id,
          };
          delUnitDict(params).then((res) => {
            if (res.status === true) {
              this.tableData = this.tableData.filter(
                (item) => item.id !== row.id
              );
              this.GETquery();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message({
                type: "error",
                message: "删除失败，请稍后再试。",
              });
            }
          });
        })
        .catch(() => {
          // User canceled the deletion
          this.$message({
            type: "info",
            message: "删除已取消。",
          });
        });
    },

    // 分页
    handleSizeChange(pageSize) {
      this.pageSize = pageSize; // 更新每页显示条数
      this.GETquery(); // 重新获取数据
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum; // 更新当前页
      this.GETquery(); // 重新获取数据
    },

    // 常用类型
    ONallocation(row) {
      this.rowList = row;
      this.notdrawer = true;
      getUnitDictConstantsList({
        contentsType: this.rowList.contentsType,
      }).then((res) => {
        this.nothaveData = res.data;
      });
    },

    // 删除常用
    DELshuxing(row) {
      const params = {
        updateBy: row.updateBy,
        id: row.id,
      };
      delUnitDictProperty(params).then((res) => {
        this.nothaveData = this.nothaveData.filter(
          (item) => item.id !== row.id
        );
      });
    },

    // 编辑常用
    compile(row) {
      this.maintainVisible = true;
      this.bujianval = row.contentsName;
      this.compilerow = row;
      this.editType = "edit"; // 设置编辑模式
    },
    // 提交
    submit() {
      const params = {
        contentsName: this.bujianval,
        contentsType: this.rowList.contentsType,
        parentId: this.rowList.id,
        unitModule: this.rowList.unitModule,
        contentsDictKey: 0,
      };
      console.log(params, "1");

      if (this.editType === "edit") {
        // 编辑操作
        const updateParams = {
          contentsName: this.bujianval,
          id: this.compilerow.id, // 编辑时需要传递项的 ID
          updateBy: 0, // 更新人的 ID（如果需要）
        };
        console.log(updateParams, "2");
        updateUnitDictProperty(updateParams).then((res) => {
          this.maintainVisible = false;
          getUnitDictConstantsList({
            contentsType: this.rowList.contentsType,
          }).then((res) => {
            this.nothaveData = res.data;
          });
        });
      } else {
        // 新增操作
        createUnitDictProperty(params).then((res) => {
          this.maintainVisible = false;
          getUnitDictConstantsList({
            contentsType: this.rowList.contentsType,
          }).then((res) => {
            this.nothaveData = res.data;
          });
        });
      }
      this.handleClose();
    },
    // 品牌

    drawerhandleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },

    drawerhandleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.fetchData();
    },

    fetchData() {
      const params = {
        contentsDictKey: this.drawerList.contentsDictKey,
        manufacture: this.brandvalue,
        modelNumber: this.modelvalue,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      getUnitDictBrandModelPage(params).then((res) => {
        this.relevanceData = res.data.list;
        this.drawertotal = res.data.totalSize;
      });
    },

    ONbrand(row) {
      this.drawer = true;
      this.zcShow = row.contentsDictKey;
      console.log(row, 1111);

      this.drawerList = row;
      console.log(row);
      this.fetchData();
    },

    // 提交品牌
    Glsubmit() {
      const params = {
        manufacture: this.brand,
        modelNumber: this.guige,
        unitType: this.drawerList ? this.drawerList.contentsDictKey : "", // 确保 this.drawerList 存在
        rollsNumbe: this.quantity,
        rollsDiameter: this.diameter,
        circleDiameter: this.section,
        thetaDeg: this.contact,
      };
      console.log(params, "params");

      return;
      if (!params.manufacture || !params.modelNumber || !params.unitType) {
        this.$message({
          message: "请确保所有字段都已填写！",
          type: "warning",
        });
        return;
      }

      if (this.editType === "edit") {
        // Edit operation
        const updateParams = {
          id: this.pprow.id, // The ID of the item being edited
          manufacture: params.manufacture,
          modelNumber: params.modelNumber,
          unitType: params.unitType,
          rollsNumbe: params.rollsNumbe,
          rollsDiameter: params.rollsDiameter,
          circleDiameter: params.circleDiameter,
          thetaDeg: params.thetaDeg,
        };
        updateUnitDictBrandModel(updateParams).then((res) => {
          if (res.status === true) {
            this.$message({
              message: "更新成功！",
              type: "success",
            });
            this.notdrawer = false;
            this.handleClose();
            this.editType = null; // Reset editType after a successful edit
            if (this.drawerList) {
              this.ONbrand(this.drawerList);
            } else {
              this.$message({
                message: "未选择有效的部件信息，无法更新相关数据。",
                type: "error",
              });
            }
          }
        });
      } else {
        // New entry
        saveUnitDictBrandModel(params).then((res) => {
          if (res.status === true) {
            this.$message({
              message: "恭喜你，这是一条成功消息",
              type: "success",
            });
            this.notdrawer = false;
            this.handleClose();
            if (this.drawerList) {
              this.ONbrand(this.drawerList);
            } else {
              this.$message({
                message: "未选择有效的部件信息，无法更新相关数据。",
                type: "error",
              });
            }
          }
        });
      }
    },

    //删除品牌
    DELpingpai(row) {
      this.$confirm("确定删除该品牌吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delUnitDictBrandModel({ id: row.id }).then((res) => {
            if (res.status === true) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.relevanceData = this.relevanceData.filter(
                (item) => item.id !== row.id
              );
            } else {
              this.$message({
                type: "error",
                message: "删除失败，请重试！",
              });
            }
          });
        })
        .catch(() => {
          // 用户点击了"取消"
          this.$message({
            type: "info",
            message: "已取消删除操作",
          });
        });
    },

    handleClick(row) {
      this.pprow = row;
      this.relevanceVisible = true;
      this.brand = row.manufacture;
      this.guige = row.modelNumber;
      this.editType = "edit"; // 设置编辑模式
    },

    // 清空选项
    handleClose() {
      this.modulevalue = "";
      this.namevalue = "";
      this.functionvalue = "";
      this.bujianval = "";
      this.brand = "";
      this.guige = "";
      this.brandvalue = "";
      this.modelvalue = "";
      this.dialogVisible = false;
      this.maintainVisible = false;
      this.relevanceVisible = false;
      this.drawer = false;

      this.quantity = "";
      this.diameter = "";
      this.section = "";
      this.contact = "";
      this.zcShow = "";
    },

    newtype(type) {
      if (type === "1") {
        this.relevanceVisible = true;
      } else if (type === "2") {
        this.maintainVisible = true;
      }
    },
    onlyNumberFilter(value) {
      const newValue = value.replace(/[^\d]/g, ""); // 过滤非数字字符
      return newValue;
    },
  },
};
</script>

<style lang="scss" scoped>
.inquire {
  display: flex;
  justify-content: space-between;

  .condition {
    display: flex;

    p {
      width: 80px;
      line-height: 32px;
    }

    .el-input {
      width: 150px;
      margin-right: 20px;
    }
  }
}

.assemblyList {
  margin: 20px 0;
}

.fenye {
  margin: 20px auto;
  text-align: center;
}

.button-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;

  .but {
    width: 100px;
  }
}

.drawers {
  .drawersDIV {
    padding: 0 20px;
    margin-bottom: 20px;
  }

  .el-input {
    width: 100px;
    // margin-right: 20px;
    margin-bottom: 20px;
  }
}

.maintain {
  margin-bottom: 20px;

  .two {
    width: 120px;
    display: inline-block;
    text-align: right;
  }
  .el-input {
    width: 220px;
  }

  .Sptwo {
    margin-left: 10px;
  }
}
</style>