<template>
  <div class="">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="维保" prop="maintenanceId">
        <el-tree-select v-model="queryParams.maintenanceId" :data="maintenanceOptions" :props="{
          value: 'maintenanceId',
          label: 'maintenanceName',
          children: 'children',
        }" value-key="maintenanceId" placeholder="请选择维保" check-strictly filterable clearable @change="handleQuery" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="备件编号/图纸号" prop="sparePartNumber">
        <el-input maxlength="100" v-model="queryParams.sparePartNumber" placeholder="请输入备件编号/图纸号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="备件名称" prop="sparePartName">
        <el-input maxlength="100" v-model="queryParams.sparePartName" placeholder="请输入备件名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="备件规格" prop="sparePartSpecifications">
        <el-input maxlength="100" v-model="queryParams.sparePartSpecifications" placeholder="请输入备件规格" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="备件品牌" prop="sparePartBrand">
        <el-input maxlength="100" v-model="queryParams.sparePartBrand" placeholder="请输入备件品牌" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="备件类型" prop="sparePartStockType">
        <el-select v-model="queryParams.sparePartStockType" placeholder="请选择库存类型" clearable filterable @change="handleQuery">
          <el-option v-for="dict in com_spare_part_stock_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="货物类型" prop="sparePartGoodsType">
                <el-select v-model="queryParams.sparePartGoodsType" placeholder="请选择货物类型" clearable filterable
                    @change="handleQuery">
                    <el-option v-for="dict in com_spare_part_goods_type" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item> -->
      <!-- <el-form-item label="库存总量" prop="sparePartQuantity">
                <el-input maxlength="100" v-model="queryParams.sparePartQuantity" placeholder="请输入库存总量" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="备件单价" prop="sparePartUnitPrice">
                <el-input maxlength="100" v-model="queryParams.sparePartUnitPrice" placeholder="请输入备件单价" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item> -->
      <!-- <el-form-item label="impa" prop="impa">
                <el-input maxlength="100" v-model="queryParams.impa" placeholder="请输入impa" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="min-height: 32px">
      <el-col :span="1.5" v-hasPermi="['sparePart:sparePart:add']">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">
          新增
        </el-button>
      </el-col>

      <!-- <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['sparePart:sparePart:edit']">修改
                </el-button>
            </el-col> -->
      <el-col :span="1.5" v-hasPermi="['sparePart:sparePart:edit']">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改
        </el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['sparePart:sparePart:remove']">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除
        </el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['sparePart:sparePart:export']">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain :icon="showSidebar ? 'DArrowLeft' : 'DArrowRight'" @click="handleToggleShowSidebar">
          {{ showSidebar ? "隐藏" : "显示" }}侧边栏
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="MostlyCloudy" @click="handleSwitchSidebarSpan" v-show="showSidebar">
          侧边栏比例 {{ sidebarSpan }}:{{ 24 - sidebarSpan }}
        </el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="[
        'sparePart:sparePart:in',
        'sparePartAccess:sparePartAccess:add',
      ]">
        <el-button type="warning" plain icon="DocumentAdd" :disabled="multiple" @click="handleAddSparePartAccessDetailsIn">入库
        </el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="[
        'sparePart:sparePart:out',
        'sparePartAccess:sparePartAccess:add',
      ]">
        <el-button type="warning" plain icon="DocumentRemove" :disabled="multiple" @click="handleAddSparePartAccessDetailsOut">出库
        </el-button>
      </el-col>

      <el-col :span="1.5" v-hasPermi="[
        'sparePart:sparePart:apply',
        'sparePartApply:sparePartApply:add',
      ]">
        <el-button type="warning" plain icon="ShoppingBag" :disabled="multiple" @click="handleAddSparePartApply">申领
        </el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="[
        'sparePart:sparePart:in',
        'sparePartAccess:sparePartAccess:add',
      ]">
        <el-badge :value="sparePartRetrievalQuantityInTotal" :hidden="sparePartRetrievalQuantityInTotal == 0">
          <el-button type="warning" plain icon="DocumentAdd" @click="handleOpenSparePartAccessDetailsInDrawer">入库列表
          </el-button>
        </el-badge>
      </el-col>
      <el-col :span="1.5" v-hasPermi="[
        'sparePart:sparePart:out',
        'sparePartAccess:sparePartAccess:add',
      ]">
        <el-badge :value="sparePartRetrievalQuantityOutTotal" :hidden="sparePartRetrievalQuantityOutTotal == 0">
          <el-button type="warning" plain icon="DocumentRemove" @click="handleOpenSparePartAccessDetailsOutDrawer">出库列表
          </el-button>
        </el-badge>
      </el-col>
      <el-col :span="1.5" v-hasPermi="[
        'sparePart:sparePart:apply',
        'sparePartApply:sparePartApply:add',
      ]">
        <el-badge :value="sparePartApplyQuantityTotal" :hidden="sparePartApplyQuantityTotal == 0">
          <el-button type="warning" plain icon="ShoppingBag" @click="handleOpenSparePartApplyDetailsDrawer">
            申领列表
          </el-button>
        </el-badge>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sparePartList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" v-hasPermi="['sparePart:sparePart:edit', 'sparePart:sparePart:remove','sparePart:sparePart:in',
        'sparePartAccess:sparePartAccess:add',
        'sparePart:sparePart:out',
        'sparePart:sparePart:apply',
        'sparePartApply:sparePartApply:add',
      ]" />
      <el-table-column type="expand" width="30">
        <template #default="scope">
          <div class="padding">
            <el-descriptions :column="1">
              <el-descriptions-item label="备件编号/图纸号">
                {{ scope.row.sparePartNumber }}
              </el-descriptions-item>
              <el-descriptions-item label="图片">
                <image-preview :src="scope.row.filePath" :width="50" :height="50" />
              </el-descriptions-item>
              <el-descriptions-item label="备件名称">
                {{ scope.row.sparePartName }}
              </el-descriptions-item>
              <el-descriptions-item label="备件规格">
                {{ scope.row.sparePartSpecifications }}
              </el-descriptions-item>
              <el-descriptions-item label="备件品牌">
                {{ scope.row.sparePartBrand }}
              </el-descriptions-item>
              <el-descriptions-item label="存放位置">
                {{ scope.row.sparePartStorageLocation }}
              </el-descriptions-item>
              <el-descriptions-item label="备件类型">
                <dict-tag :options="com_spare_part_stock_type" :value="scope.row.sparePartStockType" style="display: inline-block" />
              </el-descriptions-item>
              <el-descriptions-item label="备件单价">
                {{ scope.row.sparePartUnitPrice }}元
              </el-descriptions-item>
              <el-descriptions-item label="库存总量">
                {{ scope.row.sparePartQuantity }}{{ scope.row.sparePartUnit }}
              </el-descriptions-item>
              <el-descriptions-item label="备注">
                {{ scope.row.remark }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备件ID" align="center" prop="sparePartId" /> -->
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="维保" align="center" prop="maintenanceId">
        <template #default="scope">
          <TextTag :options="maintenanceList" column="maintenanceId" label="maintenanceName" :value="scope.row.maintenanceId" />
        </template>
      </el-table-column>
      <el-table-column label="备件编号/图纸号" align="center" prop="sparePartNumber" />
      <!-- <el-table-column label="impa" align="center" prop="impa" /> -->
      <el-table-column label="图片" align="center" prop="filePath" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.filePath" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="备件名称" align="center" prop="sparePartName" show-overflow-tooltip />
      <el-table-column label="备件规格" align="center" prop="sparePartSpecifications" show-overflow-tooltip />
      <el-table-column label="备件品牌" align="center" prop="sparePartBrand" />
      <el-table-column label="存放位置" align="center" prop="sparePartStorageLocation" show-overflow-tooltip />
      <el-table-column label="备件类型" align="center" prop="sparePartStockType">
        <template #default="scope">
          <dict-tag :options="com_spare_part_stock_type" :value="scope.row.sparePartStockType" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="货物类型" align="center" prop="sparePartGoodsType">
                <template #default="scope">
                    <dict-tag :options="com_spare_part_goods_type" :value="scope.row.sparePartGoodsType" />
                </template>
            </el-table-column> -->
      <el-table-column label="备件单价" align="center" prop="sparePartUnitPrice" />
      <el-table-column label="库存总量" align="center" prop="sparePartQuantity" />
      <el-table-column label="单位" align="center" prop="sparePartUnit" />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160" fixed="right" v-hasPermi="[
          'sparePart:sparePart:edit',
          'sparePart:sparePart:remove',
          'sparePart:sparePart:in',
          'sparePart:sparePart:out',
          'sparePartAccess:sparePartAccess:add',
          'sparePart:sparePart:apply',
          'sparePartApply:sparePartApply:add',
        ]">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="View" @click="handleView(scope.row)"
                        v-hasPermi="['sparePart:sparePart:query']">详细
                    </el-button> -->

          <!-- <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['sparePart:sparePart:edit']">修改
                    </el-button> -->
          <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['sparePart:sparePart:edit']">修改
          </el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['sparePart:sparePart:remove']">删除
          </el-button>
          <el-button link type="warning" icon="DocumentAdd" @click="addSparePartAccessDetailsIn(scope.row);activeCollapseName = '10';" v-hasPermi="['sparePart:sparePart:in','sparePartAccess:sparePartAccess:add',]">入库
          </el-button>
          <el-button link type="warning" icon="DocumentRemove" @click="addSparePartAccessDetailsOut(scope.row);activeCollapseName = '20';" v-hasPermi="['sparePart:sparePart:out','sparePartAccess:sparePartAccess:add',]">出库
          </el-button>
          <el-button link type="warning" icon="ShoppingBag" @click="addSparePartApplyDetails(scope.row);activeCollapseName = '_30';" v-hasPermi="['sparePart:sparePart:apply','sparePartApply:sparePartApply:add',]">申领
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <div class="margin-tb solid-left solid-right" @click="handleCollapseClick" v-hasPermi="[
      'sparePart:sparePart:edit',
      'sparePart:sparePart:remove',
      'sparePart:sparePart:in',
      'sparePart:sparePart:out',
      'sparePartAccess:sparePartAccess:add',
      'sparePart:sparePart:apply',
      'sparePartApply:sparePartApply:add',
    ]">
      <el-collapse v-model="activeCollapseName" :accordion="true">
        <el-collapse-item :title="`入库列表(${sparePartRetrievalQuantityInTotal})`" name="10" v-hasPermi="[
          'sparePart:sparePart:in',
          'sparePartAccess:sparePartAccess:add',
        ]">
          <template #title>
            <span class="margin-left">{{
              `入库列表(${sparePartRetrievalQuantityInTotal})`
            }}</span>
          </template>
          <SparePartAccessDetailsCard :sparePartAccessType="10" :header="false" @submit="handleOpenSparePartAccessInSubmitDrawer" />
        </el-collapse-item>
        <el-collapse-item :title="`出库列表(${sparePartRetrievalQuantityOutTotal})`" name="20" v-hasPermi="[
          'sparePart:sparePart:out',
          'sparePartAccess:sparePartAccess:add',
        ]">
          <template #title>
            <span class="margin-left">{{
              `出库列表(${sparePartRetrievalQuantityOutTotal})`
            }}</span>
          </template>
          <SparePartAccessDetailsCard :sparePartAccessType="20" :header="false" @submit="handleOpenSparePartAccessOutSubmitDrawer" />
        </el-collapse-item>
        <el-collapse-item :title="`申领列表(${sparePartApplyQuantityTotal})`" name="_30" v-hasPermi="[
          'sparePart:sparePart:apply',
          'sparePartApply:sparePartApply:add',
        ]">
          <template #title>
            <span class="margin-left">{{
              `申领列表(${sparePartApplyQuantityTotal})`
            }}</span>
          </template>
          <SparePartApplyDetailsCard :header="false" @submit="handleOpenSparePartApplySubmitDrawer" />
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- 添加或修改备件对话框 -->
    <el-drawer :title="title" v-model="open" width="800px" size="80vw" append-to-body>
      <el-row :gutter="20">
        <el-col :xs="24" :span="16">
          <el-card shadow="hover" header="表单">
            <el-form ref="sparePartRef" :model="form" :rules="rules" label-width="80px" class="grid col-2">
              <el-form-item label="维保" prop="maintenanceId">
                <el-tree-select filterable v-model="form.maintenanceId" :data="maintenanceOptions" :props="{
                  value: 'maintenanceId',
                  label: 'maintenanceName',
                  children: 'children',
                }" value-key="maintenanceId" placeholder="请选择维保" check-strictly style="width: 100%" @change="handleFormMaintenanceIdChange" />
              </el-form-item>
              <el-form-item label="备件编号" prop="sparePartNumber">
                <!-- <el-input maxlength="100" v-model="form.sparePartNumber" placeholder="请输入备件编号" /> -->
                <el-autocomplete maxlength="100" v-model="form.sparePartNumber" :fetch-suggestions="querySearchSparePartNumber" clearable placeholder="请输入备件编号" style="width: 100%" @select="handleAutocompleteSparePartNumberSelect" />
              </el-form-item>
              <el-form-item label="备件名称" prop="sparePartName">
                <!-- <el-input maxlength="100" v-model="form.sparePartName" placeholder="请输入备件名称" /> -->
                <el-autocomplete maxlength="100" v-model="form.sparePartName" :fetch-suggestions="querySearchSparePartName" clearable placeholder="请输入备件名称" style="width: 100%" @select="handleAutocompleteSparePartNameSelect" />
              </el-form-item>
              <el-form-item label="备件规格" prop="sparePartSpecifications">
                <!-- <el-input maxlength="100" v-model="form.sparePartSpecifications" placeholder="请输入备件规格" /> -->
                <el-autocomplete maxlength="100" v-model="form.sparePartSpecifications" :fetch-suggestions="querySearchSparePartSpecifications" clearable placeholder="请输入备件规格" style="width: 100%" />
              </el-form-item>
              <el-form-item label="备件品牌" prop="sparePartBrand">
                <!-- <el-input maxlength="100" v-model="form.sparePartBrand" placeholder="请输入备件品牌" /> -->
                <el-autocomplete maxlength="100" v-model="form.sparePartBrand" :fetch-suggestions="querySearchSparePartBrand" clearable placeholder="请输入备件品牌" style="width: 100%" />
              </el-form-item>

              <!-- <el-form-item label="货物类型" prop="sparePartGoodsType">
                    <el-select v-model="form.sparePartGoodsType" placeholder="请选择货物类型" style="width:100%;display:block">
                        <el-option v-for="dict in com_spare_part_goods_type" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item> -->
              <el-form-item label="备件单价" prop="sparePartUnitPrice">
                <el-input-number v-model="form.sparePartUnitPrice" :precision="2" :min="0" :step="0.1" placeholder="请输入备件单价">
                  <template #append>￥</template>
                </el-input-number>
                <span class="margin-left">元</span>
              </el-form-item>
              <el-form-item label="库存总量" prop="sparePartQuantity">
                <el-input-number v-model="form.sparePartQuantity" :precision="0" :min="0" :step="1" placeholder="请输入库存总量" />
              </el-form-item>
              <!-- <el-form-item label="impa" prop="impa" style="width:100%">
                    <el-input maxlength="100" v-model="form.impa" placeholder="请输入impa" />
                </el-form-item> -->
              <el-form-item label="备件类型" prop="sparePartStockType">
                <el-select v-model="form.sparePartStockType" filterable placeholder="请选择库存类型" style="width: 100%; display: block">
                  <el-option v-for="dict in com_spare_part_stock_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="单位" prop="sparePartUnit">
                <!-- <el-input maxlength="100" v-model="form.sparePartUnit" placeholder="请输入单位" /> -->
                <el-autocomplete maxlength="100" v-model="form.sparePartUnit" :fetch-suggestions="querySearchSparePartUnit" clearable placeholder="请输入单位" style="width: 100%" />
              </el-form-item>
              <el-form-item label="存放位置" prop="sparePartStorageLocation" style="width: 100%">
                <!-- <el-input maxlength="300" v-model="form.sparePartStorageLocation" type="textarea"
                        placeholder="请输入存放位置" /> -->
                <el-autocomplete maxlength="300" type="textarea" v-model="form.sparePartStorageLocation" :fetch-suggestions="querySearchSparePartStorageLocation" clearable placeholder="请输入存放位置" style="width: 100%" />
              </el-form-item>
              <el-form-item label="备注" prop="remark" style="width: 100%">
                <!-- <el-input maxlength="300" v-model="form.remark" type="textarea" placeholder="请输入备注" /> -->
                <el-autocomplete maxlength="300" type="textarea" v-model="form.remark" :fetch-suggestions="querySearchRemark" clearable placeholder="请输入备注" style="width: 100%" />
              </el-form-item>

              <el-form-item label="文件路径" style="width: 100%">
                <image-upload v-model="form.filePath" :limit="1" />
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
        <el-col :xs="24" :span="8">
          <el-card shadow="hover" header="维保">
            <MaintenanceDescription :maintenance="maintenance" />
          </el-card>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <SparePartAccessDetailsDrawer ref="sparePartAccessDetailsDrawerInRef" sparePartAccessType="10" @submit="handleOpenSparePartAccessInSubmitDrawer" />
    <SparePartAccessDetailsDrawer ref="sparePartAccessDetailsDrawerOutRef" sparePartAccessType="20" @submit="handleOpenSparePartAccessOutSubmitDrawer" />
    <SparePartApplyDetailsDrawer ref="sparePartApplyDetailsDrawerRef" @submit="handleOpenSparePartApplySubmitDrawer" />

    <SparePartAccessSubmitDrawer ref="sparePartAccessSubmitDrawerInRef" sparePartAccessType="10" @close="handleCloseSparePartAccessDetailsInDrawer" @submit="getList" />
    <SparePartAccessSubmitDrawer ref="sparePartAccessSubmitDrawerOutRef" sparePartAccessType="20" @close="handleCloseSparePartAccessDetailsOutDrawer" @submit="getList" />
    <SparePartApplySubmitDrawer ref="sparePartApplySubmitDrawerRef" @close="handleCloseSparePartApplyDetailsDrawer" @submit="getList" />

    <el-backtop :right="10" :bottom="10" />

    <el-dialog title="管理员密码验证" v-model="openSparePartQuantityPasswordDialog" width="500px" append-to-body>
      <el-form ref="sparePartQuantityPasswordRef" :model="form" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="管理员密码" prop="password">
          <el-input maxlength="100" v-model="form.password" placeholder="请输入管理员密码" type="password" />
        </el-form-item>
      </el-form>
      <!-- <el-checkbox v-model="notCheckPasswordAgain" label="当前登录状态不再校验密码" /> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSparePartApplyQuantityPasswordForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="sparePart">
