<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="visibleSelect ? '物资柜' : '绑定物资柜'"
        prop="materialsCabinetId"
      >
        <el-select
          style="width: 215px"
          :disabled="visibleSelect"
          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 label="物资名称" prop="materialsName">
        <el-input
          style="width: 215px"
          v-model="queryParams.materialsName"
          placeholder="请输入物资名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资类型" prop="materialsTypeId">
        <treeselect
          style="width: 215px"
          v-model="queryParams.materialsTypeId"
          :options="machinerytypeOptions"
          :normalizer="normalizer"
          placeholder="请选择物资类型"
        />
      </el-form-item>
      <el-form-item label="物资规格种类" prop="propertyId">
        <el-select
          style="width: 215px"
          v-model="queryParams.propertyId"
          placeholder="请选择物资规格种类"
          @change="handlePropertyChange"
        >
          <el-option
            v-for="property in PropertyList"
            :key="property.propertyId"
            :label="property.propertyName"
            :value="property.propertyId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物资规格" prop="recordId">
        <el-select
          style="width: 215px"
          v-model="queryParams.recordId"
          placeholder="请选择物资规格"
          :disabled="!queryParams.propertyId"
        >
          <el-option
            v-for="value in filteredPropertyValues"
            :key="value.recordId"
            :label="value.valueName"
            :value="value.recordId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="RFID" prop="materialsRfid">
        <el-input
          style="width: 215px"
          v-model="queryParams.materialsRfid"
          placeholder="请输入RFID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
        <el-input
          style="width: 215px"
          v-model="queryParams.supplier"
          placeholder="请输入供应商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="有效期截止" prop="">
        <el-date-picker
          style="width: 215px"
          :default-time="['00:00:00', '23:59:59']"
          v-model="createTime"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
          @change="handleClearTime"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否在柜中" prop="loanState">
        <el-select
          style="width: 215px"
          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="status">
        <el-select
          style="width: 215px"
          v-model="queryParams.status"
          placeholder="物资状态"
        >
          <el-option
            v-for="dict in dict.type.material_info_status"
            :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:materials:add']"
          >新增
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          v-no-more-click
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleImport"
          v-hasPermi="['iscs:materials:import']"
          >批量新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="this.cabinetId"
          v-no-more-click
          type="primary"
          plain
          icon="el-icon-link"
          size="mini"
          @click="handleBind"
          v-hasPermi="['iscs:materials: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="['iscs:materials:remove']"
          >批量删除
        </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="visibleSelect ? '物资柜' : '绑定物资柜'"
        align="center"
        prop="cabinetName"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.cabinetName">{{ scope.row.cabinetName }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="物资编号" align="center" prop="materialsId">
      </el-table-column>
      <el-table-column label="物资名称" align="center" prop="materialsName" />
      <el-table-column
        label="物资类型"
        align="center"
        prop="materialsTypeName"
      />
      <el-table-column
        label="物资规格种类"
        align="center"
        prop="propertiesProperty"
      />
      <el-table-column label="物资规格" align="center" prop="propertiesValue" />
      <el-table-column label="物资图片" prop="materialsTypePicture" width="90">
        <template slot-scope="scope">
          <div class="img-box" v-if="scope.row.materialsTypePicture">
            <el-image
              style="width: 50px; height: 50px"
              :preview-teleported="true"
              class="images"
              :hide-on-click-modal="true"
              :src="scope.row.materialsTypePicture"
              :zoom-rate="1.2"
              :preview-src-list="[scope.row.materialsTypePicture]"
              :initial-index="1"
              fit="cover"
            >
            </el-image>
            <i class="el-icon-zoom-in" id="eyeicon"></i>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="RFID" align="center" prop="materialsRfid">
        <template slot-scope="scope">
          <span v-if="scope.row.materialsRfid">{{
            scope.row.materialsRfid
          }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="supplier">
      </el-table-column>
      <!--      <el-table-column label="所属柜" align="center" prop="cabinetName" />-->
      <el-table-column label="有效期截止" align="center" prop="expirationDate">
        <template slot-scope="scope">
          {{ scope.row.expirationDate }}
        </template>
      </el-table-column>
      <el-table-column label="是否在柜中" align="center" prop="loanState">
        <template slot-scope="scope">
          <!--          <dict-tag-->
          <!--            :options="dict.type.material_status"-->
          <!--            :value="scope.row.loanState"-->
          <!--          />-->
          <img
            src="@/assets/images/柜中.png"
            v-if="scope.row.loanState == '1'"
            alt=""
            style="width: 30px; height: 30px"
          />
          <img
            src="@/assets/images/柜外.png"
            v-if="scope.row.loanState == '0'"
            alt=""
            style="width: 30px; height: 30px"
          />
          <!-- <span v-if="scope.row.loanState == '0'">-</span>
          <span v-if="scope.row.loanState == '1'">√</span> -->
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.material_info_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <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:materials:edit']"
            >修改
          </el-button>
          <el-button
            v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iscs:materials:remove']"
            >删除
          </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 :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="materialsCabinetId">
              <el-select
                :disabled="visibleSelect"
                style="width: 348px"
                v-model="form.materialsCabinetId"
                placeholder="请选择绑定物资柜"
              >
                <el-option
                  v-for="dict in cabinets"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物资名称" prop="materialsName">
              <el-input
                v-model="form.materialsName"
                placeholder="请输入物资名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物资类型" prop="materialsTypeId">
              <treeselect
                style="width: 350px"
                v-model="form.materialsTypeId"
                :options="machinerytypeOptions"
                :normalizer="normalizer"
                placeholder="选择物资类型"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="RFID" prop="materialsRfid">
              <el-input
                v-model="form.materialsRfid"
                placeholder="请输入物资RFID"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <el-input v-model="form.supplier" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期截止" prop="expirationDate">
              <el-date-picker
                v-model="form.expirationDate"
                type="date"
                placeholder="选择日期"
                :picker-options="FormpickerOptions"
                @change="handleClearTime"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物资规格" prop="properties">
              <div
                v-for="(property, index) in PropertyList"
                :key="property.propertyId"
                class="property-container"
              >
                <h3>{{ property.propertyName }}</h3>
                <div class="property-values">
                  <!-- 循环渲染属性值 -->
                  <div
                    v-for="(value, valueIndex) in PropertyValueList.filter(
                      (v) => v.propertyId === property.propertyId
                    )"
                    :key="value.recordId"
                    :class="[
                      'property-value',
                      {
                        selected:
                          selectedValues[property.propertyId] ===
                          value.recordId,
                      },
                    ]"
                    @click="selectValue(property.propertyId, value.recordId)"
                  >
                    {{ value.valueName }}
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="height: 110px">
            <el-form-item label="物资图片" prop="materialsTypePicture">
              <div class="img-box2" v-if="form.materialsTypePicture">
                <el-image
                  style="width: 90px; height: 90px"
                  :preview-teleported="true"
                  class="images"
                  :hide-on-click-modal="true"
                  :src="form.materialsTypePicture"
                  :zoom-rate="1.2"
                  :preview-src-list="[form.materialsTypePicture]"
                  :initial-index="1"
                  fit="cover"
                >
                </el-image>
                <i class="el-icon-zoom-in" id="eyeicon"></i>
              </div>
              <span v-else>-</span>
            </el-form-item>
          </el-col>
        </el-row>

      </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>

    <!-- 物资导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="upload.updateSupport"/>-->
          <!--            是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="submitFileForm"
          >确 定
        </el-button>
        <el-button v-no-more-click @click="upload.open = false"
          >取 消
        </el-button>
      </div>
    </el-dialog>

    <!--    绑定物资的弹窗-->
    <el-dialog :visible.sync="openBind" width="1000px" append-to-body>
      <div slot="title" class="dialog-title">
        <i></i>
        <span class="title">绑定物资</span>
      </div>
      <el-table
        :data="dialogMatList"
        @selection-change="handleSelectionBindChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column :sortable="true" label="物资编号" align="center" prop="materialsId" >
        </el-table-column>
        <el-table-column label="物资名称" align="center" prop="materialsName" />
        <el-table-column
          label="物资类型"
          align="center"
          prop="materialsTypeName"
        />
        <el-table-column
          label="物资图片"
          align="center"
          prop="materialsTypePicture"
        >
          <template slot-scope="scope">
            <img
              v-if="scope.row.materialsTypePicture"
              :src="scope.row.materialsTypePicture"
              alt=""
              style="width: 50px; height: 50px"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="RFID" align="center" prop="materialsRfid" />
        <el-table-column label="供应商" align="center" prop="supplier">
        </el-table-column>
        <el-table-column label="有效期" align="center" prop="expirationDate">
          <template slot-scope="scope">
            {{ scope.row.expirationDate }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="loanState">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.material_status"
              :value="scope.row.loanState"
            />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="totalBind > 0"
        :total="totalBind"
        :page.sync="queryParams.current"
        :limit.sync="queryParams.size"
        @pagination="getmatInfoList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="submitBind"
          >确 定
        </el-button>
        <el-button v-no-more-click @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMaterials,
  addMaterials,
  updateMaterials,
  deleteMaterials,
  selectMaterialsById,
  getIsMaterialsCabinets,
  updateMaterialsBinding,
} from "@/api/mes/material/information";
import {
  listType,
  selectMaterialsTypeById,
} from "@/api/mes/material/typeindex";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { genCode } from "@/api/system/autocode/rule";
import Template from "@/views/print/printtemplate/list.vue";
import { getToken } from "@/utils/auth";
import { PropertyPage } from "@/api/mes/standard";
import { PropertyValuePage } from "@/api/mes/standard/propertyForm";

