<template>
  <div class="p-2 auto-overflow-y">
    <el-row :gutter="10">
      <el-col :lg="8" :xs="24">
        <pt-area @get-area-id="getAreaId"></pt-area>
      </el-col>
      <el-col :lg="16" :xs="24" class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="panel">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px" class="-mb-15px">
              <!-- <el-form-item label="所属区域" prop="areaId">
                <el-input v-model="queryParams.areaId" placeholder="请输入所属区域id" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item> 
              <el-form-item label="房间编码" prop="roomCode">
                <el-input v-model="queryParams.roomCode" placeholder="请输入房间编码" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item> -->
              <el-form-item label="房间名称" prop="roomName">
                <el-input v-model="queryParams.roomName" placeholder="请输入房间名称" style="width: 150px" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="房间类型" prop="roomType">
                <el-select v-model="queryParams.roomType" placeholder="请选择房间类型" clearable style="width: 150px">
                  <el-option v-for="dict in FJLX" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="门牌号1" prop="codeOne">
                <el-input v-model="queryParams.codeOne" placeholder="请输入门牌号1" style="width: 150px" 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>
          </div>
        </transition>

        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-hasPermi="['room:ptRoom:add']" type="primary" plain icon="Plus" @click="openForm('create')">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:post:edit']" type="success" plain icon="Edit" :disabled="single" @click="openForm('update')"
                  >修改</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['room:ptRoom:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                  >删除</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['room:ptRoom:set']" type="primary" plain icon="Setting" :disabled="multiple" @click="openDialog()"
                  >批量设置</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  v-hasPermi="['room:ptRoom:set']"
                  type="primary"
                  plain
                  icon="Remove"
                  :disabled="multiple"
                  :loading="unsetLoading"
                  @click="unSet()"
                  >解除设置</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-dropdown class="mt-[1px]">
                  <el-button plain type="info">
                    更多
                    <el-icon class="el-icon--right"><arrow-down /></el-icon
                  ></el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item icon="Download" @click="handleExportTemplate">下载模板</el-dropdown-item>
                      <el-dropdown-item icon="Top" @click="handleImport"> 导入数据</el-dropdown-item>
                      <el-dropdown-item icon="Download" @click="handleExport"> 导出数据</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-col>
              <!-- <el-col :span="1.5">
                <el-button v-hasPermi="['room:ptRoom:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
              </el-col> -->
              <right-toolbar v-model:showSearch="showSearch" :columns="columns" @query-table="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="ptRoomList" height="calc(100vh - 23.75rem)" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column v-if="true" label="房间Id,主键" align="center" prop="roomId" /> -->
            <el-table-column v-if="columns[0].visible" label="所属区域" align="center" prop="areaName" />
            <el-table-column v-if="columns[1].visible" label="房间编码" align="center" prop="roomCode" />
            <el-table-column v-if="columns[2].visible" label="房间名称" align="center" prop="roomName" show-overflow-tooltip />
            <el-table-column v-if="columns[3].visible" label="房间类型" align="center" prop="roomType">
              <template #default="scope">
                <dict-tag :options="FJLX" :value="scope.row.roomType" />
              </template>
            </el-table-column>
            <el-table-column v-if="columns[4].visible" label="门牌号1" align="center" prop="codeOne" />
            <el-table-column v-if="columns[5].visible" label="门牌号2" align="center" prop="codeTwo" />
            <el-table-column v-if="columns[6].visible" label="门牌号3" align="center" prop="codeThree" />
            <el-table-column v-if="columns[7].visible" label="门牌号4" align="center" prop="codeFour" />
            <el-table-column v-if="columns[8].visible" label="门牌号5" align="center" prop="codeFive" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button v-hasPermi="['room:ptRoom:edit']" link type="primary" icon="Edit" @click="openForm('update', scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button v-hasPermi="['room:ptRoom:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
              </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-col>
    </el-row>
    <!-- 添加或修改房间定义对话框 -->
    <detail-form ref="detailFormRef" apped-to-body @success="getList" />

    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="30%" 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
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__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="handleExportTemplate"
              >下载模板</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-dialog v-model="dialog.visible" :title="dialog.title" width="400px" append-to-body>
      <el-form ref="setRef" v-loading="setLoading" :model="setData" :rules="formRules" label-width="80px">
        <el-form-item label="房间类型" prop="roomType">
          <el-select v-model="setData.roomType" placeholder="请选择房间类型">
            <el-option v-for="dict in FJLX" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="setLoading" type="primary" @click="submitSetForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PtRoom" lang="ts">
/** 模块导入 */
import { listPtRoom, delPtRoom, batchSet } from '@/api/basics/room/ptRoom';
import { PtRoomVO } from '@/api/basics/room/ptRoom/types';
import DetailForm from './DetailForm.vue';
import ptArea from '../ptArea/index.vue';
import { globalHeaders } from '@/utils/request';
const uploadRef = ref<ElUploadInstance>();

defineOptions({ name: 'PtRoom' });

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
/** 当前页面引用的数据字典 */
const { FJLX } = toRefs<any>(proxy?.useDict('FJLX'));
// 是否加载遮罩层
const loading = ref(true);
// 是否显示查询项
const showSearch = ref(true);
const ptRoomList = ref<PtRoomVO[]>([]);
// 列表选中的记录Id
const ids = ref<Array<number | string>>([]);
// 单选
const single = ref(true);
// 多选
const multiple = ref(true);
// 总记录数
const total = ref(0);

const setLoading = ref(false);
const unsetLoading = ref(false);

const areaId = ref<string | number>(null);

const getAreaId = (v: string | number) => {
  queryParams.areaId = v;
  getList();
};

// 查询窗体Ref
const queryFormRef = ref<ElFormInstance>();
const setRef = ref<ElFormInstance>();

const columns = ref<FieldOption[]>([
  /* { key: 0, label: `房间Id,主键`, visible: true, children: [] }, */
  { key: 1, label: `所属区域`, visible: true, children: [] },
  { key: 2, label: `房间编码`, visible: true, children: [] },
  { key: 3, label: `房间名称`, visible: true, children: [] },
  { key: 4, label: `房间类型`, visible: true, children: [] },
  { key: 5, label: `门牌号1`, visible: true, children: [] },
  { key: 6, label: `门牌号2`, visible: true, children: [] },
  { key: 7, label: `门牌号3`, visible: true, children: [] },
  { key: 8, label: `门牌号4`, visible: true, children: [] },
  { key: 9, label: `门牌号5`, visible: true, children: [] }
]);

const formRules = reactive({
  roomType: [{ required: true, message: '房间类型不能为空', trigger: 'blur' }]
});

const setData = reactive({
  roomIds: [],
  roomType: ''
});

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  areaId: undefined,
  roomCode: '',
  roomName: '',
  roomType: '',
  codeOne: '',
  codeTwo: '',
  codeThree: '',
  codeFour: '',
  codeFive: '',
  params: {}
});

