<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="区域名称" prop="regionName">
            <el-input v-model="queryParams.regionName" placeholder="请输入" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="区域标题" prop="regionTitle">
            <el-input v-model="queryParams.regionTitle" placeholder="请输入" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="区域描述" prop="regionDesc">
            <el-input v-model="queryParams.regionDesc" placeholder="请输入" 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 type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['system:region:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['system:region:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['system:region:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['system:region:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="regionList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="区域id" align="center" prop="regionId" v-if="true" />
        <el-table-column label="区域名称" align="center" prop="regionName" />
        <el-table-column label="区域标题" align="center" prop="regionTitle" />

        <el-table-column label="主图展示" align="center" prop="url">
          <template #default="scope">
            <ImagePreview :width="100" :height="100" :src="scope.row.url" :preview-src-list="[scope.row.url]" />
          </template>
        </el-table-column>

        <el-table-column label="区域描述" align="center" prop="regionDesc" />
        <el-table-column label="区域类型" align="center" prop="regionType" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:region:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:region:remove']"></el-button>
            </el-tooltip>
          </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-card>
    <!-- 添加或修改区域对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" append-to-body>
      <el-form ref="regionFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="区域名称" prop="regionName">
              <el-input v-model="form.regionName" placeholder="请输入" style="width: 400px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域标题" prop="regionTitle">
              <el-input v-model="form.regionTitle" placeholder="请输入" style="width: 400px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="区域类型" prop="regionType">
          <el-select v-model="form.regionType" placeholder="区域" clearable style="width:400px">
            <el-option v-for="dict in region_type" :label="dict.label" :value="dict.value" :key="dict.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="区域设施" prop="regionType">
          <el-select v-model="form.regionFacilities" multiple placeholder="区域设施" clearable style="width:500px">
            <el-option v-for="dict in facilities_data" :label="dict.label" :value="dict.value" :key="dict.value" />
          </el-select>
        </el-form-item> -->

        <el-form-item label="区域描述" prop="regionDesc">
          <el-input v-model="form.regionDesc" maxlength="200" placeholder="请输入区域描述" show-word-limit type="textarea"
            rows="5" style="width: 800px;" />
        </el-form-item>
        <el-upload v-model:file-list="fileList" :multiple="true" :action="upload.url" :on-preview="handlePreview"
          :on-remove="handleRemove" :before-remove="beforeRemove" :headers="upload.headers"
          :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload" list-type="picture-card">
          上传区域图
          <template #tip>
            <div class="el-upload__tip">
              小于500KB的jpg/png/jpeg文件
            </div>
          </template>
          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
              <span class="el-upload-list__item-actions">
                <span @click="onClickDefaultPhoto(file)">
                  <el-icon v-if="file.defaults">
                    <Open />
                  </el-icon>
                  <el-icon v-else>
                    <TurnOff />
                  </el-icon>
                </span>
                <span v-if="!disabled" @click="onClickDeletePhoto(file)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>


        <!--设施列表查询-->
        <div id="app">
          <el-button @click="onClickOpen">添加设施</el-button>
          <el-form :model="datas.queryParams" ref="queryFormRefFac" :inline="true" label-width="68px">
            <el-dialog title="设施列表" v-model="dialogVisible" close-on-click-modal="false" width="80%" top="5vh"
              :before-close="handleClose">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" :disabled="multiple" @click="handleAddFac()"
                  v-hasPermi="['system:region:add']">添加设施</el-button>
              </el-col>
              <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
                <div class="search" v-show="showSearch">
                  <el-form :model="datas.queryParams" ref="queryFormRefFac" :inline="true" label-width="68px">
                    <el-form-item label="设施名称" prop="facilitiesName">
                      <el-input v-model="datas.queryParams.facilitiesName" placeholder="请输入设施名称" clearable
                        @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="设施标题" prop="facilitiesTitle">
                      <el-input v-model="datas.queryParams.facilitiesTitle" placeholder="请输入设施标题" clearable
                        @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="Search" @click="handleQueryFac">搜索</el-button>
                      <el-button icon="Refresh" @click="resetQueryFac">重置</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </transition>

              <el-table v-loading="loading" :data="facilitiesList" @selection-change="handleSelectionChangeFac">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="设施id" align="center" prop="facilitiesId" v-if="true" />
                <el-table-column label="设施名称" align="center" prop="facilitiesName" />
                <el-table-column label="设施标题" align="center" prop="facilitiesTitle" />

                <el-table-column label="主图展示" align="center" prop="url">
                  <template #default="scope">
                    <ImagePreview :width="100" :height="100" :src="scope.row.url" :preview-src-list="[scope.row.url]" />
                  </template>
                </el-table-column>

                <el-table-column label="设施描述" align="center" prop="facilitiesDesc" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-tooltip content="修改" placement="top">
                      <el-button link type="primary" icon="Edit" @click="handleUpdateFac(scope.row)"
                        v-hasPermi="['system:facilities:edit']"></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
              <pagination v-show="facTotal > 0" :total="facTotal" v-model:page="datas.queryParams.pageNum"
                v-model:limit="datas.queryParams.pageSize" @pagination="onClickOpen" />
            </el-dialog>
          </el-form>
        </div>


        <!--区域设施展示列表-->
        <el-table v-loading="loading" :data="facItem" v-show="showTable">
          <el-table-column label="设施id" align="center" prop="facilitiesId" v-if="false" />
          <el-table-column label="设施名称" align="center" prop="facilitiesName" />
          <el-table-column label="设施标题" align="center" prop="facilitiesTitle" />

          <el-table-column label="主图展示" align="center" prop="url">
            <template #default="scope">
              <!-- <ImagePreview :width="100" :height="100" :src="scope.row.url" :preview-src-list="[scope.row.url]" /> -->
              <div v-if="scope.row.sysimg.find((item:any) => item.enumC === '0')">
                <div v-for="item in scope.row.sysimg" >
                  <ImagePreview :width="100" :height="100" :src="item.url" v-if="item.enumC === '0'" />
                </div>
              </div>
              <div v-else>
                <ImagePreview :width="100" :height="100" :src="''" />
              </div>
            </template>
          </el-table-column>

          <el-table-column label="设施描述" align="center" prop="facilitiesDesc" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdateFac(scope.row)"
                  v-hasPermi="['system:facilities:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDeleteFac(scope.row)"
                  v-hasPermi="['system:facilities:remove']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>


        <!--详情弹框列表-->
        <el-dialog :title="dialogs.title" v-model="dialogs.visible" width="600px" append-to-body>
          <el-form ref="facilitiesFormRef" :model="datas.form" :rules="datas.rules" label-width="80px">
            <el-form-item label="设施名称" prop="facilitiesName">
              <el-input v-model="datas.form.facilitiesName" placeholder="请输入设施名称" readonly="true" />
            </el-form-item>
            <el-form-item label="设施标题" prop="facilitiesTitle">
              <el-input v-model="datas.form.facilitiesTitle" placeholder="请输入设施标题" readonly="true" />
            </el-form-item>
            <el-form-item label="设施类型" prop="facilitiesType">
              <el-select v-model="datas.form.facilitiesType" placeholder="设施类型" clearable style="width:500px">
                <el-option v-for="dict in facilities_type" :label="dict.label" :value="dict.value" :key="dict.value"
                  disabled />
              </el-select>
            </el-form-item>
            <el-form-item label="设施描述" prop="facilitiesDesc">
              <el-input v-model="datas.form.facilitiesDesc" maxlength="200" placeholder="请输入设施描述" show-word-limit
                type="textarea" readonly="true" />
            </el-form-item>

            <el-upload v-model:file-list="facImgList" :multiple="true" :action="upload.url" :on-preview="handlePreview"
              :on-remove="handleRemove" :before-remove="beforeRemove" :headers="upload.headers"
              :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload" list-type="picture-card"
              :disabled="true">
              上传区域图
              <template #tip>
                <div class="el-upload__tip">
                  jpg/png files with a size less than 500KB.
                </div>
              </template>
              <template #file="{ file }">
                <div>
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                  <span class="el-upload-list__item-actions">
                  </span>
                </div>
              </template>
            </el-upload>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="cancelFac">取 消</el-button>
            </div>
          </template>
        </el-dialog>


      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Region" lang="ts">
import { listRegion, getRegion, delRegion, addRegion, updateRegion } from '@/api/system/region';
import { RegionVO, RegionQuery, RegionForm } from '@/api/system/region/types';
import { globalHeaders } from "@/utils/request";
import type { UploadProps } from 'element-plus'
import { propTypes } from '@/utils/propTypes';
import { FacilitiesVO, FacilitiesQuery, FacilitiesForm } from '@/api/system/facilities/types';
import { getFacilities, listFacilities } from '@/api/system/facilities';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { facilities_type } = toRefs<any>(proxy?.useDict("facilities_type"));
const { region_type } = toRefs<any>(proxy?.useDict("region_type"));
const { facilities_data } = toRefs<any>(proxy?.useDict("facilities_data"));
const facilitiesList = ref<FacilitiesVO[]>([]);
const iframeUrl = ref(import.meta.env.VITE_APP_BASE_API + '/system/region/list?pageNum=1&pageSize=10');
const upload = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload',
});
const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: propTypes.number.def(5),
  // 大小限制(MB)
  fileSize: propTypes.number.def(5),
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: propTypes.array.def(["png", "jpg", "jpeg"]),
  // 是否显示提示
  isShowTip: propTypes.bool.def(true),
});
const dialogs = reactive<DialogOption>({
  visible: false,
  title: ''
});
const number = ref(0);
const regionList = ref<RegionVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const facTotal = ref(0);
const fileList = ref<any[]>([]);
const facImgList = ref<any[]>([]);
const disabled = ref(false)
const emit = defineEmits(['update:modelValue']);
const queryFormRef = ref<ElFormInstance>();
const queryFormRefFac = ref<ElFormInstance>();
const regionFormRef = ref<ElFormInstance>();
const dialogVisible = ref(false);
const facItem = ref<any[]>([]);
const facItemP = ref<any[]>([]);
let showTable = ref(false);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const onClickDefaultPhoto = (file: any) => {
  
  if (file.defaults) {
    file.defaults = false;
    file.enumC = '1'; //主图标识
  } else {
    file.defaults = true;
    file.enumC = '0'; //主图标识
    fileList.value.forEach(item => {
      if (item.uid !== file.uid) {
        item.defaults = false;
        item.enumC = '1'; //主图标识
      }
    })
  }
}

