<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <!-- 搜索项 -->
      <el-form-item label="库位编号" prop="pcode">
        <el-input v-model="queryParams.pcode" placeholder="请输入库位编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="所属场景" prop="scene">
        <el-select v-model="queryParams.scene" placeholder="请选择所属场景" style="width: 200px" clearable filterable>
          <el-option
              v-for="item in sceneOptions"
              :key="item.id"
              :label="item.sceneName"
              :value="item.sceneCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属大库" prop="parentWarehouseCode">
        <!-- <el-input v-model="queryParams.warehouseName" placeholder="请输入所属仓库" clearable @keyup.enter="handleQuery" /> -->
        <el-select v-model="queryParams.parentWarehouseCode" placeholder="请选择所属大库" style="width: 200px" clearable filterable @change="selectBigWarehouse" @clear="clearFun">
          <el-option
              v-for="item in warehouseOptions"
              :key="item.warehouseCode"
              :label="item.warehouseName"
              :value="item.warehouseCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属小库" prop="warehouseCode">
        <el-select v-model="queryParams.warehouseCode" placeholder="请选择所属小库" style="width: 200px" clearable filterable>
          <el-option
              v-for="item in warehouseList"
              :key="item.warehouseCode"
              :label="item.warehouseName"
              :value="item.warehouseCode"
          />
        </el-select>
        <!-- <el-input v-model="queryParams.warehouseName" placeholder="请输入所属仓库" clearable @keyup.enter="handleQuery" /> -->
      </el-form-item>
      <!-- <el-form-item label="编码后ID" prop="encodedId">
        <el-input v-model="queryParams.encodedId" placeholder="请输入编码后ID" 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">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['information:pcdedetail:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['information:pcdedetail:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['information:pcdedetail:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- v-hasPermi="['information:pcdedetail:import']" -->
        <el-button type="primary" plain icon="Upload" @click="handleImport" >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['information:pcdedetail:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="pcdedetailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键ID" align="center" prop="id" />-->
      <el-table-column label="库位编号" align="center" prop="pcode" />
<!--      <el-table-column label="所属场景" align="center" prop="scene" />-->
      <el-table-column label="所属场景" align="center" prop="sceneName" />
      <el-table-column label="所属大库" align="center" prop="parentWarehouseName" />
      <el-table-column label="所属小库" align="center" prop="warehouseName" />
      <el-table-column label="编码后ID" align="center" width="200" prop="encodedId" />
      <el-table-column label="标签" align="center" prop="tag" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="修改时间" align="center" prop="updatedAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['information:pcdedetail:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['information:pcdedetail:remove']">删除</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" />

    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="pcdedetailRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="库位编号" prop="pcode">
          <el-input v-model="form.pcode" placeholder="请输入库位编号" />
        </el-form-item>
        <el-form-item label="所属仓库" prop="warehouse">
          <!-- <el-select v-model="form.warehouse" placeholder="请选择所属仓库" clearable filterable style="width: 100%">
            <el-option
              v-for="item in warehouseOptions"
              :key="item.id"
              :label="item.warehouseName"
              :value="item.warehouseCode"
            />
          </el-select> -->
          <el-cascader :options="warehouseOptions" style="width: 100%;" @change="warehouseChange" v-model="form.warehouse" :props="{children: 'children', label: 'warehouseName', value: 'warehouseCode'}" />
        </el-form-item>
        <el-form-item label="所属场景" prop="scene">
          <el-select v-model="form.scene" placeholder="请选择所属场景" clearable filterable @change="handleQuery">
            <el-option
                v-for="item in sceneOptions"
                :key="item.id"
                :label="item.sceneName"
                :value="item.sceneCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-input v-model="form.tag" placeholder="请输入标签" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Pcdedetail">
import {
  listPcdedetail,
  getPcdedetail,
  delPcdedetail,
  addPcdedetail,
  updatePcdedetail,
  getAllScenes
} from "@/api/information/pcdedetail";
import { warehouseDict, warehouseAll,listWarehouseinfo } from "@/api/information/warehouseinfo";
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();

const pcdedetailList = ref([]);
const open = 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 sceneOptions = ref([]);
const warehouseOptions = ref([]);
const warehouseList = ref([]);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    pcode: null,
    scene: null,
    warehouseName: null,
    encodedId: null,
    tag: null,
    remark: null,
    isDelete: null,
    createdBy: null,
    createdAt: null,
    updatedBy: null,
    updatedAt: null,
    warehouseCode: null,   //小库
    parentWarehouseCode: null //大仓
  },
  rules: {
    pcode: [{ required: true, message: "库位编号不能为空", trigger: "blur" }],
    scene: [{ required: true, message: "所属场景不能为空", trigger: "blur" }],
    warehouse: [{ required: true, message: "所属仓库不能为空", trigger: "blur" }],
  }
});

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

