<template>
  <div class="content-box">
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <span class="cameratxt">房型管理</span>
    </div>
    <div class="scroll">
      <div class="middle">
        <div class="filter">
          <div class="condition">
            <el-input
              :clearable="true"
              @clear="searchBtn"
              v-model.trim="searchInput.keyWord"
              class="w-50 m-2"
              placeholder="请输入房号"
              style="width: 180px"
            />
          </div>
          <el-button
            color="rgba(0, 97, 255, 1)"
            type="primary"
            class="search"
            @click="searchBtn"
            ><el-icon>
              <Search />
            </el-icon>
            <span>查询</span></el-button
          >
          <div class="condition">
            <span>房间类型</span>
            <el-select
              :clearable="false"
              v-model="searchInput.type"
              @change="getList"
              class="m-2"
              placeholder="请选择房间类型"
              style="width: 120px"
            >
              <el-option label="全日房" :value="1" />
              <el-option label="钟点房" :value="2" />
            </el-select>
          </div>
          <!-- <div class="condition" style="margin-left: 50px">
            <span>房间名称</span>
            <el-select
              style="width: 180px"
              v-model="searchInput.name"
              class="m-2"
              placeholder="请选择房型"
              :clearable="true"
              @change="searchBtn"
            >
              <el-option
                :label="`${i.roomName}(${i.roomType == 1 ? '全' : '钟'})`"
                :value="i.id"
                v-for="i in houseTypeList"
              />
            </el-select>
          </div> -->
        </div>
        <!-- 按钮列表 -->
        <div class="gongneng" v-if="flagBtn.tianjia == 1">
          <el-button type="primary" color="rgba(0, 97, 255, 1)" @click="addlist"
            ><img
              src="@/assets/add.png"
              style="width: 14px; height: 14px; margin-right: 4px"
              alt=""
            /><span>添加房型</span></el-button
          >
        </div>
      </div>
      <div class="footer" v-loading="loading">
        <el-table
          :row-class-name="tableRowClassName"
          :data="tableData.list"
          @selection-change="handleSelectionChange"
          style="width: 100%"
          :header-cell-style="{
            background: 'rgba(240, 243, 247, 1)',
            height: '50px',
            border: 0,
          }"
        >
          <!-- <el-table-column align="center" type="selection" width="80" /> -->
          <el-table-column
            width="150"
            align="center "
            type="index"
            label="序号"
          />
          <el-table-column
            v-if="searchInput.type == 2"
            align="center"
            prop="time"
            label="钟点时长"
          />
          <el-table-column align="center" prop="name" label="房型名称">
            <template #default="{ row }">
              <span>{{ row.name }}</span
              ><span style="color: #1e7dfb"
                >({{ row.type == 1 ? "全" : "钟" }})</span
              >
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="roomId"
            label="房号"
            width="220"
          >
            <template #default="{ row }">
              <div class="ul" style="display: flex; flex-wrap: wrap">
                <el-tag
                  v-for="i in row.roomList"
                  style="margin: 5px"
                  type="primary"
                  >{{ i }}</el-tag
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="roomLength" label="数量" />
          <el-table-column align="center" prop="price" label="房费(元)" />
          <!-- <el-table-column align="center" prop="count" label="数量" /> -->
          <!-- <el-table-column align="center" prop="count" label="类型">
            <template #default="scope">
              <span v-if="scope.row.type == 1">全日房</span>
              <span v-if="scope.row.type == 2">钟点房</span>
            </template>
          </el-table-column> -->

          <el-table-column align="center" label="操作" width="150">
            <template #default="scope">
              <div class="edit">
                <div
                  class="look"
                  v-if="flagBtn.xiugai == 1"
                  @click="edit(scope.row)"
                >
                  编辑
                </div>
                <el-popconfirm
                  v-if="flagBtn.shanchu == 1"
                  width="220"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  :icon="InfoFilled"
                  icon-color="#f89626"
                  title="是否删除此房型?"
                  @confirm="del(scope.row)"
                  @cancel="cancelEvent"
                >
                  <template #reference>
                    <div class="del">删除</div>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pageSize">
          <span></span>
          <el-pagination
            background
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next, jumper, slot"
            :total="total"
            @update:current-page="handleCurrentChange"
          />
        </div>
        <!-- 添加房型弹窗 -->
        <el-dialog
          class="addStaff"
          v-model="addDialogVisible"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :title="dialongTitle"
          align-center
          width="900"
          :before-close="cancelAdd"
        >
          <div class="slider">
            <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              :rules="rules"
              label-width="100px"
              class="demo-ruleForm"
              size="default"
              label-position="left"
              status-icon
              :inline="true"
            >
              <div class="titles"><span>房型信息</span></div>
              <div class="form_item tag">
                <div class="items">
                  <!-- prop="fileListJson" -->
                  <el-form-item label="房间图片 :" prop="roomPicture">
                    <div class="tooltips" v-loading="imgShow">
                      <div class="img img1">
                        <div class="updateImg">
                          <div class="imglist" v-if="fileList.list.length">
                            <div
                              class="imgItem"
                              v-for="i in fileList.list"
                              :key="i.id"
                            >
                              <img :src="i.url" alt="" />
                              <div class="lookImg">
                                <img
                                  src="@/assets/lookImg.png"
                                  alt=""
                                  @click="lookImg(i)"
                                />
                                <div
                                  class="delimg"
                                  @click="handleRemove(i)"
                                ></div>
                              </div>
                            </div>
                          </div>
                          <div class="imglist" v-else>
                            <img src="#" alt="" />
                          </div>

                          <el-upload
                            class="avatar-uploader"
                            action=""
                            list-type="picture"
                            :on-preview="handlePreview"
                            :on-change="handleChange"
                            :http-request="handleUpload"
                            :before-upload="beforeAvatarUpload"
                          >
                            <template #trigger>
                              <el-button
                                type="primary"
                                color="rgba(0, 97, 255, 1)"
                                @click="updateImg"
                                >上传图片</el-button
                              >
                              <span class="zhu"
                                >（注：最多可上传6张图片，建议按16:9的比例）</span
                              >
                            </template>
                            <!-- <template #tip>
                                <div class="el-upload__tip">
                                  （注：图片大小不超过10M，建议按3:2比例）
                                </div>
                              </template> -->
                          </el-upload>
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                </div>
              </div>
              <div class="form_item">
                <div class="items">
                  <el-form-item label="房型名称 :" prop="roomName">
                    <el-input
                      v-model.trim="ruleForm.roomName"
                      placeholder="请输入房型名称"
                      clearable
                    />
                    <!-- <el-select
                      v-model="ruleForm.hName"
                      class="m-2"
                      placeholder="请选择民宿类型"
                    >
                      <el-option
                        v-for="i in houseType"
                        :label="i.name"
                        :value="i.name"
                      />
                    </el-select> -->
                  </el-form-item>
                </div>
                <div class="items">
                  <el-form-item label="房费 :" prop="roomPrice">
                    <el-input
                      v-model.trim="ruleForm.roomPrice"
                      placeholder="请输入房费"
                      clearable
                    />
                  </el-form-item>
                </div>
              </div>
              <div class="form_item">
                <div class="items">
                  <el-form-item label="面积 :" prop="roomArea">
                    <el-input
                      v-model.trim="ruleForm.roomArea"
                      placeholder="请输入面积大小"
                      clearable
                    ></el-input>
                    &nbsp;&nbsp;㎡
                  </el-form-item>
                </div>
                <div class="items">
                  <el-form-item label="房间上架 :" prop="putaway">
                    <el-switch
                      v-model="ruleForm.putaway"
                      style="
                        --el-switch-on-color: #0f6aff;
                      "
                      :active-value="1"
                      :inactive-value="2"
                    />
                  </el-form-item>
                  <span style="color: #f81313;display:inline-block;transform: translateY(-7px)">开启则不在小程序上显示</span>
                </div>
              </div>
              <div class="form_item">
                <div class="roomUl">
                  <div
                    class="title"
                    style="line-height: normal; transform: translateX(10px)"
                  >
                    房间
                  </div>
                  <div class="delRoom">
                    <div class="ul">
                      <div class="li" v-for="i in ruleForm.roomNumbers">
                        <el-tag
                          size="large"
                          style="margin: 0 15px 8px 0"
                          type="primary"
                          >{{ i }}</el-tag
                        >
                      </div>
                    </div>
                  </div>
                </div>
                <!-- <el-form-item label="房间号 :" prop="roomNumbers">
                  <el-tree-select
                    v-model="roomSelNumList"
                    :data="roomNumList"
                    multiple
                    :render-after-expand="false"
                    show-checkbox
                    style="width: 240px"
                    :props="defaultProps"
                    node-key="id"
                  />
                </el-form-item> -->
              </div>
              <div class="form_item">
                <div class="items">
                  <el-form-item label="类型 :" prop="roomType">
                    <el-select
                      v-model="ruleForm.roomType"
                      class="m-2"
                      placeholder="请选择类型"
                      style="width: 200px"
                    >
                      <el-option label="全日房" value="1" />
                      <el-option label="钟点房" value="2" />
                    </el-select>
                  </el-form-item>
                </div>
              </div>
              <div class="form_item" v-if="ruleForm.roomType == 2">
                <div class="items">
                  <el-form-item label="钟点时长 :" prop="roomLiveTime">
                    <el-select
                      v-model="ruleForm.roomLiveTime"
                      class="m-2"
                      placeholder="请选择类型"
                      style="width: 200px"
                    >
                      <el-option label="1小时" value="1" />
                      <el-option label="2小时" value="2" />
                      <el-option label="3小时" value="3" />
                      <el-option label="4小时" value="4" />
                    </el-select>
                  </el-form-item>
                </div>
                <!-- <div class="items">
                  <el-form-item label="使用时间 :" prop="receivingTime">
                    <el-time-picker
                      v-model="ruleForm.receivingTime"
                      is-range
                      range-separator="-"
                      format="HH:ss"
                      value-format="HH:ss"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      style="width: 200px"
                    />
                  </el-form-item>
                </div> -->
              </div>
              <div class="titles">
                <span>房型配置</span
                ><span>（最多可选择5个描述展示，管理端房型配置管理）</span>
              </div>
              <div class="form_item">
                <div class="items">
                  <el-form-item label="选择配置 :" prop="roomConfig">
                    <!-- <el-checkbox-group
                      @change="checkHouse"
                      v-model="ruleForm.roomConfig"
                      :max="5"
                    >
                      <el-checkbox
                        v-for="city in cities"
                        :key="city.id"
                        :label="city.id"
                        >{{ city.name }}</el-checkbox
                      >
                    </el-checkbox-group> -->
                    <el-checkbox-group
                      @change="checkHouse"
                      v-model="ruleForm.roomConfig"
                      :max="5"
                    >
                      <el-checkbox
                        v-for="i in roomConfig"
                        :label="i.houseService"
                        >{{ i.houseService }}</el-checkbox
                      >
                      <!-- <el-checkbox label="电视">电视</el-checkbox>
                      <el-checkbox label="双人床">双人床</el-checkbox>
                      <el-checkbox label="浴室">浴室</el-checkbox>
                      <el-checkbox label="投影机">投影机</el-checkbox> -->
                    </el-checkbox-group>
                  </el-form-item>
                </div>
              </div>
              <el-form-item class="options">
                <el-button
                  color="rgba(41, 109, 227, 1)"
                  class="queding"
                  type="primary"
                  @click="submitAdd(ruleFormRef)"
                >
                  确认
                </el-button>
                <el-button type="primary" plain @click="cancelAdd(ruleFormRef)"
                  >取消</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </el-dialog>
      </div>
    </div>
    <div class="bgImg" v-if="bgImg">
      <el-carousel
        @click="bgImg = false"
        ref="bgImgs"
        indicator-position
        arrow="always"
        :autoplay="false"
        trigger
      >
        <el-carousel-item v-for="item in bgImgList" :key="item.id">
          <img :src="item.url" alt="" />
        </el-carousel-item>
      </el-carousel>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  watch,
  nextTick,
  onBeforeMount,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Calendar } from "@element-plus/icons-vue";
