<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--物料目录-->
      <el-col :span="6" :xs="24" v-show="showSidebar">
        <!-- <el-affix :offset="20" style="width:100%;"> -->
          <el-card shadow="never">
            <div class="head-container">
              <el-input maxlength="100" v-model="impaNotes" placeholder="请输入物料目录" clearable prefix-icon="Search" style="margin-bottom: 20px" />
            </div>
            <el-row :gutter="10" class="mb8" style="min-height:32px" v-hasPermi="['impa:impa:add']">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAddIMPA">新增
                </el-button>
              </el-col>
            </el-row>
            <div class="head-container" style="height:calc(100vh - 50px);max-height:calc(100vh - 200px)">
              <el-scrollbar class="solid radius">
                <el-tree class="impa-tree" :data="impaList" :props="{ label: 'label', children: 'children' }" :expand-on-click-node="false" :filter-node-method="filterNode" ref="impaTreeRef" default-expand-all @node-click="handleIMPAClick">
                  <template #default="{ node, data }">
                    <span class="impa-tree-node" :class="{ active: data.impaCode == queryParams.impaCode }">
                      <div class="left">
                        <el-tooltip :content="`${data.impaCode} - ${data.label} \n${data.remark}`" placement="bottom">
                          <div>
                            <div>{{ data.impaCode }} - {{ data.label }}</div>
                            <div class="text-sm" style="color:var(--el-text-color-secondary)">{{ data.remark }}</div>
                          </div>
                          <template #content>
                            <div>{{ data.impaCode }} - {{ data.label }}</div>
                            <div>{{ data.remark }}</div>
                          </template>
                        </el-tooltip>
                      </div>
                      <div class="action flex align-center">
                        <div class="flex align-center" v-hasPermi="['impa:impa:edit']">
                          <el-icon @click.stop="handleUpdateIMPA(data)">
                            <Edit color="var(--el-color-success)" />
                          </el-icon>
                        </div>
                        <div class="flex align-center" v-hasPermi="['impa:impa:remove']">
                          <el-icon @click.stop="handleRemoveIMPA(node, data)" color="var(--el-color-danger)" class="margin-left-xs">
                            <Delete />
                          </el-icon>
                        </div>
                      </div>
                    </span>
                  </template>
                </el-tree>
              </el-scrollbar>
            </div>
          </el-card>
        <!-- </el-affix> -->
      </el-col>
      <!--物料清单-->
      <el-col :span="showSidebar ? 18 : 24" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="IMPA" prop="impa">
            <el-input maxlength="100" v-model="queryParams.impa" placeholder="请输入IMPA" clearable style="width: 240px" @keyup.enter="handleQuery" @change="handleQuery" @input="handleQuery" />
          </el-form-item>

          <el-form-item label="描述" prop="warehouseName">
            <el-input maxlength="100" v-model="queryParams.warehouseName" placeholder="请输入描述" clearable style="width: 240px" @keyup.enter="handleQuery" @change="handleQuery" @input="handleQuery" />
          </el-form-item>

          <el-form-item label="物料目录" prop="impaCode">
            <el-select v-model="queryParams.impaCode" filterable placeholder="请选择物料目录" @change="handleQuery" clearable>
              <el-option v-for="item in impaList" :key="item.id" :label="item.impaNotes" :value="item.impaCode" style="height: 60px;" class="flex align-center">
                <div>
                  <div>{{ item.impaCode }} - {{ item.impaNotes }}</div>
                  <div class="text-xs" style="line-height:1rem;color:var(--el-text-color-secondary)">{{ item.remark }}
                  </div>
                </div>
              </el-option>
            </el-select>
          </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="['warehouse:warehouse:add']">
            <el-button type="primary" plain icon="Plus" @click="handleAddWarehouse">新增
            </el-button>
          </el-col>
          <el-col :span="1.5" v-hasPermi="['warehouse:warehouse:edit']">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdateWarehouse">修改
            </el-button>
          </el-col>
          <el-col :span="1.5" v-hasPermi="['warehouse:warehouse:remove']">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDeleteWarehouse">删除
            </el-button>
          </el-col>
          <el-col :span="1.5" v-hasPermi="['warehouse:warehouse:export']">
            <el-button type="warning" plain icon="Download" @click="handleExportWarehouse">导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain :icon="showSidebar ? 'DArrowLeft' : 'DArrowRight'" @click="showSidebar = !showSidebar">
              {{ showSidebar? "隐藏": "显示" }}侧边栏
            </el-button>
          </el-col>
          <el-col :span="1.5" v-hasPermi="['warehouse:warehouse:in', 'warehouseAccess:warehouseAccess:add']">
            <el-button type="warning" plain icon="DocumentAdd" :disabled="multiple" @click="handleAddWarehouseAccessDetailsIn">入库
            </el-button>
          </el-col>
          <el-col :span="1.5" v-hasPermi="['warehouse:warehouse:out', 'warehouseAccess:warehouseAccess:add']">
            <el-button type="warning" plain icon="DocumentRemove" :disabled="multiple" @click="handleAddWarehouseAccessDetailsOut">出库
            </el-button>
          </el-col>
          <el-col :span="1.5" v-hasPermi="['warehouse:warehouse:apply']">
            <el-button type="warning" plain icon="Sell" :disabled="multiple" @click="handleAddWarehouseApply">申领
            </el-button>
          </el-col>
          <el-col :span="1.5" v-hasPermi="['warehouse:warehouse:purchase']">
            <el-button type="warning" plain icon="SoldOut" :disabled="multiple" @click="handleAddApplyPurchase">申购
            </el-button>
          </el-col>
          <el-col :span="1.5" v-hasPermi="['warehouse:warehouse:in', 'warehouseAccess:warehouseAccess:add']">
            <el-badge :value="warehouseRetrievalQuantityInTotal" :hidden="warehouseRetrievalQuantityInTotal == 0">
              <el-button type="warning" plain icon="DocumentAdd" @click="handleOpenWarehouseAccessDetailsInDrawer">入库列表
              </el-button>
            </el-badge>
          </el-col>
          <el-col :span="1.5" v-hasPermi="['warehouse:warehouse:out', 'warehouseAccess:warehouseAccess:add']">
            <el-badge :value="warehouseQuantityOutTotal" :hidden="warehouseQuantityOutTotal == 0">
              <el-button type="warning" plain icon="DocumentRemove" @click="handleOpenWarehouseAccessDetailsOutDrawer">出库列表
              </el-button>
            </el-badge>
          </el-col>
          <el-col :span="1.5" v-hasPermi="['warehouse:warehouse:apply']">
            <el-badge :value="warehouseApplyDetailsTotal" :hidden="warehouseApplyDetailsTotal == 0">
              <el-button type="warning" plain icon="Sell" @click="handleOpenWarehouseApplyDetailsDrawer">
                申领列表
              </el-button>
            </el-badge>
          </el-col>

          <el-col :span="1.5" v-hasPermi="['warehouse:warehouse:purchase']">
            <el-badge :value="applyPurchaseNumTotal" :hidden="applyPurchaseNumTotal == 0">
              <el-button type="warning" plain icon="SoldOut" @click="showApplyPurchaseDetailsDrawer">申购列表
              </el-button>
            </el-badge>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-card shadow="never">
          <el-table v-loading="loadingWarehouse" :data="warehouseList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="40" align="center" v-hasPermi="['warehouse:warehouse:edit', 'warehouse:warehouse:remove', 'warehouse:warehouse:in', 'warehouse:warehouse:out', 'warehouse:warehouse:apply', 'warehouse:warehouse:purchase', 'warehouseAccess:warehouseAccess:add']" />
            <el-table-column type="expand" width="30">
              <template #default="scope">
                <div class="padding">
                  <el-descriptions :column="1">
                    <!-- 1 -->
                    <el-descriptions-item label="IMPA">
                      {{ scope.row.impa }}
                    </el-descriptions-item>
                    <el-descriptions-item label="文件路径">
                      <image-preview :src="scope.row.filePath" :width="50" :height="50" />
                    </el-descriptions-item>
                    <el-descriptions-item label="物料目录">
                      <TextTag :options="impaList" column="impaCode" label="impaNotes" :value="scope.row.impaCode" style="display:inline-block" />
                    </el-descriptions-item>
                    <el-descriptions-item label="描述">
                      {{ scope.row.warehouseName }}
                    </el-descriptions-item>
                    <el-descriptions-item label="单位">
                      {{ scope.row.unit }}
                    </el-descriptions-item>
                    <el-descriptions-item label="规格" :span="3">
                      {{ scope.row.warehouseSpecifications }}
                    </el-descriptions-item>
                    <el-descriptions-item label="备注" :span="3">
                      {{ scope.row.remark }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="序号" align="center" type="index" width="50" />
            <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="impaCode" :show-overflow-tooltip="true">
              <template #default="scope">
                <TextTag :options="impaList" column="impaCode" label="impaNotes" :value="scope.row.impaCode" />
              </template>
            </el-table-column>
            <el-table-column label="描述" align="center" prop="warehouseName" :show-overflow-tooltip="true" />
            <el-table-column label="规格" align="center" prop="warehouseSpecifications" :show-overflow-tooltip="true" />
            <el-table-column label="库存" align="center" prop="warehouseQuantity" />
            <el-table-column label="单位" align="center" prop="unit" />
            <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160" fixed="right" v-hasPermi="['warehouse:warehouse:edit', 'warehouse:warehouse:remove', 'warehouse:warehouse:purchase']">
              <template #default="scope">
                <!-- <el-button
                link
                icon="View"
                @click="handleView(scope.row)"
                v-hasPermi="['warehouse:warehouse:query']"
                >详细
              </el-button> -->
                <el-button link type="success" icon="Edit" @click="handleUpdateWarehouse(scope.row)" v-hasPermi="['warehouse:warehouse:edit']">修改
                </el-button>
                <el-button link type="danger" icon="Delete" @click="handleDeleteWarehouse(scope.row)" v-hasPermi="['warehouse:warehouse:remove']">删除
                </el-button>
                <el-button link type="warning" icon="DocumentAdd" @click="addWarehouseAccessDetailsIn(scope.row); activeCollapseName = '10'" v-hasPermi="['warehouse:warehouse:in', 'warehouseAccess:warehouseAccess:add']">入库
                </el-button>
                <el-button link type="warning" icon="DocumentRemove" @click="addWarehouseAccessDetailsOut(scope.row); activeCollapseName = '20'" v-hasPermi="['warehouse:warehouse:out', 'warehouseAccess:warehouseAccess:add']">出库
                </el-button>
                <el-button link type="warning" icon="Sell" @click="addWarehouseApplyDetails(scope.row); activeCollapseName = '_30'" v-hasPermi="['warehouse:warehouse:apply']">申领
                </el-button>
                <el-button link type="warning" icon="SoldOut" @click="addApplyPurchaseDetails(scope.row)" v-hasPermi="['warehouse:warehouse:purchase']">申购
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

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

        <!-- <ApplyPurchaseDetailsCard class="margin-tb" @submit="showApplyPurchaseDrawerSubmit"
          v-show="warehouseList.length > 0" v-hasPermi="['warehouse:warehouse:purchase']" /> -->
      </el-col>
    </el-row>

    <!-- 添加或修改物料管理-物料目录对话框 -->
    <el-dialog :title="title" v-model="openIMPACatalog" width="500px" append-to-body>
      <el-form ref="impaRef" :model="impaForm" :rules="rules" label-width="80px">
        <el-form-item label="编号" prop="impaCode">
          <el-input maxlength="100" v-model="impaForm.impaCode" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="描述" prop="impaNotes">
          <el-input maxlength="100" v-model="impaForm.impaNotes" placeholder="请输入描述" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input maxlength="100" v-model="impaForm.remark" placeholder="请输入备注" type="textarea" :rows="6" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitIMPAForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改物料管理-物料清单对话框 -->
    <el-dialog :title="title" v-model="openWarehouseDialog" width="1000px" append-to-body>
      <el-form ref="warehouseRef" :model="warehouseForm" :rules="rules" label-width="80px" class="grid col-2">
        <el-form-item label="impa" prop="impa" style="width:100%">
          <!-- <el-input maxlength="100" v-model="warehouseForm.impa" placeholder="请输入impa" /> -->
          <el-autocomplete maxlength="100" v-model="warehouseForm.impa" :fetch-suggestions="querySearchImpa" clearable placeholder="请输入impa" style="width:100%" @select="handleAutocompleteImpaSelect" />
        </el-form-item>
        <el-form-item label="编号" prop="impaCode">
          <el-select v-model="warehouseForm.impaCode" filterable placeholder="请选择物料类型编号" style="width:100%;display:block">
            <el-option v-for="item in impaList" :key="item.id" :label="item.impaNotes" :value="item.impaCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <!-- <el-input maxlength="100" v-model="warehouseForm.unit" auto-complete="on" name="unit" placeholder="请输入单位" /> -->
          <el-autocomplete maxlength="100" v-model="warehouseForm.unit" :fetch-suggestions="querySearchUnit" clearable placeholder="请输入单位" style="width:100%" />
        </el-form-item>

        <el-form-item label="库存" prop="warehouseQuantity" style="width:100%" v-if="warehouseForm.warehouseId == null">
          <el-input v-model="warehouseForm.warehouseQuantity" type="number" name="warehouseQuantity" :min="0" placeholder="请输入库存数量" />
        </el-form-item>

        <el-form-item label="描述" prop="warehouseName" style="width:100%">
          <!-- <el-input maxlength="300" v-model="warehouseForm.warehouseName" placeholder="请输入描述" type="textarea" :rows="4" /> -->
          <el-autocomplete maxlength="300" type="textarea" :rows="2" v-model="warehouseForm.warehouseName" :fetch-suggestions="querySearchDescription" clearable placeholder="请输入描述" style="width:100%" />
        </el-form-item>
        <el-form-item label="规格" prop="warehouseSpecifications" style="width:100%">
          <!-- <el-input maxlength="300" v-model="warehouseForm.warehouseSpecifications" placeholder="请输入规格" type="textarea"
            :rows="4" /> -->
          <el-autocomplete maxlength="300" type="textarea" :rows="5" v-model="warehouseForm.warehouseSpecifications" :fetch-suggestions="querySearchSpecifications" clearable placeholder="请输入规格" style="width:100%" />
        </el-form-item>
        <el-form-item label="备注" prop="remark" style="width:100%">
          <!-- <el-input maxlength="300" v-model="warehouseForm.remark" placeholder="请输入备注" type="textarea" :rows="6" /> -->
          <el-autocomplete maxlength="300" type="textarea" :rows="5" v-model="warehouseForm.remark" :fetch-suggestions="querySearchRemark" clearable placeholder="请输入备注" style="width:100%" />
        </el-form-item>
        <el-form-item label="文件路径">
          <image-upload v-model="warehouseForm.filePath" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitWarehouseForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <WarehouseAccessDetailsDrawer ref="warehouseAccessDetailsDrawerInRef" warehouseAccessType="10" @submit="handleOpenWarehouseAccessInSubmitDrawer" />
    <WarehouseAccessDetailsDrawer ref="warehouseAccessDetailsDrawerOutRef" warehouseAccessType="20" @submit="handleOpenWarehouseAccessOutSubmitDrawer" />

    <WarehouseAccessSubmitDrawer ref="warehouseAccessSubmitDrawerInRef" warehouseAccessType="10" @close="handleCloseWarehouseAccessDetailsInDrawer" @submit="getList" />
    <WarehouseAccessSubmitDrawer ref="warehouseAccessSubmitDrawerOutRef" warehouseAccessType="20" @close="handleCloseWarehouseAccessDetailsOutDrawer" @submit="getList" />

    <WarehouseApplyDetailsDrawer ref="warehouseApplyDetailsDrawerRef" @submit="handleOpenWarehouseApplySubmitDrawer" />

    <WarehouseApplySubmitDrawer ref="warehouseApplySubmitDrawerRef" @close="handleColseWarehouseApplyDetailsDrawer" @submit="getList" />

    <ApplyPurchaseDetailsDrawer ref="applyPurchaseDetailsDrawerRef" @submit="showApplyPurchaseDrawerSubmit" />

    <ApplyPurchaseDrawerSubmit ref="applyPurchaseDetailsDrawerSubmitRef" @close="closeApplyPurchaseDetailsDrawer" />

    <el-backtop :right="10" :bottom="10" />
  </div>
</template>
<script name="IMPA" setup >
import { overrideProperties } from "@/utils/ruoyi";
import {
  listImpa,
  getImpa,
  delImpa,
  addImpa,
  updateImpa,
} from "@/api/impa/impa";

import {
  listWarehouse,
  getWarehouse,
  delWarehouse,
  addWarehouse,
  updateWarehouse,
  downloadWarehouse,
} from "@/api/warehouse/warehouse";

import { addApplyPurchaseDetails } from "@/utils/applyPurchaseDetails";

// import WarehouseAccessDetailsCard from "@/components/WarehouseAccessDetails/card";
import WarehouseAccessSubmitDrawer from "@/components/WarehouseAccess/submit/drawer";
import WarehouseAccessDetailsDrawer from "@/components/WarehouseAccessDetails/drawer";

import { addWarehouseAccessDetailsOut } from "@/utils/warehouseAccessDetailsOut";
import { addWarehouseAccessDetailsIn } from "@/utils/warehouseAccessDetailsIn";
import { addWarehouseApplyDetails } from "@/utils/warehouseApplyDetails";

import WarehouseApplyDetailsCard from "@/components/WarehouseApplyDetails/card";
import WarehouseApplyDetailsDrawer from "@/components/WarehouseApplyDetails/drawer";

import WarehouseApplySubmitDrawer from "@/components/WarehouseApply/submit/drawer";

import ApplyPurchaseDetailsDrawer from "@/components/ApplyPurchaseDetails/drawer";
import ApplyPurchaseDrawerSubmit from "@/components/ApplyPurchase/submit/drawer";
import ApplyPurchaseDetailsCard from "@/components/ApplyPurchaseDetails/card";

const route = useRoute();

const store = useStore();

//// console.log(route)
const { proxy } = getCurrentInstance();
// const { sys_normal_disable, sys_user_sex } = proxy.useDict(
//   "sys_normal_disable",
//   "sys_user_sex"
// );

const warehouseList = ref([]);
const open = ref(false);
const openIMPACatalog = ref(false);
const openWarehouseDialog = ref(false);
const showSidebar = ref(true);

const openSubscribeDrawer = ref(false);

// const loading = ref(true);
const loadingWarehouse = ref(true);

const showSearch = ref(true);
const warehouseIds = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const impaNotes = ref("");
const impaList = ref(undefined);
const activeCollapseName = ref(null);

const data = reactive({
  impaForm: {},
  warehouseForm: {
    warehouseQuantity: 0,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    impaCode: [
      {
        required: true,
        message: "编号不能为空",
        trigger: "blur",
      },
    ],
    impaNotes: [
      {
        required: true,
        message: "描述不能为空",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules, impaForm, warehouseForm } = toRefs(data);

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return (
    data.label.indexOf(value) !== -1 ||
    data.remark.toLowerCase().indexOf(value.toLowerCase()) !== -1
  );
};
/** 根据名称筛选部门树 */
watch(impaNotes, (val) => {
  proxy.$refs["impaTreeRef"].filter(val);
});

const warehouseRetrievalQuantityInTotal = computed(() => {
  let total = 0;
  console.log(store.state.data.warehouseAccessDetailsIn);
  Object.values(store.state.data.warehouseAccessDetailsIn).map((item) => {
    total += item.warehouseRetrievalQuantity;
  });
  return total;
});

const warehouseQuantityOutTotal = computed(() => {
  let total = 0;
  Object.values(store.state.data.warehouseAccessDetailsOut).map((item) => {
    total += item.warehouseRetrievalQuantity;
  });
  return total;
});

const warehouseApplyDetailsTotal = computed(() => {
  let total = 0;
  Object.values(store.state.data.warehouseApplyDetails).map((item) => {
    total += item.warehouseApplyQuantity;
  });
  return total;
});

const applyPurchaseNumTotal = computed(() => {
  let total = 0;
  Object.values(store.state.data.applyPurchaseDetails).map((item) => {
    total += item.applyPurchaseNum;
  });
  store.state.data.applyPurchaseDetailsCustomList.map((item) => {
    total += item.applyPurchaseNum;
  });
  return total;
});

/** 查询部门下拉树结构 */
function getTreeselect() {
  listImpa({ pageNum: 1, pageSize: 9999 }).then((response) => {
    response.rows.map((item) => {
      item.label = `${item.impaNotes}`;
    });
    // impaList.value = response.rows.filter((item) => item.status === "0");
    impaList.value = response.rows.sort(
      (a, b) => Number(a.impaCode) - Number(b.impaCode)
    );
  });
}

/** 查询物料管理-物料目录列表 */
function getList() {
  loadingWarehouse.value = true;
  listWarehouse(queryParams.value).then((response) => {
    warehouseList.value = response.rows;
    total.value = response.total;
    loadingWarehouse.value = false;
  });
}

/** 节点单击事件 */
function handleIMPAClick(data) {
  // proxy.$modal.msg(`${JSON.stringify(data)}`);
  queryParams.value.impaCode = data.impaCode;
  handleQuery();
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 重置操作表单 */
function reset() {
  impaForm.value = {};
  warehouseForm.value = {};
  proxy.resetForm("userRef");
}
/** 取消按钮 */
function cancel() {
  openIMPACatalog.value = false;
  openWarehouseDialog.value = false;
  reset();
}

/** 新增按钮操作 */
function handleAddIMPA() {
  reset();
  title.value = "新增物料管理-物料目录";
  openIMPACatalog.value = true;
}
/** 修改按钮操作 */
function handleUpdateIMPA(data) {
  impaForm.value = data;
  openIMPACatalog.value = true;
  title.value = "修改物料管理-物料目录";
}
/** 删除按钮操作 */
function handleRemoveIMPA(node, data) {
  //// console.log(node, data);
  proxy.$modal
    .confirm(`是否删除【${data.label}】？`)
    .then(() => {
      delImpa(data.id).then(() => {
        getTreeselect();
      });
    })
    .catch(() => {});
}
/** 提交按钮 */
function submitIMPAForm() {
  proxy.$refs["impaRef"].validate((valid) => {
    // console.log(valid);
    if (valid) {
      if (impaForm.value.id != undefined) {
        updateImpa(impaForm.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          openIMPACatalog.value = false;
          getTreeselect();
        });
      } else {
        addImpa(impaForm.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          openIMPACatalog.value = false;
          getTreeselect();
        });
      }
    }
  });
}

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

/** 新增按钮操作 */
function handleAddWarehouse() {
  reset();
  openWarehouseDialog.value = true;
  title.value = "添加物料管理-物料清单";
}
/** 删除按钮操作 */
function handleDeleteWarehouse(row) {
  // console.log(row)
  const deleteWarehouseIds = row.warehouseId || warehouseIds.value;
  console.log(deleteWarehouseIds);
  const warehouseListFilter = Array.isArray(deleteWarehouseIds)
    ? warehouseList.value.filter((item) =>
        deleteWarehouseIds.includes(item.warehouseId)
      )
    : warehouseList.value.filter((item) =>
        [row.warehouseId].includes(item.warehouseId)
      );
  // console.log(deleteWarehouseIds);
  const impas = warehouseListFilter.map((item) => item.impa);
  proxy.$modal
    .confirm(`是否确认删除物料管理-物料清单IMPA为【${impas}】的数据项？`)
    .then(function () {
      return delWarehouse(deleteWarehouseIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 修改按钮操作 */
function handleUpdateWarehouse(row) {
  reset();
  getTreeselect();
  const warehouseIds = row.warehouseId || warehouseIds.value;
  getWarehouse(warehouseIds).then((response) => {
    warehouseForm.value = response.data;
    openWarehouseDialog.value = true;
    title.value = "修改物料管理-物料清单";
  });
}
/** 提交按钮 */
function submitWarehouseForm() {
  proxy.$refs["warehouseRef"].validate((valid) => {
    if (valid) {
      if (warehouseForm.value.warehouseId != undefined) {
        updateWarehouse(warehouseForm.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          openWarehouseDialog.value = false;
          getList();
        });
      } else {
        addWarehouse(warehouseForm.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          openWarehouseDialog.value = false;
          getList();
        });
      }
    }
  });
}
/** 导出按钮操作 */
function handleExportWarehouse() {
  downloadWarehouse(queryParams.value);
}

function showApplyPurchaseDetailsDrawer() {
  proxy.$refs["applyPurchaseDetailsDrawerRef"].show();
}

function closeApplyPurchaseDetailsDrawer() {
  proxy.$refs["applyPurchaseDetailsDrawerRef"].handleClose();
}

function showApplyPurchaseDrawerSubmit() {
  function isEmpty(value) {
    // console.log(value)
    return value == null || (value + "").trim() == "";
  }
  for (let i in store.state.data.applyPurchaseDetailsCustomList) {
    let keys = [
      "materialWarehouseImpaCode",
      "materialWarehouseImpa",
      "materialWarehouseImpaDescription",
      "materialWarehouseImpaSpecifications",
      "applyPurchaseNum",
      "materialWarehouseImpaUnit",
    ];
    for (let j in keys) {
      // console.log(keys[j])
      // console.log(store.state.data.applyPurchaseDetailsCustomList[i])
      // console.log(store.state.data.applyPurchaseDetailsCustomList[i].value)

      if (
        isEmpty(store.state.data.applyPurchaseDetailsCustomList[i][keys[j]])
      ) {
        proxy.$modal.msgWarning("请补全自定义申购列表");
        return;
      }
    }
  }
  proxy.$refs["applyPurchaseDetailsDrawerSubmitRef"].show();
}

function handleAddWarehouseAccessDetailsIn() {
  const warehouseListFilter =
    warehouseList.value.filter((item) =>
      warehouseIds.value.includes(item.warehouseId)
    ) || [];
  warehouseListFilter.map((item, index) => {
    item.warehouseAccessType = "10";
    addWarehouseAccessDetailsIn(item, index == 1);
  });
  activeCollapseName.value = "10";
}

function handleAddWarehouseAccessDetailsOut() {
  const warehouseListFilter =
    warehouseList.value.filter((item) =>
      warehouseIds.value.includes(item.warehouseId)
    ) || [];
  warehouseListFilter.map((item, index) => {
    item.warehouseAccessType = "20";
    addWarehouseAccessDetailsOut(item, index == 1);
  });
  activeCollapseName.value = "20";
}

function handleAddWarehouseApply() {
  const warehouseListFilter =
    warehouseList.value.filter((item) =>
      warehouseIds.value.includes(item.warehouseId)
    ) || [];
  warehouseListFilter.map((item, index) => {
    addWarehouseApplyDetails(item, index == 1);
  });
  activeCollapseName.value = "_30";
}

function handleAddApplyPurchase() {
  const warehouseListFilter =
    warehouseList.value.filter((item) =>
      warehouseIds.value.includes(item.warehouseId)
    ) || [];
  warehouseListFilter.map((item, index) => {
    item.materialWarehouseImpa = item.impa;
    addApplyPurchaseDetails(item, index == 0);
  });
}

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

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

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

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

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

const querySearchRemark = async (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);
};

const handleAutocompleteImpaSelect = (value) => {
  console.log(value);
  listWarehouse({
    pageNum: 1,
    pageSize: queryParams.value.pageSize,
    impa: value.value,
  }).then((response) => {
    if (response.rows.length > 0) {
      overrideProperties(warehouseForm.value, response.rows[0]);
      warehouseForm.value.warehouseId = null;
    }
  });
};

function handleOpenWarehouseAccessOutSubmitDrawer() {
  proxy.$refs["warehouseAccessSubmitDrawerOutRef"].show();
}

function handleOpenWarehouseAccessInSubmitDrawer() {
  proxy.$refs["warehouseAccessSubmitDrawerInRef"].show();
}

function handleOpenWarehouseAccessDetailsInDrawer() {
  proxy.$refs["warehouseAccessDetailsDrawerInRef"].show();
}

function handleCloseWarehouseAccessDetailsInDrawer() {
  proxy.$refs["warehouseAccessDetailsDrawerInRef"].handleClose();
}

function handleOpenWarehouseAccessDetailsOutDrawer() {
  proxy.$refs["warehouseAccessDetailsDrawerOutRef"].show();
}

function handleCloseWarehouseAccessDetailsOutDrawer() {
  proxy.$refs["warehouseAccessDetailsDrawerOutRef"].handleClose();
}

function handleOpenWarehouseApplyDetailsDrawer() {
  proxy.$refs["warehouseApplyDetailsDrawerRef"].show();
}

function handleColseWarehouseApplyDetailsDrawer() {
  proxy.$refs["warehouseApplyDetailsDrawerRef"].handleClose();
}

function handleOpenWarehouseApplySubmitDrawer() {
  proxy.$refs["warehouseApplySubmitDrawerRef"].show();
}

function handleCloseWarehouseApplySubmitDrawer() {
  proxy.$refs["warehouseApplySubmitDrawerRef"].handleClose();
}

function initialData() {
  getTreeselect();
  getList();
  //// console.log(router)
  //// console.log(route.query)
  if (route.query.showApplyPurchaseDrawerSubmit == "true") {
    // // console.log(route.query)
    nextTick(() => {
      showApplyPurchaseDetailsDrawer();
    });
  }

  if (route.query.showWarehouseApplySubmitDrawer == "true") {
    // // console.log(route.query)
    nextTick(() => {
      handleOpenWarehouseApplyDetailsDrawer();
    });
  }
}

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

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

// initialData();
</script>


<style lang="scss">
// .el-affix{
// 	.el-affix--fixed{
// 		z-index: -1 !important;
// 	}
// }
.impa-tree {
  .el-tree-node__content {
    height: 46px;
  }

  .impa-tree-node {
    width: 90%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    // padding-right: 10px;
    .action {
      display: none;
      margin-right: 10px;
    }

    > .left {
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
      // margin-right:20px;
      // max-width: 50%;
    }

    &.active {
      background-color: var(--el-tree-node-hover-bg-color);
      font-weight: bold;
      color: var(--van-primary-color);
    }

    &:hover {
      .action {
        display: flex;
      }
    }
  }
}
</style>