const onClickDeletePhoto = (file: any) => {
  const index = fileList.value.findIndex((item) => {
    return item.uid === file.uid;
  })
  fileList.value.splice(index, 1);
  emit("update:modelValue", listToString(fileList.value));
}
const initFormDatas: FacilitiesForm = {

}
const datas = reactive<PageData<FacilitiesForm, FacilitiesQuery>>({
  form: {
    facilitiesId: undefined,
    facilitiesName: undefined,
    facilitiesTitle: undefined,
    facilitiesDesc: undefined,
    facilitiesType: undefined,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    facilitiesName: undefined,
    facilitiesTitle: undefined,
    facilitiesDesc: undefined,
    facilitiesType: undefined,
    params: {
    }
  },
  rules: {
    facilitiesId: [
      { required: true, message: "设施id不能为空", trigger: "blur" }
    ],
    facilitiesName: [
      { required: true, message: "设施名称不能为空", trigger: "blur" }
    ],
    facilitiesTitle: [
      { required: true, message: "设施标题不能为空", trigger: "blur" }
    ],
    facilitiesDesc: [
      { required: true, message: "设施描述不能为空", trigger: "blur" }
    ],
  }
});
const initFormData: RegionForm = {
  regionId: undefined,
  regionName: undefined,
  regionTitle: undefined,
  regionDesc: undefined,
  regionType: undefined,
  regionFacilities: undefined,
  sysimg: undefined,
}
const data = reactive<PageData<RegionForm, RegionQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    regionName: undefined,
    regionTitle: undefined,
    regionDesc: undefined,
    regionType: undefined,
    regionFacilities: undefined,
    sysimg: undefined,
    params: {
    }
  },
  rules: {
    regionId: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    regionName: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    regionTitle: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    regionDesc: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
  }
});