import vidiconsApi from "@/api/vidicons.js";
import { dayjs } from "element-plus";
import lodash from "lodash";
import axios from "axios";
import { useStore } from "vuex";
const store = useStore();
const api = ref("");
const router = useRouter();

const flagBtn = ref(); // 按钮权限
// 表格数据
const loading = ref(false);
const tableData = reactive({
  list: [],
});

// 添加员工弹窗数据 (------------------------------------)
const dialongTitle = ref("添加房型"); // 弹窗标题
const cities = ref([
  "会议室",
  "订车场",
  "免费WIFI",
  "储物柜",
  "无早餐",
  "无停车场",
]); // 名宿配置数据

const houseTypeList = ref(); // 房型选择

const searchInput = reactive({
  keyWord: "",
  type: 1,
}); // 搜索按钮数据

// 查看图片按钮
const bgImg = ref(false);
const bgImgList = ref();

const currentPage = ref(1); // 当前页
const pageSize = ref(10);
const total = ref(); // 当前总数
const selectData = reactive({ list: [] }); // 多选框选择的数据

const addDialogVisible = ref(false); // 控制添加员工弹窗

// 添加员工表单数据
const ruleFormRef = ref();
const ruleForm = reactive({
  roomName: "", // 房型名称
  roomArea: "", //房型面积
  roomPrice: "", //单价
  number: "", //数量
  putaway: "", //房间上架
  visible: "", // 可见范围
  roomType: "", // 类型
  roomLiveTime: "", // 钟点时长
  receivingTime: "", // 使用时间
  roomConfig: "", //房型配置
  roomNumbers: [], // 房间号列表
  roomPicture: [], // 房间图片
  id: "",
});
const roomNumList = ref(); // 房间号列表数据
const roomSelNumList = ref(); // 房间号列表数据选择
const defaultProps = {
  children: "vos",
  label: "roomNumber",
  value: "id",
  // checkStrictly: true,
};