import { addSparePartAccessDetailsIn } from "@/utils/sparePartAccessDetailsIn";
import { addSparePartAccessDetailsOut } from "@/utils/sparePartAccessDetailsOut";
import { addSparePartApplyDetails } from "@/utils/sparePartApplyDetails";
import { overrideProperties } from "@/utils/ruoyi";
import { scrollTo } from "@/utils/scroll-to";
import MaintenanceDescription from "@/components/Maintenance/description";
import SparePartAccessDetailsCard from "@/components/SparePartAccessDetails/card";
import SparePartAccessDetailsDrawer from "@/components/SparePartAccessDetails/drawer";
import SparePartAccessSubmitDrawer from "@/components/SparePartAccess/submit/drawer";
import SparePartApplyDetailsCard from "@/components/SparePartApplyDetails/card";
import SparePartApplyDetailsDrawer from "@/components/SparePartApplyDetails/drawer";
import SparePartApplySubmitDrawer from "@/components/SparePartApply/submit/drawer";
import {
  listSparePart,
  getSparePart,
  delSparePart,
  addSparePart,
  updateSparePart,
  downloadSparePart,
  judgeSparePartEditPassword,
} from "@/api/sparePart/sparePart";
import { ref } from "vue";

const emit = defineEmits();

const props = defineProps({
  modelValue: [String, Number],
  maintenanceList: {
    type: Array,
    default: [],
  },
  maintenanceOptions: {
    type: Array,
    default: [],
  },
  showSparePartApplySubmitDrawer: {
    type: [Boolean, String],
    default: false,
  },
  showSidebar: {
    type: [Boolean],
    default: false,
  },
  sidebarSpan: {
    type: [Number],
    default: false,
  },
});