// 文件个数超出
// const handleExceed = () => {
//   proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
// }

// 上传失败
const handleUploadError = () => {
  proxy?.$modal.msgError("上传文件失败");
}

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}

// 上传前校检格式和大小
const handleBeforeUpload = (file: any) => {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy?.$modal.loading("正在上传文件，请稍候...");
  number.value++;
  return true;
}

const listImgInfo: any[] = [];
const handleUploadSuccess = (res: any) => {
  // 如果上传成功
  if (res.code === 200) {
    proxy?.$modal.closeLoading();
  } else {
    proxy?.$modal.loading(res.msg);
    proxy?.$modal.closeLoading();
  }
}

const { queryParams, form, rules } = toRefs(data);

/** 查询区域列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRegion(queryParams.value);
  regionList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  regionFormRef.value?.resetFields();
}

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  fileList.value = [];
  facItem.value = [];
  dialog.visible = true;
  dialog.title = "添加区域";
  showTable.value = false;
}

/** 修改按钮操作 */
const handleUpdate = async (row?: RegionVO) => {
  reset();
  const _regionId = row?.regionId || ids.value[0]
  const res = await getRegion(_regionId);
  fileList.value = [];
  facItem.value = [];
  res.data.sysimg.forEach((_s: any) => {
    const imgData = { fileName: _s.fileName, e: _s.enumC, url: _s.url, ossId: _s.ossId };
    fileList.value.push(imgData);
    console.info(fileList.value, 'fileList.value');
  })

  fileList.value.forEach(item => {
    if (item.e === '0') {
      item.defaults = true;
    }
  })

  if (res.data.regionFacilities.length > 0) {
    res.data.regionFacilities.forEach((_r: any) => {
      let imgData = {};
      _r.sysimg.forEach((_s: any) => {
        if (_s.enumC === '0') {
          imgData = {
            sysimg: _r.sysimg, facilitiesId: _r.facilitiesId, facilitiesName: _r.facilitiesName,
            facilitiesTitle: _r.facilitiesTitle, facilitiesDesc: _r.facilitiesDesc, url: _s.url
          }
          return;
        } else {
          imgData = {
            sysimg: _r.sysimg, facilitiesId: _r.facilitiesId, facilitiesName: _r.facilitiesName,
            facilitiesTitle: _r.facilitiesTitle, facilitiesDesc: _r.facilitiesDesc, url: null
          }
        }
      });
      facItem.value.push(imgData);
    })

    console.info(facItem.value, 'facItem');
    showTable.value = true;
  }

  Object.assign(form.value, res.data);
  console.info(res.data, 'res.data');
  dialog.visible = true;
  dialog.title = "修改区域";
}

