<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="物资柜编码" prop="cabinetCode">
        <el-input
          v-model="queryParams.cabinetCode"
          placeholder="请输入物资柜编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资柜名称" prop="cabinetName">
        <el-input
          v-model="queryParams.cabinetName"
          placeholder="请输入物资柜名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="物资状态" prop="loanState">
        <el-select v-model="queryParams.loanState" placeholder="状态">
          <el-option
            v-for="dict in dict.type.material_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物资类型" prop="materialsTypeId">
        <treeselect
          style="width: 318px"
          v-model="queryParams.materialsTypeId"
          :options="machinerytypeOptions"
          :normalizer="normalizer"
          placeholder="请选择物资类型"
        />
      </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"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="所属柜" prop="materialsCabinetId">
        <el-select
          style="width: 348px"
          v-model="queryParams.materialsCabinetId"
          placeholder="请选择所属柜"
        >
          <el-option
            v-for="dict in cabinets"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->

      <el-form-item>
        <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="['iscs:cabinet:add']"
          >新增
        </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:mat:info:batchremove']"
          >批量删除
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="materialsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物资柜编码" align="center" prop="cabinetCode">
      </el-table-column>
      <el-table-column label="物资柜名称" align="center" prop="cabinetName" />
      <!-- <el-table-column
        label="物资类型"
        align="center"
        prop="materialsTypeName"
      /> -->
      <!-- <el-table-column label="所属柜" align="center" prop="cabinetName" /> -->
      <!-- <el-table-column label="物资状态" align="center" prop="loanState">
        <template slot-scope="scope">
          <span>{{ scope.row.loanState == 0 ? "借出" : "柜中" }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="更新时间" align="center" prop="updateTime" />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iscs:cabinet:edit']"
            >编辑
          </el-button>
          <el-button
            v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iscs:cabinet:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pages"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
    <!-- 添加或修改班组对话框 -->
    <el-dialog :visible.sync="open" width="960px" append-to-body>
      <div slot="title" class="dialog-title">
        <i></i>
        <span class="title">{{ title }}</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="物资柜编码" prop="cabinetCode">
              <el-input
                v-model="form.cabinetCode"
                placeholder="请输入物资柜编码"
                style="width: 200px; margin-right: 10px"
              />
              <el-switch
                v-model="autoGenFlag"
                active-color="#13ce66"
                active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="硬件名称" prop="hardwareId">
              <el-select
                style="width: 348px"
                v-model="form.workareaId"
                placeholder="请选择硬件名称"
                clearable
              >
                <el-option
                  v-for="dict in this.hardWareList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物资柜名称" prop="cabinetName">
              <el-input
                v-model="form.cabinetName"
                placeholder="请输入物资柜名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域名称" prop="workareaId">
              <treeselect
                style="width: 350px"
                v-model="form.workareaId"
                :options="workareaOptions"
                :normalizer="normalizer"
                placeholder="选择区域名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
            style="width: 420px"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          v-no-more-click
          type="primary"
          @click="cancel"
          v-if="optType == 'view'"
          >返回</el-button
        >
        <el-button v-no-more-click type="primary" @click="submitForm" v-else
          >确 定</el-button
        >
        <el-button v-no-more-click @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMaterialsCabinet,
  addMaterialsCabinet,
  updateMaterialsCabinet,
  deleteMaterialsCabinet,
  selectMaterialsCabinetById,
} from "@/api/mes/material/lockers.js";
import {
  listWorkarea
} from "@/api/mes/wa/workarea";
import { listType } from "@/api/mes/material/typeindex";
import { listHardware } from "@/api/mes/hw/hardwareinfo";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { genCode } from "@/api/system/autocode/rule";