const {
  modelValue,
  maintenanceList,
  maintenanceOptions,
  showSparePartApplySubmitDrawer,
  showSidebar,
  sidebarSpan,
} = toRefs(props);

const { proxy } = getCurrentInstance();
const store = useStore();

const { com_spare_part_goods_type, com_spare_part_stock_type } = proxy.useDict(
  "com_spare_part_goods_type",
  "com_spare_part_stock_type"
);
const sparePartList = ref([]);
const sparePart = ref({});
const open = ref(false);
const openSparePartQuantityPasswordDialog = ref(false);

const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeCollapseName = ref(null);
const maintenance = ref({});
const isInputPasswordCorrectly = ref(false);
const notCheckPasswordAgain = ref(true);
// const showSidebar = ref(true);
// const sidebarSpan = ref(6);

const sparePartRetrievalQuantityOutTotal = computed(() => {
  let total = 0;
  Object.values(store.state.data.sparePartAccessDetailsOut).map((item) => {
    total += item.sparePartRetrievalQuantity;
  });
  return total;
});

const sparePartRetrievalQuantityInTotal = computed(() => {
  let total = 0;
  Object.values(store.state.data.sparePartAccessDetailsIn).map((item) => {
    total += item.sparePartRetrievalQuantity;
  });
  return total;
});