/** 提交按钮 */
const submitForm = () => {
  regionFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      console.info(form.value, 'region data');
      data.form.sysimg = fileList.value;
      data.form.regionFacilities = facItem.value;
      if (form.value.regionId) {
        await updateRegion(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addRegion(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: RegionVO) => {
  const _regionIds = row?.regionId || ids.value;
  await proxy?.$modal.confirm('是否确认删除区域编号为"' + _regionIds + '"的数据项？').finally(() => loading.value = false);
  await delRegion(_regionIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/region/export', {
    ...queryParams.value
  }, `region_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
// 对象转成指定字符串分隔
const listToString = (list: any[], separator?: string) => {
  let strs = "";
  separator = separator || ",";
  list.forEach(item => {
    if (item.ossId) {
      strs += item.ossId + separator;
    }
  })
  return strs != "" ? strs.substring(0, strs.length - 1) : "";
}

const handleClose = (done: () => void) => {
  done();
}
const onClickOpen = async () => {
  datas.queryParams.facilitiesTitle = '';
  datas.queryParams.facilitiesName = '';
  dialogVisible.value = true;
  
  loading.value = true;
  const res = await listFacilities(datas.queryParams);
  facilitiesList.value = res.rows;
  facTotal.value = res.total;
  loading.value = false;
  datas.form = { ...initFormDatas };
}

/** 多选框选中区域数据 */
const handleSelectionChangeFac = (selection: FacilitiesVO[]) => {
  facItemP.value = [];
  facItemP.value = selection.map(items => {
    const item = {
      sysimg: items.sysimg, facilitiesId: items.facilitiesId, facilitiesName: items.facilitiesName,
      facilitiesTitle: items.facilitiesTitle, facilitiesDesc: items.facilitiesDesc, url: items.url, facilitiesType: items.facilitiesType
    };
    return item;
  });

  console.info(facItemP.value, 'facItemPsssssssssss');
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  showTable.value = true;
}

const handleAddFac = (row?: FacilitiesVO) => {
  console.info(facItemP.value, 'facItemP......');
  const unique = [...facItem.value, ...facItemP.value].reduce((acc, current) => {
    const x = acc.find((item: { facilitiesId: any; }) => item.facilitiesId === current.facilitiesId);
    if (!x) {
      return acc.concat([current]);
    } else {
      return acc;
    }
  }, []);

  console.info(unique, 'unique');

  facItem.value = [];
  unique.forEach((_i: any) => {
    facItem.value.push(_i);
  });
  console.info(facItem.value, 'sssssss');

  dialogVisible.value = false; //隐藏新增区域弹框
}

const handleUpdateFac = async (row?: FacilitiesVO) => {
  const _facilitiesId = row?.facilitiesId || ids.value[0]
  const res = await getFacilities(_facilitiesId);
  Object.assign(datas.form, res.data);
  dialogs.visible = true;
  facImgList.value = res.data.sysimg;
  dialog.title = "区域详情";
}

const handleDeleteFac = async (row?: FacilitiesVO) => {
  const _facilitiesId = row?.facilitiesId || ids.value;
  await proxy?.$modal.confirm('是否确认删除设施编号为"' + _facilitiesId + '"的数据项？').finally(() => loading.value = false);
  const index = facItem.value.findIndex((item) => item.facilitiesId === _facilitiesId);
  if (index !== -1) {
    facItem.value.splice(index, 1); //删除
  }
  console.info(facItem.value, 'facItem.value');
}

const handleQueryFac = async () => {
  datas.queryParams.pageNum = 1;
  getListFac();
}

const getListFac = async () => {
  loading.value = true;
  const res = await listFacilities(datas.queryParams);
  facilitiesList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}
const resetQueryFac = () => {
  // queryFormRefFac.value?.resetFields();
  datas.queryParams.facilitiesName = '';
  datas.queryParams.facilitiesTitle = '';
  handleQueryFac();
}
const cancelFac = () => {
  dialogs.visible = false;
}
</script>