const imgShow = ref(false);
const fileList = reactive({ list: [] }); // 添加多张图片的文件
const roomConfig = ref([]); //房型配置

// 房费验证
const validatePrice = (rule, value, callback) => {
  if (/^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/.test(value)) {
    callback();
  } else {
    callback(new Error("最多包含两位小数的正数"));
  }
};
// 房费验证
const area = (rule, value, callback) => {
  if (/^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,4})?$/.test(value)) {
    callback();
  } else {
    callback(new Error("最多包含四位小数的正数"));
  }
};
// 房间数量验证
const validateNumber = (rule, value, callback) => {
  console.log(value, "房间数量");
  if (/^\+?[1-9]\d*$/.test(value)) {
    callback();
  } else {
    callback(new Error("房间数量最大不能超过三位数"));
  }
};
// 表单验证
const rules = reactive({
  roomPicture: [
    { required: true, message: "民宿图片不能为空", trigger: "blur" },
  ],
  roomName: [{ required: true, message: "房型名称不能为空", trigger: "blur" }],
  roomPrice: [
    { required: true, message: "房费不能为空", trigger: "blur" },
    // { validator: validatePrice, trigger: "blur" },
  ],
  number: [
    { required: true, message: "数量不能为空", trigger: "blur" },
    { validator: validateNumber, trigger: "blur" },
    // {
    //   pattern: /^\+?[1-9]\d*$/,
    //   message: "请输入大于0的正整数",
    //   trigger: "blur",
    // },
  ],
  putaway: [{ required: true, message: "房间上架", trigger: "blur" }],
  visible: [{ required: true, message: "请选择可见范围", trigger: "blur" }],
  roomType: [{ required: true, message: "类型不能为空", trigger: "blur" }],
  roomNumbers: [{ required: true, message: "房间号不能为空", trigger: "blur" }],
  roomLiveTime: [
    { required: true, message: "钟点时长不能为空", trigger: "blur" },
  ],
  receivingTime: [
    { required: true, message: "使用时间不能为空", trigger: "blur" },
  ],
  roomArea: [
    { required: true, message: "房型面积不能为空", trigger: "blur" },
    { validator: area, trigger: "blur" },
  ],
  roomConfig: [
    { required: true, message: "房型配置不能为空", trigger: "blur" },
  ],
});

