<template>
  <div class="p-2 auto-overflow-y">
    <el-row :gutter="10">
      <el-col :lg="5" :xs="24">
        <el-card shadow="hover" class="max-h-95%">
          <template #header>
            <div><span class="text-red-500 text-lg">区域列表</span></div>
          </template>
          <!-- <el-input v-model="areaNames" placeholder="请输入区域名称" prefix-icon="Search" clearable /> -->
          <el-tree
            ref="areaTreeRef"
            v-loading="areaLoading"
            class="mt-2 w-full h-700px inline-block overflow-auto tree"
            node-key="areaId"
            :data="ptAreaOptions"
            :props="{ label: 'areaName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            :default-expanded-keys="expandKeys"
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      <el-col :lg="19" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="search">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px" class="-mb-15px">
              <el-form-item label="设备机号" prop="termNo">
                <el-input v-model="queryParams.termNo" placeholder="请输入设备机号" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="设备名称" prop="termName">
                <el-input v-model="queryParams.termName" placeholder="请输入设备名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="设备IP" prop="termIp">
                <el-input v-model="queryParams.termIp" placeholder="请输入设备IP" clearable style="width: 240px" @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" class="max-h-85%">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-hasPermi="['consumption:xfTerm: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="['consumption:xfTerm:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                  >删除</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 v-hasPermi="['consumption:xfTerm:export']">
                      <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>
              <right-toolbar v-model:showSearch="showSearch" :columns="columns" @query-table="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table
            v-loading="loading"
            :data="xfTermList"
            max-height="calc(100vh - 25.6rem)"
            flexible
            table-layout="auto"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column v-if="columns[0].visible" label="设备机号" align="center" prop="termNo" width="90" />
            <el-table-column v-if="columns[1].visible" label="设备名称" align="left" header-align="center" prop="termName" show-overflow-tooltip />
            <el-table-column v-if="columns[2].visible" label="所属餐厅" align="left" header-align="center" prop="roomName" show-overflow-tooltip />
            <el-table-column v-if="columns[3].visible" label="结算账户" align="left" header-align="center" prop="accountName" show-overflow-tooltip />
            <el-table-column v-if="columns[4].visible" label="设备类型" align="left" header-align="center" prop="termType" show-overflow-tooltip>
              <template #default="scope">
                <dict-tag :options="XF_TermType" :value="scope.row.termType" />
              </template>
            </el-table-column>
            <el-table-column v-if="columns[5].visible" label="扣费类型" align="center" prop="consumeType">
              <template #default="scope">
                <dict-tag :options="XF_ConsumeType" :value="scope.row.consumeType" />
              </template>
            </el-table-column>
            <el-table-column v-if="columns[6].visible" label="设备IP" align="center" prop="termIp" />
            <el-table-column v-if="columns[7].visible" label="设备通讯端口" align="center" prop="commPort" />
            <el-table-column v-if="columns[8].visible" label="备注" align="center" prop="remark" />
            <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="['consumption:xfTerm:edit']"
                    link
                    type="primary"
                    icon="setting"
                    @click="openParamForm(scope.row)"
                  ></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button
                    v-hasPermi="['consumption:xfTerm: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" :pt-area-options="ptAreaOptions" apped-to-body @success="getList" />
    <EditTermParam ref="editTermParamRef"></EditTermParam>
    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" 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
      >
        <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>
  </div>
</template>

<script setup name="XfTerm" lang="ts">
/** 模块导入 */
import { listXfTerm, delXfTerm } from '@/api/consumption/xfTerm';
import { XfTermVO } from '@/api/consumption/xfTerm/types';
import DetailForm from './DetailForm.vue';
import { PtAreaOption, PtAreaVO } from '@/api/basics/room/ptArea/types';
import { queryRoom2AreaList } from '@/api/basics/room/ptRoom';
import { listPtArea } from '@/api/basics/room/ptArea';
import EditTermParam from './EditTermParam.vue';
import { globalHeaders } from '@/utils/request';

defineOptions({ name: 'XfTerm' });

const uploadRef = ref<ElUploadInstance>();
const areaNames = ref<string>('');
const areaLoading = ref(false);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
/** 当前页面引用的数据字典 */
const { YYXT, XF_ConsumeType, XF_WorkMode, XF_TermType } = toRefs<any>(proxy?.useDict('YYXT', 'XF_ConsumeType', 'XF_WorkMode', 'XF_TermType'));
// 是否加载遮罩层
const loading = ref(true);
// 是否显示查询项
const showSearch = ref(true);
const xfTermList = ref<XfTermVO[]>([]);
const ptAreaOptions = ref<PtAreaOption[]>([]);
const expandKeys = ref<Array<string | number>>([]);
// 列表选中的记录Id
const ids = ref<Array<number | string>>([]);
// 单选
const single = ref(true);
// 多选
const multiple = ref(true);
// 总记录数
const total = ref(0);

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

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: `设备类型`, visible: true, children: [] },
  { key: 6, label: `扣费类型`, visible: true, children: [] },
  { key: 7, label: `设备IP`, visible: true, children: [] },
  { key: 8, label: `设备通讯端口`, visible: true, children: [] },
  { key: 9, label: `备注`, visible: true, children: [] }
]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  termNo: undefined,
  termName: '',
  termIp: '',
  params: {}
});

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

