<!-- 机构信息 -->
<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div v-show="visible" class="search-container">
      <el-form
        ref="queryFormRef"
        :model="queryFormData"
        label-suffix=":"
        :inline="true"
        @submit.prevent="handleQuery"
      >
        <el-form-item label="机构编号 " prop="mec_no">
          <el-input v-model="queryFormData.mec_no" placeholder="请输入机构编号 " clearable />
        </el-form-item>
        <el-form-item label="行车" prop="crane_no">
          <CraneTableSelect
            v-model="queryFormData.crane_no"
            @confirm-click="handleConfirm"
            @clear-click="handleQuery"
          />
        </el-form-item>
        <el-form-item label="机构分类" prop="mec_category">
          <el-select
            v-model="queryFormData.mec_category"
            placeholder="请选择机构分类"
            style="width: 167.5px"
            clearable
          >
            <el-option
              v-for="item in dictStore.getDictArray('mec_category')"
              :key="item.dict_value"
              :value="item.dict_value"
              :label="item.dict_label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="机构类型" prop="mec_type">
          <el-select
            v-model="queryFormData.mec_type"
            placeholder="请选择机构类型"
            style="width: 167.5px"
            clearable
          >
            <el-option
              v-for="item in dictStore.getDictArray('mec_type')"
              :key="item.dict_value"
              :value="item.dict_value"
              :label="item.dict_label"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-select
            v-model="queryFormData.status"
            placeholder="请选择状态"
            style="width: 170px"
            clearable
          >
            <el-option value="1" label="启用" />
            <el-option value="0" label="停用" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="isExpand" prop="created_time" label="创建时间">
          <DatePicker v-model="createdDateRange" @update:model-value="handleCreatedDateRangeChange" />
        </el-form-item>
        <el-form-item v-if="isExpand" prop="updated_time" label="更新时间">
          <DatePicker v-model="updatedDateRange" @update:model-value="handleUpdatedDateRangeChange" />
        </el-form-item>
        <!-- 查询、重置、展开/收起按钮 -->
        <el-form-item>
          <el-button
            v-hasPerm="['module_business:mec:query']"
            type="primary"
            icon="search"
            @click="handleQuery"
          >
            查询
          </el-button>
          <el-button
            v-hasPerm="['module_business:mec:query']"
            icon="refresh"
            @click="handleResetQuery"
          >
            重置
          </el-button>
          <!-- 展开/收起 -->
          <template v-if="isExpandable">
            <el-link class="ml-3" type="primary" underline="never" @click="isExpand = !isExpand">
              {{ isExpand ? "收起" : "展开" }}
              <el-icon>
                <template v-if="isExpand">
                  <ArrowUp />
                </template>
                <template v-else>
                  <ArrowDown />
                </template>
              </el-icon>
            </el-link>
          </template>
        </el-form-item>
      </el-form>
    </div>

    <!-- 内容区域 -->
    <el-card class="data-table">
      <template #header>
        <div class="card-header">
          <span>
            机构信息列表
            <el-tooltip content="机构信息列表">
              <QuestionFilled class="w-4 h-4 mx-1" />
            </el-tooltip>
          </span>
        </div>
      </template>

      <!-- 功能区域 -->
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--left">
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-button
                v-hasPerm="['module_business:mec:create']"
                type="success"
                icon="plus"
                @click="handleOpenDialog('create')"
              >
                新增
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                v-hasPerm="['module_business:mec:delete']"
                type="danger"
                icon="delete"
                :disabled="selectIds.length === 0"
                @click="handleDelete(selectIds)"
              >
                批量删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-dropdown v-hasPerm="['module_business:mec:batch']" trigger="click">
                <el-button type="default" :disabled="selectIds.length === 0" icon="ArrowDown">
                  更多
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :icon="Check" @click="handleMoreClick('1')">
                      批量启用
                    </el-dropdown-item>
                    <el-dropdown-item :icon="CircleClose" @click="handleMoreClick('0')">
                      批量停用
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-col>
          </el-row>
        </div>
        <div class="data-table__toolbar--right">
          <el-row :gutter="10">
            <!-- <el-col :span="1.5">
              <el-tooltip content="导入">
                <el-button
                  v-hasPerm="['module_business:mec:import']"
                  type="success"
                  icon="upload"
                  circle
                  @click="handleOpenImportDialog"
                />
              </el-tooltip>
            </el-col> -->
            <el-col :span="1.5">
              <el-tooltip content="导出">
                <el-button
                  v-hasPerm="['module_business:mec:export']"
                  type="warning"
                  icon="download"
                  circle
                  @click="handleOpenExportsModal"
                />
              </el-tooltip>
            </el-col>
            <el-col :span="1.5">
              <el-tooltip content="搜索显示/隐藏">
                <el-button
                  v-hasPerm="['*:*:*']"
                  type="info"
                  icon="search"
                  circle
                  @click="visible = !visible"
                />
              </el-tooltip>
            </el-col>
            <el-col :span="1.5">
              <el-tooltip content="刷新">
                <el-button
                  v-hasPerm="['module_business:mec:query']"
                  type="primary"
                  icon="refresh"
                  circle
                  @click="handleRefresh"
                />
              </el-tooltip>
            </el-col>
            <el-col :span="1.5">
              <el-popover placement="bottom" trigger="click">
                <template #reference>
                  <el-button type="danger" icon="operation" circle></el-button>
                </template>
                <el-scrollbar max-height="350px">
                  <template v-for="column in tableColumns" :key="column.prop">
                    <el-checkbox v-if="column.prop" v-model="column.show" :label="column.label" />
                  </template>
                </el-scrollbar>
              </el-popover>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 表格区域：系统配置列表 -->
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="pageTableData"
        highlight-current-row
        class="data-table__content"
        :height="450"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <template #empty>
          <el-empty :image-size="80" description="暂无数据" />
        </template>
        <el-table-column
          v-if="tableColumns.find((col) => col.prop === 'selection')?.show"
          type="selection"
          min-width="55"
          align="center"
        />
        <el-table-column
          v-if="tableColumns.find((col) => col.prop === 'index')?.show"
          fixed
          label="序号"
          min-width="60"
        >
          <template #default="scope">
            {{ (queryFormData.page_no - 1) * queryFormData.page_size + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'crane_name')?.show" label="行车 " prop="crane_name" min-width="140">
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'mec_no')?.show" label="机构编号 " prop="mec_no" min-width="200">
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'mec_category')?.show" 
          label="机构分类" 
          prop="mec_category" 
          min-width="100">
          <template #default="scope">
            {{
                (scope.row.mec_category
                  ? (dictStore.getDictLabel("mec_category", scope.row.mec_category) as any)
                  : undefined
                )?.dict_label || scope.row.mec_category
            }}
          </template>
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'mec_type')?.show" 
          label="机构类型" 
          prop="mec_type" 
          min-width="100">
          <template #default="scope">
            {{
                (scope.row.mec_type
                  ? (dictStore.getDictLabel("mec_type", scope.row.mec_type) as any)
                  : undefined
                )?.dict_label || scope.row.mec_type
            }}
          </template>
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'hoist_weight')?.show" label="起升重量" prop="hoist_weight" min-width="100">
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'hoist_height')?.show" label="起升高度" prop="hoist_height" min-width="100">
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'sort')?.show" label="排序 " prop="sort" min-width="80">
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'status')?.show" label="是否启用" prop="status" min-width="140">
          <template #default="scope">
            <el-tag :type="scope.row.status == '1' ? 'success' : 'info'">
              {{ scope.row.status == '1' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column v-if="tableColumns.find((col) => col.prop === 'hoist_weight_var_code')?.show" label="重量关联变量" prop="hoist_weight_var_code" min-width="140">
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'stroke_var_code')?.show" label="行程高度变量" prop="stroke_var_code" min-width="140">
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'is_canvas_show')?.show" label="首页动画展示" prop="is_canvas_show" min-width="140">
          <template #default="scope">
            <el-tag :type="scope.row.is_canvas_show == '1' ? 'success' : 'info'">
              {{ scope.row.is_canvas_move == '1' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'is_canvas_move')?.show" label="启用动画" prop="is_canvas_move" min-width="140">
          <template #default="scope">
            <el-tag :type="scope.row.is_canvas_move == '1' ? 'success' : 'info'">
              {{ scope.row.is_canvas_move == '1' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'created_time')?.show" label="创建时间" prop="created_time" min-width="200">
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'updated_time')?.show" label="更新时间" prop="updated_time" min-width="200">
        </el-table-column>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'description')?.show" label="备注/描述" prop="description" min-width="140">
        </el-table-column>
        <el-table-column
          v-if="tableColumns.find((col) => col.prop === 'operation')?.show"
          fixed="right"
          label="操作"
          align="center"
          min-width="200"
        >
          <template #default="scope">
            <el-button
              v-hasPerm="['module_business:mec:detail']"
              type="info"
              size="small"
              link
              icon="document"
              @click="handleOpenDialog('detail', scope.row.id)"
            >
              详情
            </el-button>
            <el-button
              v-hasPerm="['module_business:mec:update']"
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog('update', scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              v-hasPerm="['module_business:mec:delete']"
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete([scope.row.id])"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <template #footer>
        <pagination
          v-model:total="total"
          v-model:page="queryFormData.page_no"
          v-model:limit="queryFormData.page_size"
          @pagination="loadingData"
        />
      </template>
    </el-card>

    <!-- 弹窗区域 -->
    <el-dialog
      v-model="dialogVisible.visible"
      :title="dialogVisible.title"
      @close="handleCloseDialog"
    >
      <!-- 详情 -->
      <template v-if="dialogVisible.type === 'detail'">
        <el-descriptions :column="4" border>
            <el-descriptions-item label="行车" :span="2">
              {{ detailFormData.crane_name }}
            </el-descriptions-item>
            <el-descriptions-item label="机构编号" :span="2">
              {{ detailFormData.mec_no }}
            </el-descriptions-item>
            <el-descriptions-item label="机构分类" :span="2">
              {{ (detailFormData.mec_category 
                  ? (dictStore.getDictLabel("mec_category", detailFormData.mec_category) as any)
                  : undefined
                )?.dict_label || detailFormData.mec_category }}
            </el-descriptions-item>
            <el-descriptions-item label="机构类型" :span="2">
              {{ (detailFormData.mec_type 
                  ? (dictStore.getDictLabel("mec_type", detailFormData.mec_type) as any)
                  : undefined
                )?.dict_label || detailFormData.mec_type }}
            </el-descriptions-item>
            <el-descriptions-item label="起升重量" :span="2" v-if="detailFormData.mec_category === '1'">
              {{ detailFormData.hoist_weight }}
            </el-descriptions-item>
            <el-descriptions-item label="起升高度" :span="2" v-if="detailFormData.mec_category === '1'">
              {{ detailFormData.hoist_height }}
            </el-descriptions-item>
            <el-descriptions-item label="排序 " :span="2">
              {{ detailFormData.sort }}
            </el-descriptions-item>
            <el-descriptions-item label="UUID全局唯一标识" :span="2">
              {{ detailFormData.uuid }}
            </el-descriptions-item>
            <el-descriptions-item label="状态" :span="2">
              <el-tag :type="detailFormData.status == '1' ? 'success' : 'danger'">
                {{ detailFormData.status == '1' ? "启用" : "停用" }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="备注/描述" :span="2">
              {{ detailFormData.description }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间" :span="2">
              {{ detailFormData.created_time }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间" :span="2">
              {{ detailFormData.updated_time }}
            </el-descriptions-item>
            <el-descriptions-item label="重量关联变量" :span="2">
              {{ detailFormData.hoist_weight_var_code }}
            </el-descriptions-item>
            <el-descriptions-item label="行程高度变量" :span="2">
              {{ detailFormData.stroke_var_code }}
            </el-descriptions-item>
            <el-descriptions-item label="是否首页动画展示" :span="2">
              <el-tag :type="detailFormData.is_canvas_show == '1' ? 'success' : 'danger'">
                {{ detailFormData.is_canvas_show == '1' ? "启用" : "停用" }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="是否启用动画" :span="2">
              <el-tag :type="detailFormData.is_canvas_move == '1' ? 'success' : 'danger'">
                {{ detailFormData.is_canvas_move == '1' ? "启用" : "停用" }}
              </el-tag>
            </el-descriptions-item>
        </el-descriptions>
      </template>

      <!-- 新增、编辑表单 -->
      <template v-else>
        <el-form ref="dataFormRef" :model="formData" :rules="rules" label-suffix=":" label-width="auto" label-position="right">
          <el-form-item label="行车" prop="crane_no" :required="true">
              <CraneTableSelect
                v-model="formData.crane_no"
                @confirm-click="handleConfirm"
                @clear-click="handleQuery"
              />
          </el-form-item>
          <el-form-item label="机构编号" prop="mec_no" :required="true">
            <el-input v-model="formData.mec_no" placeholder="请输入机构编号 " />
          </el-form-item>
          <el-form-item label="机构分类" prop="mec_category" :required="true" class="w-100">
            <el-select v-model="formData.mec_category" placeholder="请选择机构分类" clearable>
              <el-option
                v-for="item in dictStore.getDictArray('mec_category')"
                :key="item.dict_value"
                :value="item.dict_value.toString()"
                :label="item.dict_label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="机构类型" prop="mec_type" :required="true" class="w-100">
            <el-select v-model="formData.mec_type" placeholder="请输入机构类型" clearable>
              <el-option
                v-for="item in dictStore.getDictArray('mec_type')"
                :key="item.dict_value"
                :value="item.dict_value.toString()"
                :label="item.dict_label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="起升重量" prop="hoist_weight" :required="true" v-if="formData.mec_category === '1'">
            <el-input v-model="formData.hoist_weight" placeholder="请输入起升重量" />
          </el-form-item>
          <el-form-item label="起升高度" prop="hoist_height" :required="true" v-if="formData.mec_category === '1'">
            <el-input v-model="formData.hoist_height" placeholder="请输入起升高度" />
          </el-form-item>
          <el-form-item label="排序 " prop="sort" :required="true">
            <el-input v-model="formData.sort" placeholder="请输入排序 " />
          </el-form-item>
          <el-form-item label="状态" prop="status" :required="true">
            <el-radio-group v-model="formData.status">
              <el-radio value="1">启用</el-radio>
              <el-radio value="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="重量关联变量" prop="hoist_weight_var_code" :required="false">
            <el-input v-model="formData.hoist_weight_var_code" placeholder="请输入重量关联变量" />
          </el-form-item>
          <el-form-item label="行程高度变量" prop="stroke_var_code" :required="false">
            <el-input v-model="formData.stroke_var_code" placeholder="请输入行程高度变量" />
          </el-form-item>
          <el-form-item label="是否首页动画展示" prop="is_canvas_show" :required="false">
            <el-radio-group v-model="formData.is_canvas_show">
              <el-radio value="1">是</el-radio>
              <el-radio value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否启用动画" prop="is_canvas_move" :required="false">
            <el-radio-group v-model="formData.is_canvas_move">
              <el-radio value="1">是</el-radio>
              <el-radio value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formData.description"
              :rows="4"
              :maxlength="100"
              show-word-limit
              type="textarea"
              placeholder="请输入描述"
            />
          </el-form-item>
        </el-form>
      </template>

      <template #footer>
        <div class="dialog-footer">
          <!-- 详情弹窗不需要确定按钮的提交逻辑 -->
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button v-if="dialogVisible.type !== 'detail'" type="primary" @click="handleSubmit">
            确定
          </el-button>
          <el-button v-else type="primary" @click="handleCloseDialog">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入弹窗 -->
    <ImportModal
      v-model="importDialogVisible"
      :content-config="curdContentConfig"
      @upload="handleUpload"
    />

    <!-- 导出弹窗 -->
    <ExportModal
      v-model="exportsDialogVisible"
      :content-config="curdContentConfig"
      :query-params="queryFormData"
      :page-data="pageTableData"
      :selection-data="selectionRows"
    />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "BizMec",
  inheritAttrs: false,
});

import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { QuestionFilled, ArrowUp, ArrowDown, Check, CircleClose } from '@element-plus/icons-vue'
import { formatToDateTime } from "@/utils/dateUtil";
import { useDictStore } from "@/store";
import { ResultEnum } from '@/enums/api/result.enum'
import DatePicker from "@/components/DatePicker/index.vue";
import type { IContentConfig } from "@/components/CURD/types";
import ImportModal from "@/components/CURD/ImportModal.vue";
import ExportModal from "@/components/CURD/ExportModal.vue";
import BizMecAPI, { BizMecPageQuery, BizMecTable, BizMecForm } from '@/api/module_business/mec'
import CraneTableSelect from '../crane/components/CraneTableSelect.vue';

const visible = ref(true);
const isExpand = ref(false);
const isExpandable = ref(true);
const queryFormRef = ref();
const dataFormRef = ref();
const total = ref(0);
const selectIds = ref<number[]>([]);
const selectionRows = ref<BizMecTable[]>([]);
const loading = ref(false);

// 字典仓库与需要加载的字典类型
const dictStore = useDictStore()
const dictTypes: any = [
  'mec_type',
  'mec_category',
]

// 分页表单
const pageTableData = ref<BizMecTable[]>([]);

// 表格列配置
const tableColumns = ref([
  { prop: "selection", label: "选择框", show: true },
  { prop: "index", label: "序号", show: true },
  { prop: 'crane_name', label: '行车', show: true },
  { prop: 'crane_no', label: '行车编号', show: true },
  { prop: 'mec_no', label: '机构编号', show: true },
  { prop: 'mec_category', label: '机构分类', show: true },
  { prop: 'mec_type', label: '机构类型', show: true },
  { prop: 'hoist_weight', label: '起升重量', show: true },
  { prop: 'hoist_height', label: '起升高度', show: true },
  { prop: 'sort', label: '排序', show: true },
  { prop: 'status', label: '是否启用', show: true },
  { prop: 'description', label: '备注/描述', show: true },
  { prop: 'created_time', label: '创建时间', show: true },
  { prop: 'updated_time', label: '更新时间', show: true },
  { prop: 'hoist_weight_var_code', label: '重量关联变量', show: true },
  { prop: 'stroke_var_code', label: '行程高度变量', show: true },
  { prop: 'is_canvas_show', label: '是否首页动画展示', show: true },
  { prop: 'is_canvas_move', label: '是否启用动画', show: true },
  { prop: 'operation', label: '操作', show: true }
]);

// 导出列（不含选择/序号/操作）
const exportColumns = [
  { prop: 'crane_name', label: '行车' },
  { prop: 'mec_no', label: '机构编号' },
  { prop: 'mec_category', label: '机构分类' },
  { prop: 'mec_type', label: '机构类型' },
  { prop: 'hoist_weight', label: '起升重量' },
  { prop: 'hoist_height', label: '起升高度' },
  { prop: 'sort', label: '排序' },
  { prop: 'status', label: '是否启用(0 禁用 1 启用)' },
  { prop: 'description', label: '备注/描述' },
  { prop: 'created_time', label: '创建时间' },
  { prop: 'updated_time', label: '更新时间' },
  { prop: 'hoist_weight_var_code', label: '重量关联变量' },
  { prop: 'stroke_var_code', label: '行程高度变量' },
  { prop: 'is_canvas_show', label: '是否首页动画展示(0 禁用 1 启用)' },
  { prop: 'is_canvas_move', label: '是否启用动画(0 禁用 1 启用)' },
]

// 导入/导出配置
const curdContentConfig = {
  permPrefix: "module_business:mec",
  cols: exportColumns as any,
  importTemplate: () => BizMecAPI.downloadTemplateBizMec(),
  exportsAction: async (params: any) => {
    const query: any = { ...params };
    query.status = '0';
    query.page_no = 1;
    query.page_size = 9999;
    const all: any[] = [];
    while (true) {
      const res = await BizMecAPI.listBizMec(query);
      const items = res.data?.data?.items || [];
      const total = res.data?.data?.total || 0;
      all.push(...items);
      if (all.length >= total || items.length === 0) break;
      query.page_no += 1;
    }
    return all;
  },
} as unknown as IContentConfig;

// 详情表单
const detailFormData = ref<BizMecTable>({});
// 日期范围临时变量
const createdDateRange = ref<[Date, Date] | []>([]);
// 更新时间范围临时变量
const updatedDateRange = ref<[Date, Date] | []>([]);

// 处理创建时间范围变化
function handleCreatedDateRangeChange(range: [Date, Date]) {
  createdDateRange.value = range;
  if (range && range.length === 2) {
    queryFormData.created_time = [formatToDateTime(range[0]), formatToDateTime(range[1])];
  } else {
    queryFormData.created_time = undefined;
  }
}

// 处理更新时间范围变化
function handleUpdatedDateRangeChange(range: [Date, Date]) {
  updatedDateRange.value = range;
  if (range && range.length === 2) {
    queryFormData.updated_time = [formatToDateTime(range[0]), formatToDateTime(range[1])];
  } else {
    queryFormData.updated_time = undefined;
  }
}

// 分页查询参数
const queryFormData = reactive<BizMecPageQuery>({
  page_no: 1,
  page_size: 10,
  crane_no: undefined,
  mec_no: undefined,
  mec_category: undefined,
  mec_type: undefined,
  status: undefined,
  created_time: undefined,
  updated_time: undefined,
});


// 编辑表单
const formData = reactive<BizMecForm>({
  id: undefined,
  crane_no: undefined,
  mec_no: undefined,
  mec_category: undefined,
  mec_type: undefined,
  hoist_weight: undefined,
  hoist_height: undefined,
  sort: undefined,
  status: undefined,
  description: undefined,
  hoist_weight_var_code: undefined,
  stroke_var_code: undefined,
  is_canvas_show: undefined,
  is_canvas_move: undefined,
});

// 弹窗状态
const dialogVisible = reactive({
  title: "",
  visible: false,
  type: "create" as "create" | "update" | "detail",
});

// 表单验证规则
const rules = reactive({
  id: [
    { required: false, message: '请输入编号', trigger: 'blur' },
  ],
  crane_no: [
    { required: false, message: '请输入行车编号', trigger: 'blur' },
  ],
  mec_no: [
    { required: false, message: '请输入机构编号', trigger: 'blur' },
  ],
  mec_category: [
    { required: false, message: '请输入机构分类', trigger: 'blur' },
  ],
  mec_type: [
    { required: false, message: '请输入机构类型', trigger: 'blur' },
  ],
  hoist_weight: [
    { required: false, message: '请输入起升重量', trigger: 'blur' },
  ],
  hoist_height: [
    { required: false, message: '请输入起升高度', trigger: 'blur' },
  ],
  sort: [
    { required: false, message: '请输入排序', trigger: 'blur' },
  ],
  uuid: [
    { required: true, message: '请输入UUID全局唯一标识', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请输入是否启用', trigger: 'blur' },
  ],
  description: [
    { required: false, message: '请输入备注/描述', trigger: 'blur' },
  ],
  created_time: [
    { required: true, message: '请输入创建时间', trigger: 'blur' },
  ],
  updated_time: [
    { required: true, message: '请输入更新时间', trigger: 'blur' },
  ],
  hoist_weight_var_code: [
    { required: false, message: '请输入重量关联变量', trigger: 'blur' },
  ],
  stroke_var_code: [
    { required: false, message: '请输入行程高度变量', trigger: 'blur' },
  ],
  is_canvas_show: [
    { required: false, message: '请输入是否首页动画展示', trigger: 'blur' },
  ],
  is_canvas_move: [
    { required: false, message: '请输入是否启用动画', trigger: 'blur' },
  ],
});

// 导入弹窗显示状态
const importDialogVisible = ref(false);

// 导出弹窗显示状态
const exportsDialogVisible = ref(false);

// 打开导入弹窗
function handleOpenImportDialog() {
  importDialogVisible.value = true;
}

// 打开导出弹窗
function handleOpenExportsModal() {
  exportsDialogVisible.value = true;
}

// 列表刷新
async function handleRefresh() {
  await loadingData();
}

// 加载表格数据
async function loadingData() {
  loading.value = true;
  try {
    const response = await BizMecAPI.listBizMec(queryFormData);
    pageTableData.value = response.data.data.items;
    total.value = response.data.data.total;
  } catch (error: any) {
    console.error(error);
  } finally {
    loading.value = false;
  }
}

// 查询（重置页码后获取数据）
async function handleQuery() {
  queryFormData.page_no = 1;
  loadingData();
}

// 选择创建人后触发查询
function handleConfirm() {
  handleQuery();
}

// 重置查询
async function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryFormData.page_no = 1;
  // 重置日期范围选择器
  createdDateRange.value = [];
  updatedDateRange.value = [];
  queryFormData.created_time = undefined;
  queryFormData.updated_time = undefined;
  loadingData();
}

// 定义初始表单数据常量
const initialFormData: BizMecForm = {
  id: undefined,
  crane_no: undefined,
  mec_no: undefined,
  mec_category: undefined,
  mec_type: undefined,
  hoist_weight: undefined,
  hoist_height: undefined,
  sort: undefined,
  status: undefined,
  description: undefined,
  hoist_weight_var_code: undefined,
  stroke_var_code: undefined,
  is_canvas_show: undefined,
  is_canvas_move: undefined,
};

// 重置表单
async function resetForm() {
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
  }
  // 完全重置 formData 为初始状态
  Object.assign(formData, initialFormData);
}

// 行复选框选中项变化
async function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
  selectionRows.value = selection;
}

// 关闭弹窗
async function handleCloseDialog() {
  dialogVisible.visible = false;
  resetForm();
}

// 打开弹窗
async function handleOpenDialog(type: "create" | "update" | "detail", id?: number) {
  dialogVisible.type = type;
  if (id) {
    const response = await BizMecAPI.detailBizMec(id);
    console.log(response.data.data);
    if (type === "detail") {
      dialogVisible.title = "详情";
      Object.assign(detailFormData.value, response.data.data);
    } else if (type === "update") {
      dialogVisible.title = "修改";
      Object.assign(formData, response.data.data);
    }
  } else {
    dialogVisible.title = "新增";
    formData.id = undefined;
    formData.crane_no = undefined;
    formData.mec_no = `${Date.now()}${Math.floor(Math.random() * 1000)}`;;
    formData.mec_category = undefined;
    formData.mec_type = undefined;
    formData.hoist_weight = undefined;
    formData.hoist_height = undefined;
    formData.sort = undefined;
    formData.status = '1';
    formData.description = undefined;
    formData.hoist_weight_var_code = undefined;
    formData.stroke_var_code = undefined;
    formData.is_canvas_show = '0';
    formData.is_canvas_move = '0';
  }
  dialogVisible.visible = true;
}

// 提交表单（防抖）
async function handleSubmit() {
  // 表单校验
  dataFormRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      // 根据弹窗传入的参数(deatil\create\update)判断走什么逻辑
      const id = formData.id;
      if (id) {
        try {
          await BizMecAPI.updateBizMec(id, { id, ...formData });
          dialogVisible.visible = false;
          resetForm();
          handleCloseDialog();
          handleResetQuery();
        } catch (error: any) {
          console.error(error);
        } finally {
          loading.value = false;
        }
      } else {
        try {
          await BizMecAPI.createBizMec(formData);
          dialogVisible.visible = false;
          resetForm();
          handleCloseDialog();
          handleResetQuery();
        } catch (error: any) {
          console.error(error);
        } finally {
          loading.value = false;
        }
      }
    }
  });
}