// 查看房型列表
const getList = async () => {
  loading.value = true;
  let data = {
    page: currentPage.value,
    size: pageSize.value,
    keyWord: searchInput.keyWord, // 房型名称
    type: searchInput.type,
  };
  let res = await axios({
    method: "get",
    url: api.value + "/house/list",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("user_head"),
    },
    params: data,
  });
  console.log(res, "房型管理");
  if (res.data.code == 200) {
    loading.value = false;
    // res.data.data.list.forEach((item) => {
    //   let arr = [];
    //   item.visible.split(",").forEach((i) => {
    //     if (i == 0) {
    //       arr.push("全部");
    //     } else if (i == 1) {
    //       arr.push("学生");
    //     } else if (i == 2) {
    //       arr.push("教职工");
    //     } else if (i == 3) {
    //       arr.push("校友");
    //     } else if (i == 4) {
    //       arr.push("访客");
    //     } else if (i == 5) {
    //       arr.push("临时人员");
    //     } else if (i == 6) {
    //       arr.push("其他");
    //     } else if (i == 7) {
    //       arr.push("领导");
    //     }
    //   });
    //   item.visibleName = arr.join(",");
    // });
    res.data.data.list.forEach((i) => {
      if (i.roomId) {
        let arr = i.roomId.split(",");
        i.roomList = arr;
        i.roomLength = arr.length;
      }
    });
    tableData.list = res.data.data.list;
    total.value = res.data.data.totalCount;
  } else {
    loading.value = false;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};
const systemList = async () => {
  let data = {
    permissionSettingId: sessionStorage.getItem("permissionSettingId"),
  };
  let res = await axios({
    method: "get",
    url: api.value + "/facility-services/list",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("user_head"),
    },
    params: data,
  });
  console.log(res, "房型配置");
  if (res.data.code == 200) {
    roomConfig.value = res.data.data;
  } else {
    loading.value = false;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};
// 房型列表数据
const roomTypeList = async () => {
  let res = await axios({
    method: "get",
    url: api.value + "/house/displayBar",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("user_head"),
    },
  });
  console.log(res, "房型列表数据");
  if (res.data.code == 200) {
    houseTypeList.value = res.data.data;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};