const sparePartApplyQuantityTotal = computed(() => {
  let total = 0;
  Object.values(store.state.data.sparePartApplyDetails).map((item) => {
    total += item.sparePartApplyQuantity;
  });
  return total;
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sparePartNumber: "",
    sparePartName: "",
    sparePartSpecifications: "",
    sparePartBrand: "",
    sparePartStorageLocation: "",
    sparePartStockType: "",
    sparePartGoodsType: "",
    sparePartQuantity: "",
    sparePartUnitPrice: "",
    impa: "",
    filePath: "",
  },
  rules: {
    maintenanceId: [
      {
        required: true,
        message: "维保不能为空",
        trigger: "blur",
      },
    ],
    sparePartNumber: [
      {
        required: true,
        message: "备件编号不能为空",
        trigger: "blur",
      },
    ],
    sparePartName: [
      {
        required: true,
        message: "备件名称不能为空",
        trigger: "blur",
      },
    ],
    sparePartSpecifications: [
      {
        required: true,
        message: "备件规格不能为空",
        trigger: "blur",
      },
    ],
    sparePartBrand: [
      {
        required: true,
        message: "备件品牌不能为空",
        trigger: "blur",
      },
    ],
    sparePartStockType: [
      {
        required: true,
        message: "库存类型不能为空",
        trigger: "change",
      },
    ],
    sparePartGoodsType: [
      {
        required: true,
        message: "货物类型不能为空",
        trigger: "change",
      },
    ],
    sparePartQuantity: [
      {
        required: true,
        message: "库存总量不能为空",
        trigger: "blur",
      },
    ],
    sparePartUnitPrice: [
      {
        required: true,
        message: "备件单价不能为空",
        trigger: "blur",
      },
    ],
    password: [
      {
        required: true,
        message: "密码不能为空",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);
const baseUrl = import.meta.env.VITE_APP_BASE_API;

watch(modelValue, (newValue) => {
  queryParams.value.maintenanceId = newValue;
  handleQuery();
});

/** 查询备件列表 */
function getList() {
  loading.value = true;
  listSparePart(queryParams.value).then((response) => {
    sparePartList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function addList() {
  loading.value = true;
  listSparePart(queryParams.value)
    .then((response) => {
      sparePartList.value.push(...response.rows);
      total.value = response.total;
      if (sparePartList.value.length >= total.value) finished.value = true;
      loading.value = false;
    })
    .catch((response) => {
      loading.value = false;
    });
}

// 下拉刷新
function handlePullDownRefresh() {
  queryParams.value.pageNum = 1;
  sparePartList.value = [];
  addList();
}

// 滚动到底部的事件
function handleReachBottom() {
  queryParams.value.pageNum++;
  addList();
}

// 取消按钮
function cancel() {
  open.value = false;
  openSparePartQuantityPasswordDialog.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    sparePartId: null,
    sparePartNumber: "",
    sparePartName: "",
    sparePartSpecifications: "",
    sparePartBrand: "",
    sparePartStorageLocation: "",
    sparePartStockType: "",
    sparePartGoodsType: "",
    sparePartQuantity: "",
    createBy: "",
    createTime: "",
    updateBy: "",
    updateTime: "",
    remark: "",
    sparePartUnitPrice: "",
    impa: "",
    filePath: "",
  };
  proxy.resetForm("sparePartRef");
  proxy.resetForm("sparePartQuantityPasswordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  emit("update:modelValue", queryParams.value.maintenanceId);
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.sparePartId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加备件";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  console.log(row);
  const sparePartId = row.sparePartId || ids.value;
  console.log(ids.value);
  if (!isInputPasswordCorrectly.value || !notCheckPasswordAgain.value) {
    sparePart.value = { sparePartId };
    openSparePartQuantityPasswordDialog.value = true;
    return;
  }
  // if (notCheckPasswordAgain.value) {
  //   isInputPasswordCorrectly.value = true;
  // }
  getSparePart(sparePartId).then((response) => {
    form.value = response.data;
    handleFormMaintenanceIdChange(response.data.maintenanceId);
    open.value = true;
    openSparePartQuantityPasswordDialog.value = false;
    title.value = "修改备件";
  });
}

function submitSparePartApplyQuantityPasswordForm() {
  proxy.$refs["sparePartQuantityPasswordRef"].validate((valid) => {
    if (valid) {
      judgeSparePartEditPassword(form.value.password)
        .then()
        .then((response) => {
          if (response) {
            // open.value = true;
            openSparePartQuantityPasswordDialog.value = false;
            isInputPasswordCorrectly.value = true;
            handleUpdate(sparePart.value);
          } else {
            proxy.$modal.msgError("密码错误");
          }
        });
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["sparePartRef"].validate((valid) => {
    if (valid) {
      if (form.value.sparePartId != null) {
        updateSparePart(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          sparePart.value = {};
          getList();
        });
      } else {
        addSparePart(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const sparePartIds = row.sparePartId || ids.value;
  const sparePartListFilter = Array.isArray(sparePartIds)
    ? sparePartList.value.filter((item) =>
        sparePartIds.includes(item.sparePartId)
      )
    : sparePartList.value.filter((item) =>
        [row.sparePartId].includes(item.sparePartId)
      );
  //// console.log(sparePartIds);
  const sparePartNumbers = sparePartListFilter.map(
    (item) => item.sparePartNumber
  );

  proxy.$modal
    .confirm('是否确认删除备件编号为"' + sparePartNumbers + '"的数据项？')
    .then(function () {
      return delSparePart(sparePartIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  downloadSparePart(queryParams.value);
  // proxy.download('sparePart/sparePart/export', {
  //   ...queryParams.value
  // }, `sparePart_${new Date().getTime()}.xlsx`)
}

/** 详细按钮操作 */
function handleView(row) {}

function handleOpenSparePartAccessOutSubmitDrawer() {
  proxy.$refs["sparePartAccessSubmitDrawerOutRef"].show();
}

function handleOpenSparePartAccessInSubmitDrawer() {
  proxy.$refs["sparePartAccessSubmitDrawerInRef"].show();
}

function handleOpenSparePartAccessDetailsOutDrawer() {
  proxy.$refs["sparePartAccessDetailsDrawerOutRef"].show();
}

function handleCloseSparePartAccessDetailsOutDrawer() {
  proxy.$refs["sparePartAccessDetailsDrawerOutRef"].handleClose();
}

function handleOpenSparePartAccessDetailsInDrawer() {
  proxy.$refs["sparePartAccessDetailsDrawerInRef"].show();
}

function handleCloseSparePartAccessDetailsInDrawer() {
  proxy.$refs["sparePartAccessDetailsDrawerInRef"].handleClose();
}

function handleOpenSparePartApplySubmitDrawer() {
  proxy.$refs["sparePartApplySubmitDrawerRef"].show();
}

function handleOpenSparePartApplyDetailsDrawer() {
  proxy.$refs["sparePartApplyDetailsDrawerRef"].show();
}

function handleCloseSparePartApplyDetailsDrawer() {
  proxy.$refs["sparePartApplyDetailsDrawerRef"].handleClose();
}

function handleAddSparePartAccessDetailsIn() {
  const sparePartListFilter =
    sparePartList.value.filter((item) =>
      ids.value.includes(item.sparePartId)
    ) || [];
  sparePartListFilter.map((item, index) => {
    item.materialWarehouseImpa = item.impa;
    addSparePartAccessDetailsIn(item, index == 1);
  });
  activeCollapseName.value = "10";
}

function handleAddSparePartAccessDetailsOut() {
  const sparePartListFilter =
    sparePartList.value.filter((item) =>
      ids.value.includes(item.sparePartId)
    ) || [];
  sparePartListFilter.map((item, index) => {
    item.materialWarehouseImpa = item.impa;
    addSparePartAccessDetailsOut(item, index == 1);
  });
  activeCollapseName.value = "20";
}

function handleAddSparePartApply() {
  const sparePartListFilter =
    sparePartList.value.filter((item) =>
      ids.value.includes(item.sparePartId)
    ) || [];
  sparePartListFilter.map((item, index) => {
    // item.materialWarehouseImpa = item.impa;
    addSparePartApplyDetails(item, index == 1);
  });
  activeCollapseName.value = "_30";
}

function handleCollapseClick() {
  setTimeout(() => {
    nextTick(() => {
      scrollTo(1000, 100);
    });
  }, 300);
}

async function searchAutocompleteList(key, value) {
  let params = {
    pageNum: 1,
    pageSize: queryParams.value.pageSize,
  };
  params[key] = value;
  let result;
  await listSparePart(params).then((response) => {
    result = response.rows;
  });
  return Promise.resolve(result);
}

async function querySearchSparePartNumber(queryString, cb) {
  const responses = await searchAutocompleteList(
    `sparePartNumber`,
    queryString
  );
  const results = Array.from(
    new Set(responses.map((item) => item[`sparePartNumber`]))
  ).map((item) => {
    return {
      value: item,
    };
  });
  cb(results);
}

async function querySearchSparePartName(queryString, cb) {
  const responses = await searchAutocompleteList(`sparePartName`, queryString);
  const results = Array.from(
    new Set(responses.map((item) => item[`sparePartName`]))
  ).map((item) => {
    return {
      value: item,
    };
  });
  cb(results);
}

async function querySearchSparePartSpecifications(queryString, cb) {
  const responses = await searchAutocompleteList(
    `sparePartSpecifications`,
    queryString
  );
  const results = Array.from(
    new Set(responses.map((item) => item[`sparePartSpecifications`]))
  ).map((item) => {
    return {
      value: item,
    };
  });
  cb(results);
}

async function querySearchSparePartBrand(queryString, cb) {
  const responses = await searchAutocompleteList(`sparePartBrand`, queryString);
  const results = Array.from(
    new Set(responses.map((item) => item[`sparePartBrand`]))
  ).map((item) => {
    return {
      value: item,
    };
  });
  cb(results);
}

async function querySearchSparePartUnit(queryString, cb) {
  const responses = await searchAutocompleteList(`sparePartUnit`, queryString);
  const results = Array.from(
    new Set(responses.map((item) => item[`sparePartUnit`]))
  ).map((item) => {
    return {
      value: item,
    };
  });
  cb(results);
}

async function querySearchSparePartStorageLocation(queryString, cb) {
  const responses = await searchAutocompleteList(
    `sparePartStorageLocation`,
    queryString
  );
  const results = Array.from(
    new Set(responses.map((item) => item[`sparePartStorageLocation`]))
  ).map((item) => {
    return {
      value: item,
    };
  });
  cb(results);
}

async function querySearchRemark(queryString, cb) {
  const responses = await searchAutocompleteList(`remark`, queryString);
  const results = Array.from(
    new Set(responses.map((item) => item[`remark`]))
  ).map((item) => {
    return {
      value: item,
    };
  });
  cb(results);
}

function handleToggleShowSidebar() {
  // showSidebar.value = !showSidebar.value;
  emit("update:showSidebar", !showSidebar.value);
}

function handleSwitchSidebarSpan() {
  let newSidebarSpan = sidebarSpan.value < 12 ? sidebarSpan.value + 3 : 6;
  emit("update:sidebarSpan", newSidebarSpan);
}

const handleAutocompleteSparePartNumberSelect = (value) => {
  console.log(value);
  listSparePart({
    pageNum: 1,
    pageSize: queryParams.value.pageSize,
    sparePartNumber: value.value,
  }).then((response) => {
    if (response.rows.length > 0) {
      overrideProperties(form.value, response.rows[0]);
      form.value.sparePartId = null;
    }
  });
};

const handleAutocompleteSparePartNameSelect = (value) => {
  console.log(value);
  listSparePart({
    pageNum: 1,
    pageSize: queryParams.value.pageSize,
    sparePartName: value.value,
  }).then((response) => {
    if (response.rows.length > 0) {
      overrideProperties(form.value, response.rows[0]);
      form.value.sparePartId = null;
    }
  });
};

const handleFormMaintenanceIdChange = (maintenanceId) => {
  let _maintenanceList = maintenanceList.value.filter(
    (item) => item.maintenanceId == maintenanceId
  );
  maintenance.value = _maintenanceList[0];
};

function initialData() {
  // console.log(showSparePartApplySubmitDrawer.value)
  if (
    showSparePartApplySubmitDrawer.value == true ||
    showSparePartApplySubmitDrawer.value == "true"
  ) {
    handleOpenSparePartApplyDetailsDrawer();
  }
  getList();
}

onActivated(() => {
  //// console.log("onActivated")
  initialData();
});
onMounted(() => {
  //// console.log("onMounted")
  initialData();
});

// initialData();
</script>

<style scoped>
.el-col {
  margin-bottom: 10px;
}
</style>
