<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="库房名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入库房名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="库房编号" prop="sn">
              <el-input v-model="queryParams.sn" placeholder="请输入库房编号" 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-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"> 新增 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" :data="tableList" >
        <el-table-column label="库房名称" align="center" show-overflow-tooltip prop="name" width="150" />
        <el-table-column label="库房编号" align="center" show-overflow-tooltip prop="sn" width="150" />
        <el-table-column label="管理人员" align="center" prop="managerName" width="150" />
        <el-table-column label="负责人" align="center" prop="headerName" width="150" />
        <el-table-column label="库房地址" align="center" show-overflow-tooltip prop="address" width="150" />
        <el-table-column label="库位总数" align="center" show-overflow-tooltip prop="shelfs.total" />
        <el-table-column label="备注" align="center" show-overflow-tooltip prop="remark" width="150" />
        <el-table-column label="创建人" align="center" show-overflow-tooltip prop="createName" width="150" />
        <el-table-column label="创建时间" align="center" show-overflow-tooltip prop="createTime" width="150" />
        <el-table-column label="操作" align="center" width="100" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button size="small" link type="primary" @click="showDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="900px" append-to-body>
      <el-form ref="addFormRef" :model="form" label-width="110px">
        <SubTitle title="基本信息" />
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库房名称" prop="name" :rules="[{ required: true, message: '库房名称不能为空', trigger: 'blur' }]">
              <el-input v-model="form.name" placeholder="请输入库房名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库房编号" prop="sn" :rules="[{ required: true, message: '库房编号不能为空', trigger: 'blur' }]">
              <el-input v-model="form.sn" placeholder="请输入库房编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管理人员" prop="managerId"
              :rules="[{ required: true, message: '管理人员不能为空', trigger: 'change' }]">
              <el-select v-model="form.managerId" clearable placeholder="请选择管理人员">
                <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName"
                  :value="item.userId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库负责人" prop="headerId"
              :rules="[{ required: true, message: '仓库负责人不能为空', trigger: 'change' }]">
              <el-select v-model="form.headerId" clearable placeholder="请选择仓库负责人">
                <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName"
                  :value="item.userId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入仓库地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <SubTitle title="库位管理" />
        <el-table :data="form.tmpShelfs" max-height="300">
          <el-table-column label="库位前缀" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.suffix" placeholder="类似A、B、C..." />
            </template>
          </el-table-column>
          <el-table-column label="货架号" align="center">
            <template #default="scope">
              <div class="input-group">
                <el-input-number v-model="scope.row.shelfMinNum" :min="1" :max="1" controls-position="right" />
                <span>-</span>
                <el-input-number v-model="scope.row.shelfMaxNum" :min="1" controls-position="right" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="层数" align="center">
            <template #default="scope">
              <div class="input-group">
                <el-input-number v-model="scope.row.layerMinNum" :min="1" :max="1" controls-position="right" />
                <span>-</span>
                <el-input-number v-model="scope.row.layerMaxNum" :min="1" controls-position="right" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="货位数" align="center">
            <template #default="scope">
              <div class="input-group">
                <el-input-number v-model="scope.row.placeMinNum" :min="1" :max="1" controls-position="right" />
                <span>-</span>
                <el-input-number v-model="scope.row.placeMaxNum" :min="1" controls-position="right" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template #header>
              <div class="operateBtn">
                <span>操作</span>
                <el-icon @click="addShelfs">
                  <CirclePlus />
                </el-icon>
              </div>
            </template>
            <template #default="scope">
              <el-icon @click="delShelfs(scope.$index)">
                <Delete />
              </el-icon>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"> 确 定 </el-button>
          <el-button @click="cancel"> 取 消 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-drawer v-model="detailDrawer" title="库房详情" class="customDrawer" size="60%">
      <div>
        <el-tabs v-model="detailTab">
          <el-tab-pane label="基础信息" name="1">
            <div>
              <el-descriptions class="detail-descriptions" :column="2" border>
                <el-descriptions-item label-align="center" label="库房名称">{{ curRow.name }}</el-descriptions-item>
                <el-descriptions-item label-align="center" label="库房编号">{{ curRow.sn }}</el-descriptions-item>
                <el-descriptions-item label-align="center" label="管理人员">{{ curRow.managerName }}</el-descriptions-item>
                <el-descriptions-item label-align="center" label="负责人">{{ curRow.headerName }}</el-descriptions-item>
                <el-descriptions-item label-align="center" label="库房地址">{{ curRow.address }}</el-descriptions-item>
                <el-descriptions-item label-align="center" label="库位总数">{{ curRow.shelfs.total }}</el-descriptions-item>
                <el-descriptions-item label-align="center" label="备注">{{ curRow.remark }}</el-descriptions-item>
                <el-descriptions-item label-align="center" label="创建人">{{ curRow.createName }}</el-descriptions-item>
                <el-descriptions-item label-align="center" label="创建时间">{{ curRow.createTime }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-tab-pane>
          <el-tab-pane label="库位管理" name="2">
            <el-table :data="curRow.shelfs.shelfsData" >
              <el-table-column label="库位名称" align="center" prop="shelfName">
              </el-table-column>
              <el-table-column label="前缀" align="center" prop="suffix">
              </el-table-column>
              <el-table-column label="货架号" align="center" prop="shelfNum">
              </el-table-column>
              <el-table-column label="层号" align="center" prop="layerNum">
              </el-table-column>
              <el-table-column label="货位号" align="center" prop="placeNum">
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
  </div>
</template>

<script setup name="WarehouseManage" lang="ts">
import { listWarehouse,  addWarehouse} from '@/api/sparesManage/index';
import { deepClone } from '@/utils';
import { listUser } from '@/api/system/user/index'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const tableList = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const addFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initFormData = {
  id: undefined,
  name: undefined,
  sn: undefined,
  managerId: undefined,
  address: undefined,
  headerId: undefined,
  tmpShelfs: [{
    suffix: '',
    shelfMinNum: 1,
    shelfMaxNum: 1,
    layerMinNum: 1,
    layerMaxNum: 1,
    placeMinNum: 1,
    placeMaxNum: 1
  }],
  shelfs: undefined,
  remark: undefined,
  ext1: undefined,
  ext2: undefined
};
const formData = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    sn: undefined,
    params: {}
  }
});
const detailTab = ref('1')
const detailDrawer = ref(false)
const curRow = ref({} as any)
const { queryParams, form } = toRefs(formData);
const userOptions = ref([])
/** 查询列表 */
const getList = async () => {
  loading.value = true;
  const res = await listWarehouse(queryParams.value);
  tableList.value = res.rows.map((item) => ({
    ...item,
    shelfs: item.shelfs ? JSON.parse(item.shelfs) : null,
  }));
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...deepClone(initFormData) };
  addFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增库房库位';
};