// 房间号列表数据
const roomNumberList = async () => {
  let res = await axios({
    method: "get",
    url: api.value + "/house-number/houseNumberPullDown",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("user_head"),
    },
  });
  console.log(res, "房间号列表数据");
  if (res.data.code == 200) {
    roomNumList.value = res.data.data;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  getList();
}, 300);
// 移出照片
const handleRemove = (uploadFile, uploadFiles) => {
  // console.log(uploadFile.uid, uploadFiles);
  fileList.list = fileList.list.filter((item) => {
    return item.uid != uploadFile.uid;
  });
  ruleForm.roomPicture = fileList.list;
};
// 点击图片的查看按钮
const handlePreview = (file) => {
  imgUrl.value = file.url;
  imgVisible.value = true;
  // console.log(file);
};
// 限制上传图片的大小
const beforeAvatarUpload = (rawFile) => {
  console.log(rawFile.type);
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("图片格式必须为JPG/PNG格式!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.erroapi.valuer("图片的大小不能超过10MB!");
    return false;
  }
  return true;
};
// 添加照片时往fileList列表中添加图片信息
const handleChange = async (file, fileLists) => {
  console.log(file, "1111");
  // fileList.list.push(file);
};
// 可以获取图片参数
const handleUpload = async (file) => {
  if (fileList.list.length >= 6) {
    ElMessage.warning("最多可上传6张图片!");
    return false;
  }
  imgShow.value = true;
  console.log(file, "2222");
  let data = new FormData();
  data.set("file", file.file);
  let res = await axios({
    method: "post",
    url: api.value + "/upload/save",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("user_head"),
    },
    data: data,
  });
  console.log(res, "图片上传成功");
  if (res.data.code == 200) {
    // res.data.uid = file.file.uid;
    fileList.list.push({ url: res.data.data.url, uid: file.file.uid });
    ruleForm.roomPicture = fileList.list;
    console.log(fileList.list);
    imgShow.value = false;
  } else {
    imgShow.value = false;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

//添加房型 （--------------------------------------）
const addlist = async () => {
  dialongTitle.value = "添加房型";
  addDialogVisible.value = true;
  systemList();
  ruleForm.roomPicture = []; // 房间图片
  fileList.list = []; // 将选中的图片文件置为空
  ruleForm.roomName = ""; // 房型名称
  ruleForm.roomArea = ""; //房型面积
  ruleForm.roomPrice = ""; //单价
  ruleForm.number = ""; //数量
  ruleForm.putaway = 2; //数量
  ruleForm.roomType = ""; // 类型
  ruleForm.visible = ""; // 可见范围
  ruleForm.roomConfig = []; //房型配置
  ruleForm.id = ""; // id
  ruleForm.roomNumbers = []; // 房间号列表
  ruleForm.roomLiveTime = ""; // 钟点时长
  ruleForm.receivingTime = ""; // 使用时间
};

//编辑按钮  （-------------------------------------------）
const edit = async (row) => {
  console.log(row, "编辑房型");
  dialongTitle.value = "编辑房型";
  ruleForm.id = row.id;
  ruleForm.putaway = row.isAdded;
  if (row.roomId) {
    ruleForm.roomNumbers = row.roomId.split(",");
  }
  let data = {
    houseId: row.id,
  };
  let res = await axios({
    method: "get",
    url: api.value + "/house/details",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("user_head"),
    },
    params: data,
  });
  console.log(res, "编辑详情");
  if (res.data.code == 200) {
    addDialogVisible.value = true;
    ruleForm.roomName = res.data.data.roomName;
    ruleForm.roomArea = res.data.data.roomArea;
    ruleForm.roomPrice = res.data.data.roomPrice;
    ruleForm.number = res.data.data.number;
    // ruleForm.visible = res.data.data.visible.split(",");
    ruleForm.roomType = String(res.data.data.roomType);
    ruleForm.roomLiveTime = res.data.data.roomLiveTime;
    if (res.data.data.receivingTime) {
      ruleForm.receivingTime = res.data.data.receivingTime.split("-");
    } else {
      ruleForm.receivingTime = "";
    }
    systemList().then(() => {
      console.log(res.data.data.roomConfiguration);
      if (res.data.data.roomConfiguration) {
        ruleForm.roomConfig = res.data.data.roomConfiguration.split(",");
      } else {
        ruleForm.roomConfig = [];
      }
    });
    let imgArr = [];
    if (res.data.data.housePicture) {
      res.data.data.housePicture.split(",").forEach((i, ind) => {
        imgArr.push({
          url: i,
          uid: ind,
        });
      });
      ruleForm.roomPicture = imgArr;
      fileList.list = imgArr;
    } else {
      ruleForm.roomPicture = imgArr;
      fileList.list = imgArr;
    }

    // let arr = [];
    // res.data.data.roomIds.split(",").forEach((item, ind) => {
    //   arr.push({
    //     numberName: item,
    //     id: ind,
    //   });
    // });
    // ruleForm.roomNumbers = arr;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
  // dialongTitle.value = "编辑房型";
  // addDialogVisible.value = true;
  // ruleForm.hName = row.hName; // 房型名称
  // ruleForm.hAreas = row.hAreas; //房型面积
  // ruleForm.price = row.price; //单价
  // ruleForm.number = row.number; //数量
  //   return Number(item);
  // });
  // ruleForm.hConfig = row.hConfig; //房型配置
  // ruleForm.houseNumbers = row.houseNumbers; // 房间号列表
  // ruleForm.id = row.id; //id
};
// 取消添加房型
const cancelAdd = () => {
  addDialogVisible.value = false;
  ruleFormRef.value.resetFields();
  ruleForm.roomName = "";
  ruleForm.roomArea = "";
  ruleForm.roomPrice = "";
  ruleForm.number = "";
  ruleForm.visible = "";
  ruleForm.roomType = "";
  ruleForm.roomLiveTime = "";
  ruleForm.receivingTime = "";
  ruleForm.roomConfig = "";
  // roomConfig.value = '';
  ruleForm.roomNumbers = [];
  ruleForm.roomPicture = [];
  fileList.list = [];
};
// 选择房型配置
const checkHouse = (val) => {
  console.log(val);
  // ruleForm.roomConfig = val
  ruleForm.roomConfig = val;
  // console.log(ruleForm.roomConfig);
};

// 监听房间数量
// watch(
//   () => ruleForm.number,
//   (newVal, oldVal) => {
//     console.log(newVal, "监听房间数量");
//     if (ruleForm.number <= 999) {
//       let arr = [];
//       if (newVal > 0) {
//         for (let i = 0; i < newVal; i++) {
//           arr[i] = {
//             numberName: "",
//             id: Math.random()
//               .toString(36)
//               .substr(3, i + 1),
//           };
//         }
//       }
//       arr.forEach((item, index) => {
//         ruleForm.roomNumbers.forEach((i, ind) => {
//           if (index == ind) {
//             item.numberName = i.numberName;
//             item.id = i.id;
//           }
//         });
//       });
//       ruleForm.roomNumbers = arr;
//       console.log(arr, "根据数量添加空房间");
//     } else {
//       ElMessage({
//         type: "warning",
//         showClose: true,
//         message: "房间数量最大为三位数",
//         center: true,
//       });
//       console.log(newVal.slice(0, 3));
//       ruleForm.number = newVal.slice(0, 3);
//     }
//   }
// );

// 新增房间号
const addRoom = () => {
  console.log(ruleForm.roomNumbers);
  let arr = {
    numberName: "",
    id: Math.random().toString(36).substr(3, 6),
  };
  ruleForm.roomNumbers.push(arr);
  if (ruleForm.roomNumbers.length > 0) {
    ruleForm.number = ruleForm.roomNumbers.length;
  }
  // console.log(ruleForm.roomNumbers.length, "房间数量");
};
// 删除房间号
const delRoom = (i) => {
  ruleForm.roomNumbers = ruleForm.roomNumbers.filter((item) => {
    return i.id != item.id;
  });
  if (ruleForm.roomNumbers.length > 0) {
    ruleForm.number = ruleForm.roomNumbers.length;
  } else {
    ruleForm.number = "";
  }
  // console.log(ruleForm.roomNumbers.length, "房间数量");
};

// 确认添加房型
const submitAdd = lodash.debounce(async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialongTitle.value == "添加房型") {
        // const arr = [];
        // let flag = ruleForm.roomNumbers.some((i) => {
        //   return i.numberName == "";
        // });
        // if (flag) {
        //   ElMessage({
        //     type: "warning",
        //     showClose: true,
        //     message: "房间号不能为空",
        //     center: true,
        //   });
        //   return false;
        // }
        // ruleForm.roomNumbers.forEach((item) => {
        //   arr.push(item.numberName);
        //   console.log(item);
        // });
        const imgArr = [];
        ruleForm.roomPicture.forEach((i) => {
          imgArr.push(i.url);
        });
        console.log(ruleForm.roomPicture, "图片列表");
        console.log(imgArr, "图片列表");

        let data = {
          // roomNumbers: arr, //房间号
          house: {
            roomName: ruleForm.roomName, //房间名字
            roomType: ruleForm.roomType, //1:全日房，2：钟点房
            roomPrice: ruleForm.roomPrice,
            // number: ruleForm.number,
            roomArea: ruleForm.roomArea,
            roomLiveTime: ruleForm.roomLiveTime,
            // receivingTime: `${ruleForm.receivingTime[0]}-${ruleForm.receivingTime[1]}`,
            // visible: ruleForm.visible.join(","), //可见类型（0：全部，1:学生，2：教职工，3：校友，4：访客，5：临时人员，6：其他，7：领导）
            roomConfiguration: ruleForm.roomConfig.join(","),
            roomPicture: imgArr[0], // 房型首页图
            housePicture: imgArr.join(","), //房型图,多张用逗号隔开
            isAdded: ruleForm.putaway, //是否上架  1：上架 ，2：下架
          },
          adminId: sessionStorage.getItem("permissionSettingId"),
        };
        console.log(data, "添加房型参数");

        let res = await axios({
          method: "post",
          url: api.value + "/house/save",
          headers: {
            token: sessionStorage.getItem("token"),
            user_head: sessionStorage.getItem("user_head"),
          },
          data: data,
        });
        console.log(res, "添加房型");
        if (res.data.code == 200) {
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      } else {
        // const arr = [];
        // let flag = ruleForm.roomNumbers.some((i) => {
        //   return i.numberName == "";
        // });
        // if (flag) {
        //   ElMessage({
        //     type: "warning",
        //     showClose: true,
        //     message: "房间号不能为空",
        //     center: true,
        //   });
        //   return false;
        // }
        // ruleForm.roomNumbers.forEach((item) => {
        //   arr.push(item.numberName);
        //   console.log(item);
        // });

        const imgArr = [];
        ruleForm.roomPicture.forEach((i) => {
          imgArr.push(i.url);
        });
        console.log(ruleForm.roomPicture, "图片列表");
        console.log(imgArr, "图片列表");
        let data = {
          // roomNumbers: arr, //房间号
          house: {
            id: ruleForm.id,
            roomName: ruleForm.roomName, //房间名字
            roomType: ruleForm.roomType, //1:全日房，2：钟点房
            roomPrice: ruleForm.roomPrice,
            // number: ruleForm.number,
            roomArea: ruleForm.roomArea,
            roomLiveTime: ruleForm.roomLiveTime,
            // receivingTime: `${ruleForm.receivingTime[0]}-${ruleForm.receivingTime[1]}`,
            // visible: ruleForm.visible.join(","), //可见类型（0：全部，1:学生，2：教职工，3：校友，4：访客，5：临时人员，6：其他，7：领导）
            roomConfiguration: ruleForm.roomConfig.join(","),
            roomPicture: imgArr[0], // 房型首页图
            housePicture: imgArr.join(","), //房型图,多张用逗号隔开
            isAdded: ruleForm.putaway, //是否上架  1：上架 ，2：下架
          },
          adminId: sessionStorage.getItem("permissionSettingId"),
        };
        console.log(data, "添加房型参数");

        let res = await axios({
          method: "post",
          url: api.value + "/house/update",
          headers: {
            token: sessionStorage.getItem("token"),
            user_head: sessionStorage.getItem("user_head"),
          },
          data: data,
        });
        console.log(res, "修改房型");
        if (res.data.code == 200) {
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
}, 1000);

//删除按钮
const del = async (row) => {
  console.log(row);
  let data = {
    houseId: row.id,
    adminId: sessionStorage.getItem("permissionSettingId"),
  };
  let res = await axios({
    method: "get",
    url: api.value + "/house/delete",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("user_head"),
    },
    params: data,
  });
  if (res.data.code == 200) {
    if (tableData.list.length == 1 && currentPage.value != 1) {
      currentPage.value = currentPage.value - 1;
    }
    getList();
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
  // console.log(res);
};

// 多选框功能
const handleSelectionChange = (val) => {
  console.log(val);
  selectData.list = val;
};
//导出功能
// const importExcel = async () => {
//   if (searchInput.createTime == null) {
//     searchInput.createTime = "";
//   }
//   let data = new FormData();
//   data.set("car_number", searchInput.carnumber);
//   data.set("create_time", searchInput.createTime);
//   let res = await axios({
//     method: "post",
//     url: api.value + "/carBook/cinfotoExcel.action",
//     headers: {
//       token: sessionStorage.getItem("token"),
//     },
//     data: data,
//   });
//   // console.log(res, "导出账号");
//   if (res.data.code == 200) {
//     // const elt = document.createElement("a");
//     // elt.setAttribute(
//     //   "href",
//     //   "https://chtech.ncjti.edu.cn/carstop" + res.data.downurl
//     // );
//     // elt.setAttribute("download", "file.png");
//     // elt.style.display = "none";
//     // document.body.appendChild(elt);
//     // elt.click();
//     var downloadPath = "https://chtech.ncjti.edu.cn/carstop" + res.data.downurl;
//     console.log("获得地址数据:", downloadPath);
//     var downloadLink = document.createElement("a");
//     downloadLink.style.display = "none"; // 使其隐藏
//     downloadLink.href = downloadPath;
//     downloadLink.download = "";
//     downloadLink.click();
//     document.body.appendChild(downloadLink);
//     document.body.removeChild(downloadLink);
//     ElMessage({
//       type: "success",
//       showClose: true,
//       message: res.data.message,
//       center: true,
//     });
//   } else {
//     ElMessage({
//       type: "error",
//       showClose: true,
//       message: res.data.message,
//       center: true,
//     });
//   }
// };
// 表格斑马纹颜色修改
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return "even";
  } else if (rowIndex % 2 !== 0) {
    return "odd";
  }
  return "";
};
// 分页
const handleCurrentChange = (value) => {
  // console.log(value);
  currentPage.value = value;
  getList();
};
// 查看图片
const lookImg = (i) => {
  console.log(i);

  bgImg.value = true;
  let arr = [
    {
      url: i.url,
      id: i.uid,
    },
  ];
  bgImgList.value = arr;
};
onBeforeMount(async () => {
  api.value = store.state.user.api;
  const btnflag = JSON.parse(sessionStorage.getItem("btnflag"));
  flagBtn.value = btnflag.roomType;
  console.log(flagBtn.value, "按钮权限");
  getList();
  // roomTypeList();
  // roomNumberList();
});
onUnmounted(() => {
  // document.removeEventListener("keyup", Enters);
});
</script>