/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/backstage/room/ptRoom/importData'
});

// 对话框
const dialog = reactive<DialogOption>({
  visible: false,
  title: '批量设置类型'
});

const openDialog = () => {
  dialog.visible = true;
};

const unSet = async () => {
  unsetLoading.value = true;
  try {
    const data = {
      roomIds: ids.value,
      roomType: ''
    };
    await batchSet(data);
    getList();
    proxy?.$modal.msgSuccess('解除设置成功');
  } finally {
    unsetLoading.value = false;
  }
};

const submitSetForm = async () => {
  // 校验表单
  if (!setRef.value) return;
  const valid = await setRef.value?.validate();
  if (!valid) return;
  // 提交请求
  setLoading.value = true;
  try {
    const data = {
      roomIds: ids.value,
      roomType: setData.roomType
    };
    await batchSet(data);
    getList();
    proxy?.$modal.msgSuccess('设置成功');
    dialog.visible = false;
  } finally {
    setLoading.value = false;
  }
};

/** 查询房间定义列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPtRoom(queryParams);
  ptRoomList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: PtRoomVO[]) => {
  ids.value = selection.map((item) => item.roomId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 删除按钮操作 */
const handleDelete = async (row?: PtRoomVO) => {
  const _roomIds = row?.roomId || ids.value;
  await proxy?.$modal.confirm('是否确认删除房间定义编号为"' + _roomIds + '"的数据项？').finally(() => (loading.value = false));
  await delPtRoom(_roomIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'backstage/room/ptRoom/export',
    {
      ...queryParams
    },
    `ptRoom_${new Date().getTime()}.xlsx`
  );
};

const handleExportTemplate = () => {
  proxy?.download('backstage/room/ptRoom/exportTemplate', {}, `ptRoomTemplate_${new Date().getTime()}.xlsx`);
};

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '用户导入';
  upload.open = true;
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

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

/** 弹出框(增加、修改) */
const detailFormRef = ref();
const openForm = (type: string, row?: PtRoomVO) => {
  const id = row?.roomId || ids.value[0];
  detailFormRef?.value.open(type, id);
};
onMounted(() => {
  getList();
});
</script>