/** 提交按钮 */
const submitForm = () => {
  addFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const { tmpShelfs } = form.value
      if (tmpShelfs.length === 0) proxy?.$modal.msgError('请添加库位');
      let validFlag = false
      let validMessage = ''
      const suffixObj = {}
      let shelfsJson = {
        total: 0,
        shelfsData: []
      }
      for (let i = 0; i < tmpShelfs.length; i++) {
        const shelf = tmpShelfs[i]
        if (shelf.suffix.trim() === '') {
          validFlag = true;
          validMessage = `请填写第${i + 1}行库位前缀`
          break
        }
        if (!suffixObj[shelf.suffix]) {
          suffixObj[shelf.suffix] = shelf.suffix
        } else {
          validFlag = true;
          validMessage = `库位前缀存在重复，请检查`
          break
        }
        if (shelf.shelfMinNum > shelf.shelfMaxNum) {
          validFlag = true;
          validMessage = `第${i + 1}行库位货架号最大值应大于最小值`
          break
        }
        if (shelf.layerMinNum > shelf.layerMaxNum) {
          validFlag = true;
          validMessage = `第${i + 1}行库位层数最大值应大于最小值`
          break
        }
        if (shelf.placeMinNum > shelf.placeMaxNum) {
          validFlag = true;
          validMessage = `第${i + 1}行库位货位数最大值应大于最小值`
          break
        }
        for (let j = 1; j <= shelf.shelfMaxNum; j++) {
          for (let k = 1; k <= shelf.layerMaxNum; k++) {
            for (let n = 1; n <= shelf.placeMaxNum; n++) {
              shelfsJson.shelfsData.push({
                shelfName: `${shelf.suffix}-${j}-${k}-${n}`,
                suffix: shelf.suffix,
                shelfNum: j,
                layerNum: k,
                placeNum: n,
              })
            }
          }
        }
      }
      if (validFlag) proxy?.$modal.msgError(validMessage)
      buttonLoading.value = true;
      shelfsJson.total = shelfsJson.shelfsData.length
      form.value.shelfs = JSON.stringify(shelfsJson)
      await addWarehouse(form.value).finally(() => (buttonLoading.value = false));
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};
const showDetail = (row) => {
  Object.assign(curRow.value, row)
  detailDrawer.value = true
  detailTab.value = '1'
}
const getUserList = () => {
  listUser({ status: '0', pageSize: 10000, pageNum: 1 }).then(({ code, rows }) => {
    if (code === 200) {
      userOptions.value = rows
    }
  })
}
const addShelfs = () => {
  form.value.tmpShelfs.push({
    suffix: '',
    shelfMinNum: 1,
    shelfMaxNum: 1,
    layerMinNum: 1,
    layerMaxNum: 1,
    placeMinNum: 1,
    placeMaxNum: 1
  })
}
const delShelfs = (index) => {
  form.value.tmpShelfs.splice(index, 1)
}
onMounted(() => {
  getList();
  getUserList()
});
</script>
<style lang="scss" scoped>
.operateBtn {
  display: flex;
  align-items: center;

  .el-icon {
    color: #409eff;
    margin-left: 5px;
    cursor: pointer;
  }
}

.input-group {
  display: flex;
  align-items: center;

  >span {
    margin: 0 5px;
  }
}
</style>