<style scoped lang="scss">
.content-box {
  width: calc(100% - 40px);
  height: calc(100% - 105px);
  margin: 20px auto;
  background-color: #fff;
  color: #fff;
  display: flex;
  flex-direction: column;
  box-shadow: 0px 3px 10px rgba(0, 97, 255, 0.2);

  .left {
    // width: calc(100wh - 40px);
    display: flex;
    align-items: center;
    height: 60px;
    margin: 0 30px;
    border-bottom: 1px solid #ccc;
    color: rgb(0, 0, 0);
    font-size: 18px;
    font-weight: 600;

    span {
      margin-right: 20px;
      cursor: pointer;
    }

    .is_active {
      color: rgba(111, 182, 184, 1);
    }
  }

  .middle {
    color: #000;

    // border-bottom: 1px solid rgb(231, 231, 231);
    .filter {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      padding: 10px 0 0 0;

      .search {
        color: #fff;
        margin: 0 30px 0 0;
      }

      .condition {
        display: flex;
        align-items: center;
        margin: 10px 30px 10px 0;

        :deep(.el-input .el-input__inner) {
          font-size: 14px;
        }

        span {
          margin: 0 10px 0 0;
        }
      }
    }

    .gongneng {
      padding: 10px 0 20px 0;

      span {
        color: #fff;
      }
    }

    :deep(.cont) {
      width: 60%;
      margin: 20px auto;
    }

    :deep(.download) {
      display: flex;
      align-items: center;
      margin: 10px;
    }

    :deep(.download span) {
      font-size: 16px;
      margin-left: 20px;
    }

    :deep(.cont .el-button) {
      margin-left: 60px;
      margin-bottom: 30px;
    }

    :deep(.cont .accomplish) {
      width: 100%;
      display: flex;
      justify-content: center;
    }

    :deep(.cont .accomplish .el-button) {
      width: 50%;
      margin: 0;
    }
  }
  .scroll {
    width: calc(100% - 60px);
    height: calc(100% - 61px);
    margin: 0 auto;
    overflow: auto;
    display: flex;
    flex-direction: column;
  }
  .footer {
    flex: 1;
    overflow: auto;
    .el-table--fit {
      height: calc(100% - 60px);

      :deep(.el-table__header-wrapper) {
        background-color: #000;
        font-size: 16px;

        tr {
          color: #000;
        }
      }

      :deep(.el-table__row) {
        height: 50px;
        font-size: 16px;
        color: #000;
      }

      :deep(.el-table__row):nth-child(2n) {
        .el-table-fixed-column--right {
          background-color: rgba(240, 243, 247, 1);
        }
      }

      :deep(.el-table__row td) {
        padding: 0;
        border: 0;
      }

      .el-button--primary {
        margin-left: 5px;
      }

      :deep(.el-table__body .even) {
        background-color: #fff;
      }

      :deep(.el-table__body .odd) {
        background-color: rgba(240, 243, 247, 1);
      }

      :deep(.edit) {
        display: flex;
        align-items: center;
        justify-content: center;
        color: rgba(111, 182, 184, 1);
      }

      :deep(.look) {
        padding: 0 10px;
        cursor: pointer;
        color: rgba(30, 125, 251, 1);
      }

      .del {
        color: rgba(212, 48, 48, 1);
        cursor: pointer;
      }

      // :deep(.look):hover {
      //   color: red;
      // }
      // :deep(.del):hover {
      //   color: red;
      // }
    }

    // 添加房型弹窗样式
    :deep(.addStaff) {
      height: 650px;
      border-radius: 11px;

      .el-dialog__header {
        border-radius: 11px 11px 0 0;
        background: rgba(237, 241, 245, 1);
        font-weight: 600;
        margin: 0;

        .el-dialog__headerbtn {
          outline: none;
        }
      }

      .el-dialog__body {
        padding: 10px 30px 10px 35px;

        .slider {
          height: 560px;
          overflow: auto;
        }

        .tooltips {
          display: flex;

          .img {
            display: flex;

            .img_title {
              span {
                display: inline-block;
                width: 60px;
              }
            }

            .updateImg {
              display: flex;
              flex-direction: column;
              width: 720px;

              .el-upload {
                // margin-top: 20px;
                .zhu {
                  color: rgba(212, 48, 48, 1);
                }
              }
            }
          }
        }

        .img1 {
          img {
            width: 183px;
            height: 121px;
            opacity: 1;
            border-radius: 10px;
          }

          .updateImg {
            .el-upload__tip {
              color: rgba(212, 48, 48, 1);
              transform: translateX(-30px);
            }

            .el-upload-list {
              display: none;
            }

            .imglist {
              display: flex;
              flex-wrap: wrap;
              margin-bottom: 15px;

              img {
                margin-right: 15px;
              }

              .imgItem {
                position: relative;
              }

              .lookImg {
                width: 183px;
                height: 121px;
                cursor: pointer;
                position: absolute;
                top: 0;
                left: 0;
                border-radius: 10px;
                display: flex;
                justify-content: center;
                align-items: center;

                img {
                  width: 30px;
                  height: 30px;
                  opacity: 0;
                }

                .delimg {
                  width: 30px;
                  height: 30px;
                  background-image: url("@/assets/imgDel.png");
                  background-size: 100%;
                  opacity: 0;
                  margin-left: 5px;
                }
              }

              .lookImg:hover {
                background-color: rgba(0, 0, 0, 0.2);

                img {
                  opacity: 1;
                  cursor: pointer;
                }

                .delimg {
                  opacity: 1;
                  cursor: pointer;
                }
              }
            }
          }
        }

        .el-input {
          width: 200px;
        }

        .el-form {
          .titles {
            font-weight: 600;
            color: #000;
            font-size: 18px;
            margin: 10px 0 20px 0;

            span:nth-child(2) {
              color: rgba(212, 48, 48, 1);
            }
          }

          .footer {
            color: rgba(212, 48, 48, 1);
          }

          .form_item {
            display: flex;
            margin-bottom: 10px;

            .intro {
              .el-form-item__content {
                width: 550px;
              }
            }

            .default {
              .el-form-item__label {
                width: 160px !important;
              }
            }
          }

          .tag {
            .el-form-item__content {
              width: 200px;
            }
          }

          .roomUl {
            display: flex;

            // margin: 10px 0;
            // align-items: center;
            .title {
              width: 100px;
              height: 40px;
              text-align: left;
              line-height: 40px;
            }

            .delRoom {
              .ul {
                width: 680px;
                list-style: none;
                border: none;
                display: flex;
                flex-wrap: wrap;
                margin: 0;
                padding: 0;

                .li {
                  display: flex;
                  flex-wrap: wrap;

                  .li_items {
                    // span {
                    //   margin-right: 40px;
                    // }
                    .li_item {
                      display: flex;
                      justify-content: space-around;
                      align-items: center;
                      width: 120px;
                      height: 40px;
                      border: 1px solid #e0e0e0;
                      margin: 0 10px 10px 0;
                      border-radius: 7px;
                    }

                    .li_item_warning {
                      border: 1px solid red;
                    }

                    .warning {
                      color: red;
                      // text-align: center;
                      font-size: 12px;
                    }

                    .el-input {
                      width: 70px;

                      .el-input__wrapper {
                        box-shadow: none;
                      }
                    }

                    .del {
                      width: 14px;
                      height: 14px;
                      background-image: url("@/assets/delete.png");
                      background-size: 100%;
                    }

                    .del:hover {
                      background-image: url("@/assets/delete_hover.png");
                      cursor: pointer;
                    }
                  }
                }

                .addRoom {
                  cursor: pointer;
                  margin-left: 10px;
                  height: 42px;
                  color: rgba(9, 101, 98, 1);
                  display: flex;
                  justify-content: space-around;
                  align-items: center;

                  img {
                    width: 15px;
                    margin-right: 5px;
                  }
                }
              }
            }
          }
        }

        .options {
          width: 100%;
          margin: 25px 0 15px 0;

          .el-form-item__content {
            .queding {
              margin-left: 20px;
              color: #fff;
            }

            display: flex;
            flex-direction: row-reverse;
          }
        }
      }
    }
  }

  .bgImg {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 99999999;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.8);

    // border-radius: 50px;
    :deep(.el-carousel__container) {
      width: 100%;
      height: calc(100vh);

      .el-carousel__item {
        display: flex;
        justify-content: center;

        img {
          height: 100%;
        }
      }
    }
  }

  .pageSize {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    span {
      color: #000;
    }

    .el-pagination {
      // width: 1600px;
      :deep(.el-pagination__total) {
        color: #000;
      }

      :deep(.el-pagination__goto) {
        color: #000;
      }

      :deep(.el-pagination__classifier) {
        color: #000;
      }

      :deep(.el-input__wrapper) {
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        box-shadow: none;
      }

      :deep(.el-pager li) {
        margin: 0 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }

      :deep(.el-pager li.is-active) {
        // background-color: rgba(0, 97, 255, 0.8);
        border: 1px solid rgba(0, 97, 255, 1);
        color: rgba(0, 97, 255, 1);
      }

      :deep(.btn-prev) {
        margin-right: 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }

      :deep(.btn-next) {
        margin-left: 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }
    }
  }
}

.el-input {
  width: 192px;
}
</style>