export default {
  name: "Team",
  components: {
    Treeselect,
  },
  dicts: ["material_status"],
  data() {
    return {
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      codes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班组表格数据
      materialsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      createTime: "",
      queryParams: {
        pages: 1,
        size: 10,
        cabinetCode: null,
        cabinetName: null,
      },
      hardWareList: [],
      queryhwParams: {
        current: 1,
        size: -1,
      },
      // 查询参数
      queryParamsCabinets: {
        current: 1,
        size: -1,
      },
      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]);
            },
          },
        ],
      },

      // 表单参数
      form: {},
      cabinets: [], //物资所属柜
      // 表单校验
      rules: {
        cabinetCode: [
          { required: true, message: "物资柜编码不能为空", trigger: "blur" },
        ],
        cabinetName: [
          { required: true, message: "物资柜名称不能为空", trigger: "blur" },
        ],
      },

      workareaOptions: [],
    };
  },
  created() {
    this.getList();
    this.getHardWare();
    this.getTreeselect();
  },
  mounted() {
    this.materialsCabinets();
  },
  methods: {
    getHardWare() {
      listHardware(this.queryhwParams).then((response) => {
        this.hardWareList = response.data.records.map((item) => {
          return {
            value: item.id,
            label: item.hardwareName,
          };
        });

        console.log(response, this.hardWareList, "获取硬件信息");
      });
    },
    /** 转换数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.materialsTypeId,
        label: node.materialsTypeName,
        children: node.children,
      };
    },
    /** 查询物资类型下拉树结构 */
    getTreeselect() {
      const data = {
        current: 1,
        size: 99999,
      };

      listType(data).then((response) => {
        this.machinerytypeOptions = this.handleTree(
          response.data.records,
          "materialsTypeId",
          "parentId",
          "children"
        );
      });
    },
    // 格式化日期查询数据
    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]);
      }

      getMaterialsCabinet(this.queryParams).then((response) => {
        // console.log(response, "获取物资信息allList ");
        this.materialsList = response.data.records;
        this.total = response.data.total;
        this.machinerytypeList = this.handleTree(
          response.data.records,
          "materialsTypeId",
          "parentId",
          "children"
        );
        this.loading = false;
      });
    },
    //图片上传成功
    handleImgUplaoded(imgUrl) {
      this.form.sipUrl = imgUrl;
    },
    //图片移除
    handleImgRemoved(imgUrl) {
      this.form.sipUrl = null;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        cabinetCode: "",
        cabinetName: "",
      };
      this.resetForm("form");
      this.autoGenFlag = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.createTime = "";
      this.queryParams.cabinetCode = null;
      this.queryParams.cabinetName = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.materialsId);
      this.codes = selection.map((item) => item.cabinetCode);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 物资所属柜
    materialsCabinets() {
      getIsMaterialsCabinets(this.queryParamsCabinets).then((response) => {
        if (response?.data?.records) {
          // 提取 cabinetId 和 cabinetName
          this.cabinets = response.data.records.map((item) => ({
            value: item.cabinetId,
            label: item.cabinetName,
          }));
        }
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增物资信息";
      this.optType = "add";
      this.form.materialsTypeId = undefined;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      selectMaterialsCabinetById(row.cabinetId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "编辑物资信息";
        this.optType = "edit";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.materialsId != null) {
            updateMaterialsCabinet(this.form).then((response) => {
              console.log(response, "修改返回");
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterialsCabinet(this.form).then((response) => {
              console.log(response, "新增返回");
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materialsIds = row.cabinetIds || this.ids;
      const materialsCodes = row.cabinetCode || this.codes;
      this.$modal
        .confirm('是否确认删除编号为"' + materialsCodes + '"的数据项？')
        .then(function () {
          return deleteMaterialsCabinet(materialsIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "cal/team/export",
        {
          ...this.queryParams,
        },
        `team_${new Date().getTime()}.xlsx`
      );
    },

    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("MATERIALS_CABINET").then((response) => {
          this.form.cabinetCode = response;
        });
      } else {
        this.form.cabinetCode = null;
      }
    },
  },
};
</script>
<style lang="scss" src="@/assets/styles/dialog-title.scss" scoped>
.el-input-width {
  width: 380px !important;
}
</style>
