<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="roomName">
            <el-input v-model="queryParams.roomName" placeholder="请输入户型名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="户型标题" prop="roomTitle">
            <el-input v-model="queryParams.roomTitle" placeholder="请输入户型标题" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="户型描述" prop="roomDesc">
            <el-input v-model="queryParams.roomDesc" placeholder="请输入户型描述" clearable @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="热门户型" prop="isHot">
            <el-select v-model="queryParams.isHot" placeholder="热门户型" clearable>
              <el-option v-for="dict in hot_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="面积" prop="roomSize">
            <el-input v-model="queryParams.roomSize" placeholder="请输入面积" clearable @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="朝向" prop="direction">
            <el-input v-model="queryParams.direction" placeholder="请输入朝向" clearable @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="楼层" prop="floorNum">
            <el-input v-model="queryParams.floorNum" placeholder="请输入楼层" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <!--<el-form-item label="区域" prop="region">
            <el-select v-model="queryParams.region" placeholder="区域" clearable>
              <el-option v-for="dict in region_data" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </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:room:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['system:room:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['system:room:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['system:room:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="户型id" align="center" prop="roomId" v-if="true" width="200" />
        <el-table-column label="户型名称" align="center" prop="roomName" />
        <el-table-column label="户型标题" align="center" prop="roomTitle" />
        <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="roomDesc" />
        <el-table-column label="热门户型" align="center" prop="isHot" />
        <el-table-column label="面积" align="center" prop="roomSize" />
        <el-table-column label="朝向" align="center" prop="direction" />
        <el-table-column label="楼层" align="center" prop="floorNum" />
        <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:room:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:room: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="roomFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="户型名称" prop="roomName">
              <el-input v-model="form.roomName" placeholder="请输入户型名称" style="width: 400px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="户型标题" prop="roomTitle">
              <el-input v-model="form.roomTitle" placeholder="请输入户型标题" style="width: 400px;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="热门户型" prop="isHot">
              <el-checkbox true-label="1" false-label="0" v-model="form.isHot" label="热门" size="large" border />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="楼层" prop="floorNum">
              <el-input v-model.number="form.floorNum" placeholder="请输入楼层" type="number" style="width: 108px;" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="面积" prop="roomSize">
              <el-input v-model="form.roomSize" placeholder="请输入面积" type="number" style="width: 110px;" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="朝向" prop="direction">
              <el-input v-model="form.direction" placeholder="请输入朝向" style="width: 155px;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="户型描述" prop="roomDesc">
          <el-input v-model="form.roomDesc" maxlength="200" placeholder="请输入户型描述" show-word-limit type="textarea"
            rows="5" style="width: 800px;" />
        </el-form-item>

        <!-- <el-form-item label="区域" prop="region">
          <el-select v-model="form.region" multiple placeholder="区域" clearable style="width:500px">
            <el-option v-for="dict in region_data" :label="dict.label" :value="dict.value" :key="dict.value" />
          </el-select>
        </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="queryFormRefRegion" :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="handleAddRegion()"
                  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="queryFormRefRegion" :inline="true" label-width="68px">
                    <el-form-item label="区域名称" prop="regionName">
                      <el-input v-model="datas.queryParams.regionName" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="区域标题" prop="regionTitle">
                      <el-input v-model="datas.queryParams.regionTitle" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="Search" @click="handleQueryRegion">搜索</el-button>
                      <el-button icon="Refresh" @click="resetQueryRegion">重置</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </transition>

              <el-table v-loading="loading" :data="regionList" @selection-change="handleSelectionChangeRegion">
                <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="handleUpdateRegion(scope.row)"
                        v-hasPermi="['system:region:edit']"></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>

              <pagination v-show="regionTotal > 0" :total="regionTotal" 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="regionItem" v-show="showTable">
          
          <el-table-column label="区域id" align="center" prop="regionId" v-if="false" />
          <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">
               <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> 
            <!-- <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" class-name="small-padding fixed-width">

            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdateRegion(scope.row)"
                  v-hasPermi="['system:region:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDeleteRegion(scope.row)"
                  v-hasPermi="['system:region:remove']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <!--弹框区域详情-->
      <el-dialog :title="dialogs.title" v-model="dialogs.visible" width="600px" append-to-body>
        <el-form ref="regionFormRef" :model="datas.form" :rules="rules" label-width="80px">
          <el-form-item label="区域名称" prop="regionName">
            <el-input v-model="datas.form.regionName" placeholder="请输入" readonly="true" />
          </el-form-item>
          <el-form-item label="区域标题" prop="regionTitle">
            <el-input v-model="datas.form.regionTitle" placeholder="请输入" readonly="true" />
          </el-form-item>
          <el-form-item label="区域类型" prop="regionType">
            <el-select v-model="datas.form.regionType" placeholder="区域" clearable style="width:500px">
              <el-option v-for="dict in region_type" :label="dict.label" :value="dict.value" :key="dict.value"
                disabled />
            </el-select>
          </el-form-item>
          <el-form-item label="区域设施" prop="regionType">
            <el-select v-model="datas.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"
                disabled />
            </el-select>
          </el-form-item>

          <el-form-item label="区域描述" prop="regionDesc">
            <el-input v-model="datas.form.regionDesc" maxlength="200" placeholder="请输入区域描述" show-word-limit
              type="textarea" readonly="true" />
          </el-form-item>
          <el-upload v-model:file-list="regionImgList" :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 :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button> -->
            <el-button @click="cancelRegion">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <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="Room" lang="ts">
import { listByIds } from "@/api/system/oss";
import { listRoom, getRoom, delRoom, addRoom, updateRoom } from '@/api/system/room';
import { listRegion, getRegion, delRegion, addRegion, updateRegion } from '@/api/system/region';
import { RoomVO, RoomQuery, RoomForm } from '@/api/system/room/types';
import { ref } from 'vue'
import { ElMessageBox } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { globalHeaders } from "@/utils/request";
import { propTypes } from '@/utils/propTypes';
import { RegionVO, RegionQuery, RegionForm } from '@/api/system/region/types';


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 { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { region_data } = toRefs<any>(proxy?.useDict("region_data"));
const regionList = ref<RegionVO[]>([]);
const roomList = ref<RoomVO[]>([]);
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 regionTotal = ref(0);
const disabled = ref(false);
const dialogVisible = ref(false);
const iframeUrl = ref(import.meta.env.VITE_APP_BASE_API + '/system/region/list?pageNum=1&pageSize=10');
const { region_type } = toRefs<any>(proxy?.useDict("region_type"));
const { facilities_data } = toRefs<any>(proxy?.useDict("facilities_data"));
let showTable = ref(false);
const queryFormRef = ref<ElFormInstance>();
const queryFormRefRegion = ref<ElFormInstance>();
const roomFormRef = ref<ElFormInstance>();
const emit = defineEmits(['update:modelValue']);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialogs = reactive<DialogOption>({
  visible: false,
  title: ''
});

const regionItem = ref<any[]>([]);
const regionItemP = ref<any[]>([]);

const number = ref(0);
const fileList = ref<any[]>([]);
const regionImgList = ref<any[]>([]);


watch(() => props.modelValue, async val => {
  if (val) {
    let temp = 1;
    // 首先将值转为数组
    let list = [];
    if (Array.isArray(val)) {
      list = val;
    } else {
      console.info(val, 'listByIds');
      const res = await listByIds(val as string)
      list = res.data.map((oss) => {
        const data = { name: oss.originalName, url: oss.url, ossId: oss.ossId };
        return data;
      });
    }
    // 然后将数组转为对象数组
    fileList.value = list.map(item => {
      item = { fileName: item.fileName, url: item.url, ossId: item.ossId };
      item.uid = item.uid || new Date().getTime() + temp++;
      return item;
    });
  } else {
    fileList.value = [];
    return [];
  }
}, { deep: true, immediate: true });

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 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 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 handleUploadSuccess = (res: any) => {
  // 如果上传成功
  if (res.code === 200) {
    proxy?.$modal.closeLoading();
  } else {
    proxy?.$modal.loading(res.msg);
    proxy?.$modal.closeLoading();
  }
}

const initFormDatas: RegionForm = {
}
const datas = reactive<PageData<RegionForm, RegionQuery>>({
  form: {
    regionId: undefined,
    regionName: undefined,
    regionTitle: undefined,
    regionDesc: undefined,
    regionType: undefined,
    regionFacilities: undefined,
    sysimg: undefined,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    regionName: undefined,
    regionTitle: undefined,
    regionDesc: undefined,
    regionType: undefined,
    regionFacilities: undefined,
    sysimg: undefined,
    params: {
    }
  },
  rules: {

  }
});

const initFormData: RoomForm = {
}
const data = reactive<PageData<RoomForm, RoomQuery>>({
  form: {
    roomId: undefined,   // 户型id
    roomName: undefined, // 户型名称
    roomTitle: undefined,// 户型标题
    roomDesc: undefined, // 户型描述
    isHot: undefined,    // 是否热门户型
    roomSize: undefined, // 面积
    direction: undefined,// 朝向
    floorNum: undefined, // 楼层
    region: undefined,   // 区域
    sysimg: undefined,   // 图片
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roomName: undefined,
    roomTitle: undefined,
    roomDesc: undefined,
    isHot: undefined,
    roomSize: undefined,
    direction: undefined,
    floorNum: undefined,
    region: undefined,
    sysimg: undefined,   // 图片
    params: {
    },
    types: {
    }
  },

  rules: {
    roomId: [
      { required: true, message: "户型id不能为空", trigger: "blur" }
    ],
    roomName: [
      { required: true, message: "户型名称不能为空", trigger: "blur" }
    ],
    roomTitle: [
      { required: true, message: "户型标题不能为空", trigger: "blur" }
    ],
    roomDesc: [
      { required: true, message: "户型描述不能为空", trigger: "blur" }
    ],
    region: [
      { required: true, message: "区域不能为空", trigger: "blur" }
    ],
    roomSize: [
      { required: true, message: "面积不能为空", trigger: "blur" }
    ],
    direction: [
      { required: true, message: "朝向不能为空", trigger: "blur" }
    ],
    floorNum: [
      { required: true, message: "楼层不能为空", trigger: "blur" }
    ],
  }
});

const onClickOpen = async () => {
  datas.queryParams.regionName = '';
  datas.queryParams.regionTitle = '';
  dialogVisible.value = true;
  console.info(iframeUrl);
  loading.value = true;
  const res = await listRegion(datas.queryParams);
  regionList.value = res.rows;
  regionTotal.value = res.total;
  loading.value = false;
  datas.form = { ...initFormDatas };
}

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

/** 查询户型列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRoom(queryParams.value);
  roomList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

const handleQueryRegion = () => {
  queryParams.value.pageNum = 1;
  onClickOpen();
}
const resetQueryRegion = () => {
  queryFormRef.value?.resetFields();
  handleQueryRegion();
}

const handleClose = (done: () => void) => {
  done();
}

/** 多选框选中区域数据 */
const handleSelectionChangeRegion = (selection: RegionVO[]) => {
  regionItemP.value = [];
  regionItemP.value = selection.map(items => {
    const item = {
      sysimg: items.sysimg, regionId: items.regionId, regionName: items.regionName,
      regionTitle: items.regionTitle, regionDesc: items.regionDesc, url: items.url, regionType: items.regionType
    };
    return item;
  });
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  showTable.value = true;
}

const handleAddRegion = (row?: RegionVO) => {
  const unique = [...regionItem.value, ...regionItemP.value].reduce((acc, current) => {
    const x = acc.find((item: { regionId: any; }) => item.regionId === current.regionId);
    if (!x) {
      return acc.concat([current]);
    } else {
      return acc;
    }
  }, []);

  console.info(unique, 'unique');

  regionItem.value = [];
  unique.forEach((_i: any) => {
    regionItem.value.push(_i);
  });


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

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

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

/** 修改按钮操作 */
const handleUpdate = async (row?: RoomVO) => {
  reset();
  const _roomId = row?.roomId || ids.value[0]
  const res = await getRoom(_roomId);
  fileList.value = [];
  regionItem.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);
  })

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

  if (res.data.region.length > 0) {
    res.data.region.forEach((_r: any) => {
      let imgData = {};
      _r.sysimg.forEach((_s: any) => {
        if (_s.enumC === '0') {
          imgData = {
            sysimg: _r.sysimg, regionId: _r.regionId, regionName: _r.regionName,
            regionTitle: _r.regionTitle, regionDesc: _r.regionDesc, url: _s.url
          }
        } else {
          imgData = {
            sysimg: _r.sysimg, regionId: _r.regionId, regionName: _r.regionName,
            regionTitle: _r.regionTitle, regionDesc: _r.regionDesc, url: null
          }
        }
      });
      regionItem.value.push(imgData);
    })
    console.info(regionItem.value, 'regionItem.value');
    showTable.value = true;
  }

  console.info(fileList.value);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改户型";
}

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

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

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/room/export', {
    ...queryParams.value
  }, `room_${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 handleUpdateRegion = async (row?: RegionVO) => {
  const _regionId = row?.regionId || ids.value[0]
  const res = await getRegion(_regionId);
  Object.assign(datas.form, res.data);
  dialogs.visible = true;
  regionImgList.value = res.data.sysimg;
  dialog.title = "区域详情";
}
const cancelRegion = () => {
  reset();
  dialogs.visible = false;
}
const handleDeleteRegion = async (row?: RegionVO) => {
  const _regionIds = row?.regionId || ids.value;
  await proxy?.$modal.confirm('是否确认删除区域编号为"' + _regionIds + '"的数据项？').finally(() => loading.value = false);
  // regionItem.value.splice(index, 1);
  const index = regionItem.value.findIndex((item) => item.regionId === _regionIds);
  if (index !== -1) {
    regionItem.value.splice(index, 1); //删除
  }
}
</script>