export default {
  name: "Team",
  components: {
    Template,
    Treeselect,
  },
  props: {
    cabinetId: {
      type: String,
      required: false,
    },
  },
  dicts: ["material_status", "material_info_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: {
        current: 1,
        size: 10,
        materialsCode: null,
        materialsName: null,
        materialsRfid: null,
        loanState: null,
        materialsCabinetId: null,
        materialsTypeId: null,
        startExpirationDate: "",
        endExpirationDate: "",
        supplier: null,
        expirationDate: null,
        recordId: null,
        propertyId: null,
      },

      // 查询参数
      queryParamsCabinets: {
        current: 1,
        size: -1,
      },
      FormpickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      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]);
            },
          },
        ],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/iscs/materials/importMaterials",
        // url: process.env.VUE_APP_BASE_API + '/common/upload'
      },

      // 表单参数
      form: {
        materialsCabinetId: null,
      },
      cabinets: [], //物资所属柜
      // 表单校验
      rules: {
        materialsName: [
          { required: true, message: "物资名称不能为空", trigger: "blur" },
        ],
        materialsTypeId: [
          { required: true, message: "物资类型不能为空", trigger: "blur" },
        ],
      },
      machinerytypeOptions: [],
      materialsIds: [], //绑定物资传递的数据
      queryParamsBind: {
        current: 1,
        size: 10,
        materialsCabinetId: 0,
      },
      dialogMatList: [], //绑定物资弹窗el-table数据
      openBind: false,
      totalBind: 0, //弹窗列表总数
      visibleSelect: false,
      PropertyList: [], //属性名
      PropertyValueList: [], //属性值
      selectedValues: {}, // 存储选中的属性值
    };
  },
  watch: {
    "form.materialsTypeId": function (val, old) {
      if (val && val !== old) {
        console.log(val, "watch监听拿到新增时候的值");
        selectMaterialsTypeById(val).then((response) => {
          const data = {
            pageSize: 99999999,
            pageNum: 1,
            propertyId: response.data.propertyIds,
          };
          this.form.materialsTypePicture = response.data.materialsTypePicture;
          PropertyPage(data).then((response) => {
            console.log(response, "获取物资属性名 ");
            this.PropertyList = response.data.records;
          });
          PropertyValuePage(data).then((response) => {
            console.log(response, "获取物资属性值 ");
            this.PropertyValueList = response.data.records;
          });
        });
      }
    },
  },
  created() {
    this.queryParams.materialsCabinetId = this.cabinetId || null;
    if (this.cabinetId) {
      this.visibleSelect = true;
    }
    this.getList();
    this.getTreeselect();
  },
  computed: {
    filteredPropertyValues() {
      if (!this.queryParams.propertyId) {
        return [];
      }
      return this.PropertyValueList.filter(
        (value) => value.propertyId === this.queryParams.propertyId
      );
    },
  },
  mounted() {
    this.materialsCabinets();
  },
  methods: {
    handlePropertyChange(propertyId) {
      // 当属性改变时，重置 recordId
      this.queryParams.recordId = "";
    },
    /* 绑定物资 */
    handleBind() {
      this.openBind = true;
      this.getmatInfoList(); //绑定物资列表数据
    },
    getmatInfoList() {
      listMaterials(this.queryParamsBind).then((response) => {
        this.dialogMatList = response.data.records;
        this.totalBind = response.data.total;
      });
    },
    submitBind() {
      const data = {
        materialsCabinetId: this.cabinetId,
        materialsIds: this.materialsIds,
      };
      updateMaterialsBinding(data).then((res) => {
        console.log(res, "绑定物资");
        if (res.data) {
          this.$message.success("绑定成功");
          this.openBind = false;
        }
      });
    },
    handleSelectionBindChange(selection) {
      this.materialsIds = selection.map((item) => item.materialsId);
    },
    // 物资绑定结束------
    // 格式化日期查询数据
    formatDate(date) {
      if (date && date instanceof Date && !isNaN(date)) {
        // 使用本地时间
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
      return null;
    },
    /** 查询物资信息列表 */
    getList() {
      this.loading = true;
      // 格式化日期并更新 queryParams
      console.log(this.createTime, "this.createTime");
      if (Array.isArray(this.createTime) && this.createTime.length === 2) {
        this.queryParams.startExpirationDate = this.formatDate(
          this.createTime[0]
        );
        this.queryParams.endExpirationDate = this.formatDate(
          this.createTime[1]
        );
      }

      listMaterials(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;
      });
    },
    /** 转换数据结构 */
    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"
        );
      });
      // 这里给查询的数据
      PropertyPage(data).then((response) => {
        console.log(response, "获取物资属性名 ");
        this.PropertyList = response.data.records;
      });
      PropertyValuePage(data).then((response) => {
        console.log(response, "获取物资属性值 ");
        this.PropertyValueList = response.data.records;
      });
    },
    // 选择属性值
    selectValue(propertyId, recordId) {
      // 如果当前选中值和之前选中的相同，直接切换选中状态
      if (this.selectedValues[propertyId] === recordId) {
        this.selectedValues[propertyId] = null;
      } else {
        this.$set(this.selectedValues, propertyId, recordId);
      }
      // 生成 JSON 格式的数据
      const selectionJson = Object.entries(this.selectedValues).map(
        ([propertyId, recordId]) => {
          const property = this.PropertyList.find(
            (p) => p.propertyId === propertyId
          );
          const value = this.PropertyValueList.find(
            (v) => v.recordId === recordId
          );
          return {
            propertyId,
            recordId,
            valueName: value ? value.valueName : "",
            propertyName: property ? property.propertyName : "",
          };
        }
      );
      this.form.properties = JSON.stringify(selectionJson);
      console.log(selectionJson, "生成的属性值json");
    },
    setInitialSelection(data) {
      data.forEach((item) => {
        this.$set(this.selectedValues, item.propertyId, item.recordId);
      });
    },
    //图片上传成功
    handleImgUplaoded(imgUrl) {
      this.form.sipUrl = imgUrl;
    },
    //图片移除
    handleImgRemoved(imgUrl) {
      this.form.sipUrl = null;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openBind = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        materialsName: "",
        createTime: "",
        materialsTypeId: "",
        materialsCabinetId: "",
        expirationDate: "",
        supplier: "",
        materialsRfid: "",
      };
      this.resetForm("form");
      this.autoGenFlag = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.createTime = "";
      this.queryParams.materialsCode = null;
      this.queryParams.materialsName = null;
      this.queryParams.loanState = null;
      this.queryParams.materialsCabinetId = null;
      this.queryParams.materialsTypeId = null;
      this.queryParams.startExpirationDate = null;
      this.queryParams.endExpirationDate = null;
      this.queryParams.materialsRfid = null;
      this.queryParams.supplier = null;
      this.queryParams.propertyId = null;
      this.queryParams.recordId = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.materialsId);
      this.codes = selection.map((item) => item.materialsName);
      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,
          }));
          this.cabinets.push({ value: 0, label: "空" });
        }
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.selectedValues = {}; //新增保持物资规格是清空的
      this.PropertyList = []; //新增保持物资规格是清空的
      this.PropertyValueList = []; //新增保持物资规格是清空的
      this.open = true;
      this.title = "新增物资信息";
      this.optType = "add";
      this.form.materialsTypeId = undefined;
      if (this.visibleSelect) {
        this.form.materialsCabinetId = this.cabinetId;
      }
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      selectMaterialsById(row.materialsId).then((response) => {
        this.form = response.data;
        if (response.data) {
          const data = {
            pageSize: 99999999,
            pageNum: 1,
            propertyId: response.data.propertyIds,
          };
          PropertyPage(data).then((response) => {
            console.log(response, "获取物资属性名 ");
            this.PropertyList = response.data.records;
          });
          PropertyValuePage(data).then((response) => {
            console.log(response, "获取物资属性值 ");
            this.PropertyValueList = response.data.records;
          });
        }
        this.open = true;
        this.title = "修改物资信息";
        this.optType = "edit";
        // 设置 selectedValues
        if (response.data.properties) {
          const JsonData = JSON.parse(response.data.properties);
          this.setInitialSelection(JsonData);
        } else {
          this.selectedValues = {};
        }
      });
    },
    // 有效期参数转换时间类型
    formatDateExpirationDate(dateString) {
      if (!dateString) {
        return null; // 如果传入的是 null 或 undefined，则返回 null
      }
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1，并且补零
      const day = String(date.getDate()).padStart(2, "0"); // 补零

      return `${year}-${month}-${day}`;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.materialsId != null) {
            this.form.expirationDate = this.formatDateExpirationDate(
              this.form.expirationDate
            );
            updateMaterials(this.form).then((response) => {
              console.log(response, "修改返回");
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.expirationDate = this.formatDateExpirationDate(
              this.form.expirationDate
            );
            console.log(this.form, "新增参数");
            addMaterials(this.form).then((response) => {
              console.log(response, "新增返回");
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物资导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "iscs/materials/importTemplate",
        {},
        `md_item_template${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    /** 删除按钮操作 */
    // confirm('是否确认删除编号为"' + materialsCodes + '"的数据项？')
    handleDelete(row) {
      const materialsIds = row.materialsId || this.ids;
      const materialsCodes = row.materialsId || this.ids;
      this.$modal
        .confirm("是否确认删除所选数据项？")
        .then(function () {
          return deleteMaterials(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_CODE").then((response) => {
          this.form.materialsCode = response;
        });
      } else {
        this.form.materialsCode = null;
      }
    },
    //有效期截止 清空函数
    handleClearTime(value) {
      console.log(value, "日期被清空了没");
      if (value == null) {
        this.queryParams.startExpirationDate = null;
        this.queryParams.endExpirationDate = null;
        this.form.expirationDate = null;
      }
    },
  },
};
</script>
<style lang="scss" src="@/assets/styles/dialog-title.scss" scoped></style>
<style lang="scss">
//图片放大
.img-box {
  width: 50px;
  height: 50px;
  position: relative;

  #eyeicon {
    display: none;
  }
}

.img-box:hover {
  background: #000;

  .images {
    opacity: 0.6;
  }

  #eyeicon {
    display: block;
    position: absolute;
    top: 40%;
    left: 40%;
    z-index: 100;
    color: white;
    pointer-events: none;
  }
}

.img-box1 {
  width: 90px;
  height: 90px;
  position: relative;

  #eyeicon {
    display: none;
  }
}

.img-box1:hover {
  background: #000;
  position: absolute;
  top: 62%;

  .images {
    opacity: 0.6;
  }

  #eyeicon {
    display: block;
    position: absolute;
    top: 40%;
    left: 40%;
    z-index: 100;
    color: white;
    pointer-events: none;
  }
}
.img-box2 {
  width: 90px;
  height: 90px;
  position: relative;

  #eyeicon {
    display: none;
  }
}

.img-box2:hover {
  background: #000;
  position: absolute;

  .images {
    opacity: 0.6;
  }

  #eyeicon {
    display: block;
    position: absolute;
    top: 40%;
    left: 40%;
    z-index: 100;
    color: white;
    pointer-events: none;
  }
}
//属性名和属性值样式
.property-container {
  margin-bottom: 20px;
}

.property-values {
  display: flex;
  flex-wrap: wrap;
}

.property-value {
  padding: 10px;
  margin: 5px;
  border: 1px solid #ccc;
  cursor: pointer;
  border-radius: 4px;
}

.property-value.selected {
  border: 1px solid #80b3ff; /* 淡蓝色边框 */
  background-color: #e6f0ff; /* 选中时的背景色 */
}

.el-input-width {
  width: 380px !important;
}
</style>
