<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="100px">
                        <el-form-item label="入库时间" prop="warehouseDate">
                            <el-input
                                    v-model="queryParams.warehouseDate"
                                    placeholder="请输入入库时间"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="采购方式" prop="purchaseMethod">
                            <el-input
                                    v-model="queryParams.purchaseMethod"
                                    placeholder="请输入采购方式"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="库存位置" prop="storageLocation">
                            <el-input
                                    v-model="queryParams.storageLocation"
                                    placeholder="请输入库存位置"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="物品名称" prop="itemName">
                            <el-input
                                    v-model="queryParams.itemName"
                                    placeholder="请输入物品名称"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="原厂编号" prop="originalPartNumber">
                            <el-input
                                    v-model="queryParams.originalPartNumber"
                                    placeholder="请输入原厂编号"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="型号" prop="model">
                            <el-input
                                    v-model="queryParams.model"
                                    placeholder="请输入型号"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="入库数量" prop="warehouseQuantity">
                            <el-input
                                    v-model="queryParams.warehouseQuantity"
                                    placeholder="请输入入库数量"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="剩余数量" prop="remainingQuantity">
                            <el-input
                                    v-model="queryParams.remainingQuantity"
                                    placeholder="请输入剩余数量"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['ems/info:sparePartsInventory:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ems/info:sparePartsInventory:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ems/info:sparePartsInventory:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['ems/info:sparePartsInventory:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['ems/info:sparePartsInventory:add']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5" v-if="lowStockCount > 0">
        <el-badge :value="lowStockCount" class="item" type="danger">
          <el-button type="danger" plain icon="el-icon-warning" size="mini" @click="filterLowStock">库存预警</el-button>
        </el-badge>
      </el-col>
      <right-toolbar v-model:show-search="showSearch" @query-table="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 库存预警提示 -->
    <el-alert
      v-if="lowStockCount > 0"
      :title="`库存预警：当前有 ${lowStockCount} 项备件库存不足，请及时补充！`"
      type="warning"
      :closable="false"
      show-icon
      style="margin-bottom: 15px"
    >
    </el-alert>

    <el-table v-loading="loading" :data="sparePartsInventoryList" @selection-change="handleSelectionChange" :row-class-name="getRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="60" v-if="columns[0].visible">
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="入库时间" align="center" prop="warehouseDate" v-if="columns[1].visible" />
      <el-table-column label="采购方式" align="center" prop="purchaseMethod" v-if="columns[2].visible" />
      <el-table-column label="库存位置" align="center" prop="storageLocation" v-if="columns[3].visible" />
      <el-table-column label="物品名称" align="center" prop="itemName" v-if="columns[4].visible" />
      <el-table-column label="原厂编号" align="center" prop="originalPartNumber" v-if="columns[5].visible" />
      <el-table-column label="型号" align="center" prop="model" v-if="columns[6].visible" />
      <el-table-column label="入库数量" align="center" prop="warehouseQuantity" v-if="columns[7].visible" />
      <el-table-column label="剩余数量" align="center" prop="remainingQuantity" v-if="columns[8].visible">
        <template #default="scope">
          <span :class="getRemainingQuantityClass(scope.row)">
            <i v-if="isLowStock(scope.row)" class="el-icon-warning" style="margin-right: 4px"></i>
            {{ scope.row.remainingQuantity }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="库存阈值" align="center" prop="threshold" v-if="columns[9].visible">
        <template #default="scope">
          <span>{{ scope.row.threshold }}</span>
          <el-tooltip v-if="isLowStock(scope.row)" effect="dark" content="库存不足！剩余数量已低于阈值" placement="top">
            <i class="el-icon-warning-outline" style="color: #e6a23c; margin-left: 4px"></i>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" v-if="columns[10].visible" />

      <!-- 动态盘点列 -->
      <el-table-column v-for="(checkColumn, index) in dynamicColumns" :key="'check_' + index" :label="checkColumn" align="center" width="120">
        <template #default="scope">
          <span>{{ getCheckValue(scope.row, checkColumn) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template #default="scope">
          <div v-if="isLowStock(scope.row)" style="margin-bottom: 5px">
            <el-tag size="mini" type="danger" effect="dark"> <i class="el-icon-warning"></i> 库存不足 </el-tag>
          </div>
          <div>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['ems/info:sparePartsInventory:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['ems/info:sparePartsInventory:remove']"
              >删除</el-button
            >
          </div>
        </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="800px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库时间" prop="warehouseDate">
              <el-date-picker v-model="form.warehouseDate" type="date" placeholder="请选择入库时间" value-format="yyyy-MM-dd" format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购方式" prop="purchaseMethod">
              <el-input v-model="form.purchaseMethod" placeholder="请输入采购方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="库存位置" prop="storageLocation">
              <el-input v-model="form.storageLocation" placeholder="请输入库存位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物品名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入物品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="原厂编号" prop="originalPartNumber">
              <el-input v-model="form.originalPartNumber" placeholder="请输入原厂编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库数量" prop="warehouseQuantity">
              <el-input v-model="form.warehouseQuantity" placeholder="请输入入库数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剩余数量" prop="remainingQuantity">
              <el-input v-model="form.remainingQuantity" placeholder="请输入剩余数量" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="库存阈值" prop="threshold">
              <el-input-number v-model="form.threshold" :min="0" placeholder="请输入库存阈值" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 占位列 -->
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <!-- 盘点记录部分 -->
        <el-divider content-position="left">盘点记录</el-divider>
        <div style="margin-bottom: 10px">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="addCheckRecord">添加 盘点记录</el-button>
        </div>
        <el-table :data="form.checkData" border style="width: 100%; margin-bottom: 20px" max-height="300">
          <el-table-column label="盘点名称" width="200">
            <template #default="scope">
              <el-input v-model="scope.row.checkName" placeholder="如: 2023.3盘点" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="盘点数量" width="150">
            <template #default="scope">
              <el-input-number v-model="scope.row.checkQuantity" :min="0" size="small" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeCheckRecord(scope.$index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </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 + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <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 lang="ts">
import { computed, getCurrentInstance, onMounted, reactive, ref, type ComponentInternalInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  addSparePartsInventoryWithDynamicColumns,
  delSparePartsInventory,
  getDynamicColumns,
  getSparePartsInventoryWithDynamicColumns,
  listSparePartsInventoryWithDynamicColumns,
  updateSparePartsInventoryWithDynamicColumns
} from '@/api/ems/info/sparePartsInventory';
import { getToken } from '@/utils/auth';
import type { EmsDynamicColumn, EmsId } from '@/api/ems/types';

defineOptions({
  name: 'SparePartsInventory'
});

interface CheckDataItem {
  checkName: string;
  checkQuantity: number;
}

interface SparePartsInventoryVO extends BaseEntity {
  objid?: EmsId;
  warehouseDate?: string | null;
  purchaseMethod?: string | null;
  storageLocation?: string | null;
  itemName?: string | null;
  originalPartNumber?: string | null;
  model?: string | null;
  warehouseQuantity?: number | string | null;
  remainingQuantity?: number | string | null;
  threshold?: number | string | null;
  remarks?: string | null;
  checkData?: Record<string, unknown> | null;
}

interface SparePartsInventoryQuery extends PageQuery {
  params?: Record<string, unknown>;
}

interface SparePartsInventoryForm extends BaseEntity {
  objid?: EmsId;
  warehouseDate?: string | null;
  purchaseMethod?: string | null;
  storageLocation?: string | null;
  itemName?: string | null;
  originalPartNumber?: string | null;
  model?: string | null;
  warehouseQuantity?: number | string | null;
  remainingQuantity?: number | string | null;
  threshold?: number | string | null;
  remarks?: string | null;
  checkData: CheckDataItem[];
}

type SparePartsInventorySubmitForm = Omit<SparePartsInventoryForm, 'checkData'> & {
  checkData: Record<string, number>;
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const queryFormRef = ref<ElFormInstance>();
const formRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();

const loading = ref(true);
const ids = ref<EmsId[]>([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const sparePartsInventoryList = ref<SparePartsInventoryVO[]>([]);
const dynamicColumns = ref<string[]>([]);
const title = ref('');
const open = ref(false);

const queryParams = ref<SparePartsInventoryQuery>({
  pageNum: 1,
  pageSize: 10,
  params: {}
});

const createFormData = (): SparePartsInventoryForm => ({
  objid: undefined,
  warehouseDate: null,
  purchaseMethod: null,
  storageLocation: null,
  itemName: null,
  originalPartNumber: null,
  model: null,
  warehouseQuantity: null,
  remainingQuantity: null,
  threshold: 0,
  remarks: null,
  checkData: []
});

const form = ref<SparePartsInventoryForm>(createFormData());

const upload = reactive<ImportOption>({
  open: false,
  title: '',
  isUploading: false,
  updateSupport: 1,
  url: '',
  headers: {}
});

const rules = reactive<ElFormRules>({
  objid: [{ required: true, message: '编号不能为空', trigger: 'blur' }]
});

const columns: FieldOption[] = [
  { key: 0, label: '序号', visible: true },
  { key: 1, label: '入库时间', visible: true },
  { key: 2, label: '采购方式', visible: true },
  { key: 3, label: '库存位置', visible: true },
  { key: 4, label: '物品名称', visible: true },
  { key: 5, label: '原厂编号', visible: true },
  { key: 6, label: '型号', visible: true },
  { key: 7, label: '入库数量', visible: true },
  { key: 8, label: '剩余数量', visible: true },
  { key: 9, label: '库存阈值', visible: true },
  { key: 10, label: '备注', visible: true }
];

const lowStockCount = computed(() => sparePartsInventoryList.value.filter((item) => isLowStock(item)).length);

/** 查询备件库记录主列表 */
const getList = async () => {
  loading.value = true;
  try {
    const response = await listSparePartsInventoryWithDynamicColumns(queryParams.value);
    sparePartsInventoryList.value = (response.rows ?? []) as SparePartsInventoryVO[];
    total.value = response.total ?? 0;
  } finally {
    loading.value = false;
  }
};

/** 获取动态列列表 */
const getDynamicColumnsList = async () => {
  const response = await getDynamicColumns();
  dynamicColumns.value = (response.data ?? []).map((item: EmsDynamicColumn) => item.checkName).filter((item): item is string => !!item);
};

/** 获取盘点值 */
const getCheckValue = (row: SparePartsInventoryVO, checkName: string) => {
  if (row.checkData && row.checkData[checkName] !== undefined && row.checkData[checkName] !== null) {
    return row.checkData[checkName] as string | number;
  }
  return '';
};

/** 添加盘点记录，保持原有动态盘点录入能力不变 */
const addCheckRecord = () => {
  form.value.checkData.push({
    checkName: '',
    checkQuantity: 0
  });
};

/** 删除盘点记录 */
const removeCheckRecord = (index: number) => {
  form.value.checkData.splice(index, 1);
};

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

// 表单重置
const reset = () => {
  form.value = createFormData();
  formRef.value?.resetFields();
};

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

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

// 多选框选中数据
const handleSelectionChange = (selection: SparePartsInventoryVO[]) => {
  ids.value = selection.map((item) => item.objid).filter((item): item is EmsId => item !== null && item !== undefined);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加  备件库记录主';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SparePartsInventoryVO) => {
  reset();
  const objid = row?.objid ?? ids.value[0];
  if (objid === undefined || objid === null) {
    return;
  }
  const response = await getSparePartsInventoryWithDynamicColumns(objid);
  const record = response.data as Partial<SparePartsInventoryForm> & {
    checkData?: Record<string, number | string>;
  };
  Object.assign(form.value, record);
  if (record.checkData && typeof record.checkData === 'object' && !Array.isArray(record.checkData)) {
    form.value.checkData = Object.entries(record.checkData).map(([checkName, checkQuantity]) => ({
      checkName,
      checkQuantity: Number(checkQuantity ?? 0)
    }));
  } else {
    form.value.checkData = [];
  }
  open.value = true;
  title.value = '修改  备件库记录主';
};

/** 提交按钮 */
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) {
      return;
    }

    // 提交前将数组盘点数据压回对象，避免后端接收形态和前端编辑形态不一致。
    const submitData: SparePartsInventorySubmitForm = {
      ...form.value,
      checkData: {}
    };
    submitData.checkData = form.value.checkData.reduce<Record<string, number>>((accumulator, item) => {
      if (item.checkName && item.checkName.trim() !== '') {
        accumulator[item.checkName] = item.checkQuantity || 0;
      }
      return accumulator;
    }, {});

    if (form.value.objid != null) {
      await updateSparePartsInventoryWithDynamicColumns(submitData);
      proxy?.$modal.msgSuccess('修改成功');
    } else {
      await addSparePartsInventoryWithDynamicColumns(submitData);
      proxy?.$modal.msgSuccess('新增成功');
    }
    open.value = false;
    await getList();
    await getDynamicColumnsList();
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: SparePartsInventoryVO) => {
  const objids = row?.objid ?? ids.value;
  await proxy?.$modal.confirm('是否确认删除备件库记录主编号为"' + objids + '"的数据项？');
  await delSparePartsInventory(objids);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'ems/info/sparePartsInventory/export',
    {
      ...queryParams.value
    },
    `sparePartsInventory_${new Date().getTime()}.xlsx`
  );
};

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '导入备件库记录';
  upload.open = true;
};

/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('ems/info/sparePartsInventory/importTemplate', {}, `备件库记录数据模板_${new Date().getTime()}.xlsx`);
};

// 文件上传中处理
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

// 文件上传成功处理
const handleFileSuccess = async (response: { msg?: string }, _file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.clearFiles();
  await ElMessageBox.alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + (response.msg ?? '') + '</div>',
    '导入结果',
    {
      dangerouslyUseHTMLString: true
    }
  );
  await getList();
  await getDynamicColumnsList();
};

// 提交上传文件
const submitFileForm = () => {
  uploadRef.value?.submit();
};

// 判断是否为低库存
const isLowStock = (row: SparePartsInventoryVO) => {
  return Number(row.remainingQuantity ?? 0) <= Number(row.threshold ?? 0);
};

// 获取整行样式类名
const getRowClassName = ({ row }: { row: SparePartsInventoryVO }) => {
  return isLowStock(row) ? 'low-stock-row' : '';
};

// 过滤显示低库存记录
const filterLowStock = () => {
  ElMessage.warning(`正在显示 ${lowStockCount.value} 项库存不足的记录`);
  // 这里先保留提示语义，避免在迁移阶段顺手改动查询行为。
};

// 获取剩余数量类
const getRemainingQuantityClass = (row: SparePartsInventoryVO) => {
  // 当剩余数量低于或等于阈值时显示为红色警告
  return isLowStock(row) ? 'remaining-quantity-warning' : 'remaining-quantity-normal';
};

onMounted(async () => {
  upload.url = import.meta.env.VITE_APP_BASE_API + '/ems/info/sparePartsInventory/importData';
  upload.headers = { Authorization: 'Bearer ' + getToken() };
  await Promise.all([getList(), getDynamicColumnsList()]);
});
</script>

<style scoped>
.remaining-quantity-warning {
  color: #e6a23c;
  font-weight: bold;
  background-color: #fdf6ec;
  padding: 2px 4px;
  border-radius: 3px;
}

.remaining-quantity-normal {
  color: #606266;
}

/* 低库存整行警告样式 */
.el-table >>> .low-stock-row {
  background-color: #fef0f0 !important;
  border-left: 4px solid #f56c6c;
}

.el-table >>> .low-stock-row:hover {
  background-color: #fde2e2 !important;
}

/* 低库存行中的文本增强显示 */
.el-table >>> .low-stock-row .cell {
  font-weight: 500;
}

/* 低库存警告动画效果 */
.el-table >>> .low-stock-row .remaining-quantity-warning {
  animation: pulse-warning 2s infinite;
}

@keyframes pulse-warning {
  0% {
    background-color: #fdf6ec;
  }
  50% {
    background-color: #f9e79f;
  }
  100% {
    background-color: #fdf6ec;
  }
}
</style>