// 删除、批量删除
async function handleDelete(ids: number[]) {
  ElMessageBox.confirm("确认删除该项数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        loading.value = true;
        await BizMecAPI.deleteBizMec(ids);
        handleResetQuery();
      } catch (error: any) {
        console.error(error);
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      ElMessageBox.close();
    });
}

// 批量启用/停用
async function handleMoreClick(status: string) {
  if (selectIds.value.length) {
    ElMessageBox.confirm(`确认${status === "1" ? "启用" : "停用"}该项数据?`, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        try {
          loading.value = true;
          await BizMecAPI.batchBizMec({ ids: selectIds.value, status });
          handleResetQuery();
        } catch (error: any) {
          console.error(error);
        } finally {
          loading.value = false;
        }
      })
      .catch(() => {
        ElMessageBox.close();
      });
  }
}

// 处理上传
const handleUpload = async (formData: FormData) => {
  try {
    const response = await BizMecAPI.importBizMec(formData);
    if (response.data.code === ResultEnum.SUCCESS) {
      ElMessage.success(`${response.data.msg}，${response.data.data}`);
      importDialogVisible.value = false;
      await handleQuery();
    }
  } catch (error: any) {
    console.error(error);
  }
};

onMounted(async () => {
  // 预加载字典数据
  if (dictTypes.length > 0) {
    await dictStore.getDict(dictTypes)
  }
  loadingData();
});
</script>

<style lang="scss" scoped>
</style>