<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="登记日期">
        <el-date-picker
          v-model="daterange"
          style="width: 340px"
          value-format="yyyy/MM/dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        ></el-date-picker>
      </el-form-item>
      <!--                        <el-form-item label="日期" prop="date">-->
      <!--                            <el-input-->
      <!--                                    v-model="queryParams.date"-->
      <!--                                    placeholder="请输入日期"-->
      <!--                                    clearable-->
      <!--                                    @keyup.enter="handleQuery"-->
      <!--                            />-->
      <!--                        </el-form-item>-->
      <el-form-item label="备件名称" prop="sparePartsName">
        <el-input v-model="queryParams.sparePartsName" placeholder="请输入备件名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="备件型号" prop="sparePartModel">
        <el-input v-model="queryParams.sparePartModel" placeholder="请输入备件型号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="废存数量" prop="wasteQuantity">
                            <el-input
                                    v-model="queryParams.wasteQuantity"
                                    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="registrar">
        <el-input v-model="queryParams.registrar" placeholder="请输入登记人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="库管确认" prop="warehouseConfirmation">
        <el-input v-model="queryParams.warehouseConfirmation" placeholder="请输入库管确认" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="queryParams.remarks" 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:sparePartsRegistration: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:sparePartsRegistration: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:sparePartsRegistration:remove']"
          >删除</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:sparePartsRegistration:add']"
          >导入</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:sparePartsRegistration:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClearAll"
          v-hasPermi="['ems/info:sparePartsRegistration:remove']"
          >一键全部清空</el-button
        >
      </el-col>
      <right-toolbar v-model:show-search="showSearch" @query-table="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="sparePartsRegistrationList"
      @selection-change="handleSelectionChange"
      @row-contextmenu="handleRowContextMenu"
      class="context-menu-table"
    >
      <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="date" v-if="columns[1].visible"> </el-table-column>
      <el-table-column label="备件名称" align="center" prop="sparePartsName" v-if="columns[2].visible"> </el-table-column>
      <el-table-column label="备件型号" align="center" prop="sparePartModel" v-if="columns[8].visible" />
      <el-table-column label="废存数量" align="center" prop="wasteQuantity" v-if="columns[3].visible"> </el-table-column>
      <el-table-column label="存放位置" align="center" prop="storageLocation" v-if="columns[4].visible"> </el-table-column>
      <el-table-column label="登记人" align="center" prop="registrar" v-if="columns[5].visible"> </el-table-column>
      <el-table-column label="库管确认" align="center" prop="warehouseConfirmation" v-if="columns[6].visible"> </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" v-if="columns[7].visible"> </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleViewDetail(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-copy-document" @click="handleCopy(scope.row)">复制</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ems/info:sparePartsRegistration:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ems/info:sparePartsRegistration: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="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="日期" prop="date">
          <el-date-picker v-model="form.date" type="date" placeholder="请选择日期" value-format="yyyy/MM/dd" format="yyyy/MM/dd" />
        </el-form-item>
        <el-form-item label="备件名称" prop="sparePartsName">
          <el-input v-model="form.sparePartsName" placeholder="请输入备件名称" />
        </el-form-item>
        <el-form-item label="备件型号" prop="sparePartModel">
          <el-input v-model="form.sparePartModel" placeholder="请输入备件型号" />
        </el-form-item>
        <el-form-item label="废存数量" prop="wasteQuantity">
          <el-input-number v-model="form.wasteQuantity" placeholder="请输入废存数量" />
        </el-form-item>
        <el-form-item label="存放位置" prop="storageLocation">
          <el-input v-model="form.storageLocation" placeholder="请输入存放位置" />
        </el-form-item>
        <el-form-item label="登记人" prop="registrar">
          <el-input v-model="form.registrar" placeholder="请输入登记人" />
        </el-form-item>
        <el-form-item label="库管确认" prop="warehouseConfirmation">
          <el-input v-model="form.warehouseConfirmation" placeholder="请输入库管确认" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" 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 + '?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">
            <!--                    <div class="el-upload__tip" slot="tip">-->
            <!--                        <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据-->
            <!--                    </div>-->
            <span>仅允许导入xls、xlsx格式文件。</span>
            <!--                    <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>-->
          </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>

    <!-- 详情抽屉 -->
    <el-drawer title="备件登记详情" v-model="detailDrawer" direction="rtl" size="50%" :before-close="() => (detailDrawer = false)">
      <div style="padding: 20px">
        <el-descriptions :column="1" border>
          <el-descriptions-item>
            <template v-slot:label>
              <span style="font-weight: bold; width: 90px; display: inline-block">日期</span>
            </template>
            {{ currentRecord.date || '-' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template v-slot:label>
              <span style="font-weight: bold; width: 90px; display: inline-block">备件名称</span>
            </template>
            {{ currentRecord.sparePartsName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template v-slot:label>
              <span style="font-weight: bold; width: 90px; display: inline-block">备件型号</span>
            </template>
            {{ currentRecord.sparePartModel || '-' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template v-slot:label>
              <span style="font-weight: bold; width: 90px; display: inline-block">废存数量</span>
            </template>
            {{ currentRecord.wasteQuantity || '-' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template v-slot:label>
              <span style="font-weight: bold; width: 90px; display: inline-block">存放位置</span>
            </template>
            {{ currentRecord.storageLocation || '-' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template v-slot:label>
              <span style="font-weight: bold; width: 90px; display: inline-block">登记人</span>
            </template>
            {{ currentRecord.registrar || '-' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template v-slot:label>
              <span style="font-weight: bold; width: 90px; display: inline-block">库管确认</span>
            </template>
            {{ currentRecord.warehouseConfirmation || '-' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template v-slot:label>
              <span style="font-weight: bold; width: 90px; display: inline-block">备注</span>
            </template>
            <div style="max-height: 100px; overflow-y: auto">
              {{ currentRecord.remarks || '-' }}
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>

    <!-- 右击菜单 -->
    <div
      v-show="contextMenu.visible"
      :style="{
        position: 'fixed',
        top: contextMenu.top + 'px',
        left: contextMenu.left + 'px',
        zIndex: 9999
      }"
      class="context-menu"
      @click.stop
    >
      <div class="context-menu-item" @click="contextMenuViewDetail"><i class="el-icon-view"></i> 查看详情</div>
      <div class="context-menu-item" @click="contextMenuEdit" v-if="checkPermi(['ems/info:sparePartsRegistration:edit'])">
        <i class="el-icon-edit"></i> 修改
      </div>
      <div class="context-menu-item" @click="contextMenuDelete" v-if="checkPermi(['ems/info:sparePartsRegistration:remove'])">
        <i class="el-icon-delete"></i> 删除
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useEmsClearAll } from '@/composables/useEmsClearAll';
import {
  listSparePartsRegistration,
  getSparePartsRegistration,
  delSparePartsRegistration,
  addSparePartsRegistration,
  updateSparePartsRegistration
} from '@/api/ems/info/sparePartsRegistration';
import { getToken } from '@/utils/auth';
import { checkPermi } from '@/utils/permission';

defineOptions({
  name: 'SparePartsRegistration'
} as any);

const { proxy } = getCurrentInstance() as any;

const formRef = ref<any>();
const queryFormRef = ref<any>();
const uploadRef = ref<any>();

// 这里统一通过工厂函数重建表单，避免弹窗在新增/编辑切换时残留上一条业务数据。
const createFormData = () => ({
  objid: null,
  date: null,
  sparePartsName: null,
  wasteQuantity: null,
  storageLocation: null,
  registrar: null,
  warehouseConfirmation: null,
  remarks: null
});

// 这里保留原页面字段结构，优先保证 EMS 业务行为与接口入参不发生漂移。
const state = reactive({
  daterange: [],
  // 清空功能配置
  clearAllConfig: {
    moduleKey: 'sparePartsRegistration',
    entityName: '废旧备件登记',
    permission: 'ems/info:sparePartsRegistration:remove'
  },
  // 遮罩层
  loading: true,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 动力能源部行输科废旧备件登记表格数据
  sparePartsRegistrationList: [],
  // 弹出层标题
  title: '',
  // 是否显示弹出层
  open: false,
  // 复制的备件数据
  copiedData: null,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    date: null,
    sparePartsName: null,
    wasteQuantity: null,
    storageLocation: null,
    registrar: null,
    warehouseConfirmation: null,
    remarks: null,
    params: {}
  },
  // 表单参数
  form: createFormData(),
  // 表单校验
  rules: {
    date: [
      {
        required: true,
        message: '日期不能为空',
        trigger: 'blur'
      }
    ]
  },
  columns: [
    {
      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
    }
  ],
  // 数据导入参数
  upload: {
    // 是否显示弹出层（数据导入）
    open: false,
    // 弹出层标题（数据导入）
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: {
      Authorization: 'Bearer ' + getToken()
    },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/ems/info/sparePartsRegistration/importData'
  },
  // 详情抽屉
  detailDrawer: false,
  currentRecord: {},
  // 右击菜单
  contextMenu: {
    visible: false,
    top: 0,
    left: 0,
    row: null
  }
} as any);

const {
  clearAllConfig,
  columns,
  contextMenu,
  copiedData,
  currentRecord,
  daterange,
  detailDrawer,
  form,
  ids,
  loading,
  multiple,
  open,
  queryParams,
  rules,
  showSearch,
  single,
  sparePartsRegistrationList,
  title,
  total,
  upload
} = toRefs(state);

const getList = () => {
  loading.value = true;

  // 处理日期范围参数
  if (!queryParams.value.params) {
    queryParams.value.params = {};
  }
  if (daterange.value && daterange.value.length === 2) {
    queryParams.value.params.beginDate = daterange.value[0];
    queryParams.value.params.endDate = daterange.value[1];
  } else {
    // 清空日期范围参数
    delete queryParams.value.params.beginDate;
    delete queryParams.value.params.endDate;
  }
  listSparePartsRegistration(queryParams.value).then((response) => {
    sparePartsRegistrationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

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

const reset = () => {
  form.value = {
    objid: null,
    date: null,
    sparePartsName: null,
    wasteQuantity: null,
    storageLocation: null,
    registrar: null,
    warehouseConfirmation: null,
    remarks: null
  };
  formRef.value?.resetFields();
};

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

const resetQuery = () => {
  daterange.value = [];
  queryFormRef.value?.resetFields();
  handleQuery();
};

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

const handleAdd = () => {
  reset();
  // 如果有复制的数据，填充备件名称和型号
  if (copiedData.value) {
    form.value.sparePartsName = copiedData.value.sparePartsName;
    form.value.sparePartModel = copiedData.value.sparePartModel;
  }
  open.value = true;
  title.value = '添加  动力能源部行输科废旧备件登记';
};

const handleUpdate = (row) => {
  reset();
  const objid = row.objid || ids.value;
  getSparePartsRegistration(objid).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = '修改  动力能源部行输科废旧备件登记';
  });
};

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.value.objid != null) {
        updateSparePartsRegistration(form.value).then((response) => {
          proxy?.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        addSparePartsRegistration(form.value).then((response) => {
          proxy?.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
};

const handleDelete = (row) => {
  const objids = row.objid || ids.value;
  proxy?.$modal
    .confirm('是否确认删除动力能源部行输科废旧备件登记编号为"' + objids + '"的数据项？')
    .then(function () {
      return delSparePartsRegistration(objids);
    })
    .then(() => {
      getList();
      proxy?.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
};

const handleExport = () => {
  proxy?.download(
    'ems/info/sparePartsRegistration/export',
    {
      ...queryParams.value
    },
    `sparePartsRegistration_${new Date().getTime()}.xlsx`
  );
};

const handleImport = () => {
  upload.value.title = '废旧备件登记导入';
  upload.value.open = true;
};

const importTemplate = () => {
  proxy?.download('ems/info/sparePartsRegistration/importTemplate', {}, `sparePartsRegistration_template_${new Date().getTime()}.xlsx`);
};

const handleFileUploadProgress = (event, file, fileList) => {
  upload.value.isUploading = true;
};

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

const submitFileForm = () => {
  uploadRef.value?.submit();
};

const handleCopy = (row) => {
  copiedData.value = {
    sparePartsName: row.sparePartsName,
    sparePartModel: row.sparePartModel
  };
  proxy?.$modal.msgSuccess('已复制备件名称和型号');
};

const handleViewDetail = (row) => {
  currentRecord.value = {
    ...row
  };
  detailDrawer.value = true;
};

const handleRowContextMenu = (row, column, event) => {
  event.preventDefault();
  contextMenu.value.row = row;
  contextMenu.value.visible = true;

  // 计算菜单位置
  const x = event.clientX;
  const y = event.clientY;
  const menuWidth = 120;
  const menuHeight = 120;
  const windowWidth = window.innerWidth;
  const windowHeight = window.innerHeight;
  contextMenu.value.left = x + menuWidth > windowWidth ? x - menuWidth : x;
  contextMenu.value.top = y + menuHeight > windowHeight ? y - menuHeight : y;
};

const hideContextMenu = () => {
  contextMenu.value.visible = false;
};

const contextMenuViewDetail = () => {
  if (contextMenu.value.row) {
    handleViewDetail(contextMenu.value.row);
  }
  hideContextMenu();
};

const contextMenuEdit = () => {
  if (contextMenu.value.row && checkPermi(['ems/info:sparePartsRegistration:edit'])) {
    handleUpdate(contextMenu.value.row);
  }
  hideContextMenu();
};

const contextMenuDelete = () => {
  if (contextMenu.value.row && checkPermi(['ems/info:sparePartsRegistration:remove'])) {
    handleDelete(contextMenu.value.row);
  }
  hideContextMenu();
};

const checkPermi = (permissions) => {
  return checkPermi(permissions);
};

const { handleClearAll } = useEmsClearAll(clearAllConfig, getList);

onMounted(() => {
  getList();
});

onMounted(() => {
  // script setup 下没有 this，上下文菜单回收必须绑定稳定函数引用，否则解绑会失效。
  document.addEventListener('click', hideContextMenu);
});

onBeforeUnmount(() => {
  // 这里复用同一个函数引用，避免页面切换后遗留全局监听器。
  document.removeEventListener('click', hideContextMenu);
});
</script>

<style scoped>
.context-menu-table tbody tr:hover {
  cursor: context-menu;
}

.context-menu {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 4px 0;
  min-width: 120px;
}

.context-menu-item {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
}

.context-menu-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.context-menu-item i {
  margin-right: 8px;
  font-size: 14px;
}

.el-descriptions__label {
  width: 90px !important;
}

@media (max-width: 768px) {
  .el-drawer {
    width: 90% !important;
  }
}

@media print {
  .context-menu {
    display: none !important;
  }
}
</style>
