<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-row>
        <el-form-item label="硬件编码" prop="hardwareCode">
          <el-input
            v-model="queryParams.hardwareCode"
            placeholder="请输入硬件编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="硬件名称" prop="hardwareName">
          <el-input
            v-model="queryParams.hardwareName"
            placeholder="请输入硬件名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择硬件状态"
            clearable
          >
            <el-option
              v-for="dict in dict.type.hardware_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="硬件类型" prop="hardwareTypeId">
          <treeselect
            style="width: 215px"
            v-model="queryParams.hardwareTypeId"
            :options="hardwareTypeOption"
            :show-count="true"
            placeholder="请选择硬件类型"
          />
        </el-form-item>
      </el-row>
      <el-form-item label="规格型号" prop="hardwareSpec">
        <el-input
          v-model="queryParams.hardwareSpec"
          placeholder="请输入规格型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="createTime"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
          style="width: 540px"
        >
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="所属车间" prop="status">
        <el-select
          v-model="queryParams.workshopName"
          placeholder="请选择所属车间"
          clearable
          @change="workShopChangequery"
        >
          <el-option
            v-for="dict in this.workshopOption"
            :key="dict.key"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item style="margin-left: 50px">
        <el-button
          v-no-more-click
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button
          v-no-more-click
          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
          v-no-more-click
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:hw:information:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button v-no-more-click
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes:dv:repair:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          v-no-more-click
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:hw:information:batchremove']"
          >批量删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="repairList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="硬件编码"
        width="120px"
        align="center"
        prop="hardwareCode"
      />
      <el-table-column
        label="硬件名称"
        width="150px"
        align="center"
        prop="hardwareName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="硬件类型"
        align="center"
        prop="hardwareTypeName"
      />
      <el-table-column label="规格型号" align="center" prop="hardwareSpec" />
      <!-- <el-table-column label="所属车间" align="center" prop="workshopName" /> -->
      <el-table-column label="硬件状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.hardware_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="启用时间"
        align="center"
        prop="activationTime"
        width="120"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.activationTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="可用次数" align="center" prop="availableTimes" />
      <el-table-column label="已用次数" align="center" prop="usedTimes" />
      <el-table-column label="可用寿命" align="center" prop="availableLife" />
      <el-table-column label="已用寿命" align="center" prop="usedLife" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:hw:information:edit']"
            >编辑</el-button
          >
          <el-button
            v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:hw:information:remove']"
            >删除</el-button
          >
          <!--          <el-button v-no-more-click size="mini" type="text">预览</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改设备维修单对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1100px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="硬件编码" prop="hardwareCode">
              <el-input
                v-model="form.hardwareCode"
                placeholder="请输入硬件编码"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label-width="80">
              <el-switch
                v-model="autoGenFlag"
                active-color="#13ce66"
                active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)"
                v-if="optType != 'view'"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="硬件类型" prop="hardwareTypeId">
              <treeselect
                v-model="form.hardwareTypeId"
                :options="hardwareTypeOption"
                @input="onSelectChange"
                :show-count="true"
                placeholder="请选择硬件类型"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="硬件名称" prop="hardwareName">
              <el-input
                v-model="form.hardwareName"
                placeholder="请输入硬件名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="规格型号" prop="hardwareSpec">
              <el-input
                v-model="form.hardwareSpec"
                placeholder="请输入规格型号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="可用次数" prop="availableTimes">
              <el-input
                v-model="form.availableTimes"
                placeholder="请输入可用次数"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="已用次数" prop="usedTimes">
              <el-input
                v-model="form.usedTimes"
                placeholder="请输入已用次数"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="可用寿命" prop="availableLife">
              <el-input
                v-model="form.availableLife"
                placeholder="请输入可用寿命"
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="已用寿命" prop="usedLife">
              <el-input v-model="form.usedLife" placeholder="请输入已用寿命" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="启用日期" prop="activationTime">
              <el-date-picker
                clearable
                v-model="form.activationTime"
                style="width: 100%"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择启用日期"
              >
              </el-date-picker> </el-form-item
          ></el-col>
          <el-col :span="11">
            <!-- <el-form-item label="所属车间" prop="workshopName">
              <el-select
                v-model="form.workshopName"
                placeholder="请选择所属车间"
                clearable
                style="width: 100%"
                @change="workShopChange"
              >
                <el-option
                  v-for="dict in this.workshopOption"
                  :key="dict.key"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item> -->
            <el-form-item label="状态" prop="status">
              <el-radio v-model="form.status" label="1" v-removeAriaHidden
                ><img
                  src="@/assets/images/success.png"
                  alt=""
                  class="imgstatus"
                />
                在线</el-radio
              >
              <el-radio v-model="form.status" v-removeAriaHidden label="2"
                ><img
                  src="@/assets/images/error.png"
                  alt=""
                  class="imgstatus"
                />
                离线</el-radio
              >
              <el-radio v-model="form.status" v-removeAriaHidden label="3"
                ><img src="@/assets/images/warn.png" alt="" class="imgstatus" />
                异常</el-radio
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button v-no-more-click @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listHardware,
  addHardware,
  updateHardware,
  delHardware,
  getHardwareInfo,
  listAllWorkshop,
} from "@/api/mes/hw/hardwareinfo";
import { genCode } from "@/api/system/autocode/rule";
import { listHanrwareType } from "@/api/mes/hw/hadrwareType";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "hardwareinfo",
  dicts: ["hardware_status"],
  // components: { Repairline, MachinerySelectSingle },
  components: { Treeselect },
  data() {
    return {
      autoGenFlag: false,
      optType: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      codes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备维修单表格数据
      repairList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      createTime: "",
      queryParams: {
        current: 1,
        size: 10,
        hardwareCode: "",
        hardwareName: "",
        status: "",
        hardwareTypeName: "",
        hardwareSpec: "",
        startTime: "",
        endTime: "",
        workshopName: "",
        workshopCode: "",
        workshopId: "",
      },
      queryTypeParams: {
        enableFlag: "y",
      },
      workshopOption: [],
      hardwareTypeOption: [],
      // 表单参数
      form: {
        hardwareTypeId: 0,
        workshopCode: 0,
        workshopId: 0,
        hardwareTypeName: "",
      },
      // 表单校验
      rules: {
        hardwareCode: [
          { required: true, message: "硬件编码不能为空", trigger: "blur" },
        ],
        hardwareName: [
          { required: true, message: "硬件名称不能为空", trigger: "blur" },
        ],
        hardwareTypeId:[
          { required: true, message: "硬件类型不能为空", trigger: "blur" },
        ]
      },
      // 日期选择
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      value2: "",
      // 新增状态
      radio: 3,
      EditId: 0, //修改判断
      cascaderOptions: [], // 转换后的数据
      flatHardwareTypeOption: [], // 用于快速查找
    };
  },
  created() {
    this.getList();
    this.getHardwareTypeList();
    this.convertToTreeStructure();
  },
  methods: {
    // 格式化日期查询数据
    formatDate(date) {
      if (date && date instanceof Date && !isNaN(date)) {
        // 使用本地时间
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
          2,
          "0"
        )}-${String(date.getDate()).padStart(2, "0")}`;
      }
      return null;
    },
    /** 查询设备维修单列表 */

    getList() {
      this.loading = true;
      // 格式化日期并更新 queryParams
      if (Array.isArray(this.createTime) && this.createTime.length === 2) {
        this.queryParams.startTime = this.formatDate(this.createTime[0]);
        this.queryParams.endTime = this.formatDate(this.createTime[1]);
      }

      listHardware(this.queryParams).then((response) => {
        this.repairList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
      //   车间数据
      listAllWorkshop().then((response) => {
        this.workshopOption = response.data.map((item) => {
          return {
            label: item.workshopName,
            value: item.workshopId,
            key: item.workshopCode,
          };
        });
      });
    },
    // 获取硬件类型-所有
    getHardwareTypeList() {
      const data = {
        current: 1,
        size: 10000,
      };
      listHanrwareType(data).then((response) => {
        // console.log(response, "Type");
        this.flatHardwareTypeOption = response.data.records; // 保存扁平数据
        this.hardwareTypeOption = this.convertToTreeStructure(
          response.data.records
        );
      });
    },

    // 将扁平数据转换为树形结构
    convertToTreeStructure(data) {
      const map = {};
      const tree = [];

      // console.log(data, 'convertToTreeStructure-data');

      data.forEach((item) => {
        map[item.id] = {
          id: item.id,
          label: item.hardwareTypeName,
          children: [],
        };
      });

      data.forEach((item) => {
        const node = map[item.id];
        if (item.parentTypeId === "0") {
          tree.push(node);
        } else {
          const parent = map[item.parentTypeId];
          if (parent) {
            parent.children.push(node);
          }
        }
      });

      return tree;
    },
    // 处理选择变化
    onSelectChange(selectedId) {
      this.form.hardwareTypeId = selectedId;

      // 查找对应的 hardwareTypeName
      const selectedOption = this.flatHardwareTypeOption.find(
        (option) => option.id === selectedId
      );
      if (selectedOption) {
        this.form.hardwareTypeName = selectedOption.hardwareTypeName;
      } else {
        // console.error('Selected ID not found:', selectedId);
      }

      // console.log('Selected ID:', selectedId);
      // console.log('Selected Name:', this.form.hardwareTypeName);
    },
    // 车间下拉 --新增表单
    workShopChange(val) {
      // console.log(val, "val");

      this.form.workshopId = val;
      const item = this.workshopOption.find((item) => {
        return item.value == val ? item.key : null;
      });
      // console.log(item, "item");
      this.form.workshopCode = item.key;
      this.form.workshopName = item.label;
    },
    workShopChangequery(val) {
      // console.log(val, "查询下拉");
      this.queryParams.workshopId = val;
      const item = this.workshopOption.find((item) => {
        return item.value == val ? item.key : null;
      });

      this.queryParams.workshopCode = item.key;
      this.queryParams.workshopName = item.label;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        hardwareCode: "",
        hardwareName: "",
        status: "",
        hardwareTypeName: "",
        hardwareSpec: "",
        createTime: "",
        workshopName: "",
        workshopId: "",
        workshopCode: null,
      };

      this.autoGenFlag = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.workshopCode = "";
      this.queryParams.workshopName = "";
      this.queryParams.workshopId = "";
      this.createTime = ""; //之所以不把这个值放到queryParams是因为会被携带到参数里create Time[0]这样的内容携带进去
      this.queryParams.startTime = "";
      this.queryParams.endTime = "";
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.codes = selection.map((item) => item.hardwareCode);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.EditId = null;
      this.title = "新增硬件信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.EditId = row.id || this.ids;
      getHardwareInfo(this.EditId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "编辑硬件信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.EditId != null) {
            updateHardware(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // console.log(this.form, "form");
            addHardware(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.EditId = null;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const repairIds = row.id || this.ids;
      const repairCodes = row.hardwareCode || this.codes;
      this.$modal
        .confirm('是否确认删除硬件编码为"' + repairCodes + '"的数据项？')
        .then(function () {
          return delHardware(repairIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "dv/repair/export",
        {
          ...this.queryParams,
        },
        `repair_${new Date().getTime()}.xlsx`
      );
    },

    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("HARDWARE_CODE").then((response) => {
          this.form.hardwareCode = response;
        });
      } else {
        this.form.hardwareCode = null;
      }
    },
  },
};
</script>
<style scoped>
.imgstatus {
  position: relative;
  top: 1px;
  left: 0px;
}
/deep/ .el-radio__inner {
  border-radius: 2px;
}
/deep/.el-radio__input.is-checked .el-radio__inner::after {
  content: "";
  width: 8px;
  height: 3px;
  border: 1px solid white;
  border-top: transparent;
  border-right: transparent;
  text-align: center;
  display: block;
  position: absolute;
  top: 3px;
  left: 2px;
  transform: rotate(-45deg);
  border-radius: 0pc;
  background: none;
}
</style>