const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { Authorization: "Bearer " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/information/pcdedetail/importData"
});

function handleImport() {
  upload.title = "库位明细导入";
  upload.open = true;
}

function handleFileUploadProgress(event, file, fileList) {
  upload.isUploading = true;
}

function handleFileSuccess(response, file, fileList) {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(`<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>${response.msg}</div>`, "导入结果", { dangerouslyUseHTMLString: true });
  getList();
}

function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

//级联选择器改变事件
function warehouseChange(val) {
  warehouseOptions.value.forEach(item => {
    if (item.warehouseCode === val[0]) {
      form.value.parentWarehouseName = item.warehouseName;
    }
    item.children.forEach(child => {
      if (child.warehouseCode === val[1]) {
        form.value.warehouseName = child.warehouseName;
      }
    });
  });
}
function selectBigWarehouse(val){
  warehouseOptions.value.filter(item => {
    if (item.warehouseCode === val) {
      warehouseList.value = item.children;
      
    }
  });

}
function clearFun(){
  warehouseList.value = [];
  queryParams.parentWarehouseCode = null
  queryParams.value.warehouseCode = null
  // queryParams.value.warehouseName = null
  
}



function getList() {
  loading.value = true;
  //获取列表数据
  listPcdedetail(queryParams.value).then(response => {
    pcdedetailList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  //获取所属场景下拉数据
  getAllScenes().then(res => {
    sceneOptions.value = res.data || [];
  });
  //获取所属仓库下拉数据
  warehouseAll().then(res => {
    warehouseOptions.value = res.data || [];
  });
  // listWarehouseinfo({pageNum:1,pageSize:20}).then(res => {
  //   warehouseList.value = res.rows || [];
  // })
}

function cancel() {
  open.value = false;
  reset();
}

function reset() {
  form.value = {
    id: null,
    pcode: null,
    scene: null,
    warehouse: [],
    encodedId: null,
    tag: null,
    remark: null,
    isDelete: null,
    createdBy: null,
    createdAt: null,
    updatedBy: null,
    updatedAt: null
  };
  proxy.resetForm("pcdedetailRef");
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加库位明细";
}

function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getPcdedetail(_id).then(response => {
    form.value = response.data;
    form.value.warehouse = [form.value.parentWarehouseCode, form.value.warehouseCode]
    open.value = true;
    title.value = "修改库位明细";
  });
}

function submitForm() {
  proxy.$refs["pcdedetailRef"].validate(valid => {
    if (valid) {
      let obj = JSON.parse(JSON.stringify(form.value));
      obj.parentWarehouseCode = obj.warehouse[0]
      obj.warehouseCode = obj.warehouse[1]
      if (form.value.id != null) {
        updatePcdedetail(obj).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPcdedetail(obj).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm(`是否确认删除库位明细编号为"${_ids}"的数据项？`).then(() => delPcdedetail(_ids)).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

function handleExport() {
  proxy.download("information/pcdedetail/export", { ...queryParams.value }, `pcdedetail_${new Date().getTime()}.xlsx`);
}

getList();

</script>