/** 查询消费设备列表 */
const getList = async () => {
  loading.value = true;
  const res = await listXfTerm(queryParams);
  xfTermList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

/** 节点单击事件 */
const handleNodeClick = (data: PtAreaOption) => {
  queryParams.params = { roomId: data.areaId };
  if (typeof data.areaId == 'string') {
    queryParams.params = { roomId: data.areaId, type: 'area' };
  }
  handleQuery();
};

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

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

/** 删除按钮操作 */
const handleDelete = async (row?: XfTermVO) => {
  const _termIds = row?.termId || ids.value;
  await proxy?.$modal.confirm('是否确认删除消费设备编号为"' + _termIds + '"的数据项？').finally(() => (loading.value = false));
  await delXfTerm(_termIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

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

const handleExportTemplate = () => {
  proxy?.download('backstage/consumption/xfTerm/exportTemplate', {}, `消费设备导入模板_${new Date().getTime()}.xlsx`);
};

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '设备信息导入';
  upload.open = true;
};

/**文件上传中处理 */
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();
};

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

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

const openParamForm = (row?: XfTermVO) => {
  const id = row?.termId || ids.value[0];
  const title = row?.termName || '';
  editTermParamRef?.value.open(title + '_消费设备参数编辑', id);
};

/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

watch(areaNames, (newValue, oldValue) => {
  getMapRS();
});

const getMapRS = async () => {
  areaLoading.value = true;
  let roomMaps: Map<number, PtAreaVO[]> = null;
  await queryRoom2AreaList().then((res) => {
    roomMaps = res.data;
  });
  const res = await listPtArea();
  // 将areaId转换为字符串 避免id重复
  res.data.forEach((item) => {
    item.areaId = '' + item.areaId;
    item.parentId = '' + item.parentId;
  });
  const data: PtAreaOption[] = proxy?.handleTree<PtAreaOption>(res.data, 'areaId', 'parentId');
  //递归设置最后节点的children
  const setChildren = (node: PtAreaOption) => {
    if (node.children) {
      node.children.forEach((child) => {
        setChildren(child);
      });
    } else {
      //node.areaId去除前缀
      //判断node.areaId是否为字符串
      let id = node.areaId;
      if (typeof node.areaId == 'string') {
        id = parseInt(node.areaId);
      }
      const children = roomMaps[id];
      if (children) {
        const list: PtAreaOption[] = [];
        children.forEach((child) => {
          list.push({
            areaId: child.areaId,
            areaName: child.areaName,
            children: []
          });
        });
        node.children = list;
      }
    }
  };

  data.forEach((node) => {
    setChildren(node);
  });

  ptAreaOptions.value = [];
  ptAreaOptions.value.push(...data);
  areaLoading.value = false;
  expandKeys.value = [ptAreaOptions.value[0].areaId];
};
onMounted(() => {
  getList();
  getMapRS();
});
</script>
