<template>
  <div class="app-container">
    <div class="basic-msg" v-loading="listLoading">
      <h4>基本信息</h4>
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="130px"
        class="box"
      >
        <div class="box-item">
          <el-form-item label="场所标题" prop="title">
            <el-input v-model.trim="form.title" placeholder="请输入场所标题" />
          </el-form-item>
          <el-form-item label="场所图片" prop="picture">
            <el-upload
              ref="upload"
              name="file"
              class="avatar-uploader"
              :action="doUpload"
              :show-file-list="false"
              :http-request="doUploadAvatar"
              :before-upload="beforeAvatarUpload"
              :auto-upload="true"
              accept="image/png,image/gif,image/jpg,image/jpeg"
            >
              <img v-if="form.picture" :src="form.picture" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </div>
        <el-form-item label="场所说明" prop="instructions" class="box-item">
          <el-input
            type="textarea"
            maxlength="200"
            v-model.trim="form.instructions"
            placeholder="请输入描述说明（200字以内）"
          />
        </el-form-item>
      </el-form>
      <el-button class="sure" type="primary" @click="placeSave">保存</el-button>
    </div>
    <div class="basic-msg">
      <h4>预约时间段</h4>
      <span class="add-time" type="primary" plain @click="openDialog">+</span>
      <div class="flex-content">
        <div
          class="box-card"
          v-for="item in msg_list"
          :key="item.placeDetailId"
        >
          <div :class="timeBgc(item)">
            <span style="float: left"
              >发布时间：{{ item.createTime | nullData }}</span
            >
            <span style="float: right">{{
              item.status | timeText(item.endTime)
            }}</span>
          </div>
          <div class="content-item">
            <div class="flex-box margin-top">
              <div class="flex-itme">
                开始时间：{{ item.startTime | nullData }}
              </div>
              <div class="flex-itme">
                结束时间：{{ item.endTime | nullData }}
              </div>
            </div>
            <div class="flex-box">
              <div class="flex-itme">
                额定人数：{{ item.limitNumber | nullData }}
              </div>
              <div class="flex-itme">
                已约人数：{{ item.appointmentNumber | nullData }}
              </div>
            </div>
            <div class="card-button">
              <el-button
                type="danger"
                class="del"
                v-if="msg_list.length > 1"
                @click="appointmentDelete(item.placeDetailId)"
                >删除</el-button
              ><el-button
                type="primary"
                @click="appointmentUpdate(item)"
                v-if="new Date(item.endTime).getTime() > Date.now()"
              >
                {{ item.status === true ? "停用" : "启用" }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      title="添加预约时间段"
      :visible.sync="addTimeVisible"
      destroy-on-close
    >
      <el-form
        :model="formTime"
        :rules="rulesTime"
        ref="formTime"
        label-width="100px"
      >
        <el-form-item label="是否启用" prop="status">
          <el-radio-group v-model="formTime.status">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="预约时段" prop="startTime">
          <el-date-picker
            v-model="formTime.startTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始日期时间"
            :picker-options="expireTimeOption"
          >
          </el-date-picker>
          -
          <el-date-picker
            v-model="formTime.endTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择结束日期时间"
            :picker-options="expireTimeOption"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="额定人数" prop="limitNumber">
          <el-input-number
            class="marginRight width220"
            v-model="formTime.limitNumber"
            controls-position="right"
            placeholder="额定人数"
            :min="0"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addTimeVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="sureAppointmentTime()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  pictureLocal,
  appointmentDelete,
  appointmentSave,
  getplace,
  placeSave,
  appointmentUpdate,
} from "@/api/ordinary_user.js";
import { defaultTime } from "@/utils/defaultTime";
export default {
  name: "UserMsg",
  components: {},
  props: {
    scenario: {
      type: String,
      default: "",
    },
    updateBuilding: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      expireTimeOption: {
        disabledDate(date) {
          var times = Date.now() - 24 * 60 * 60 * 1000;
          return date.getTime() <= times;
        },
        selectableRange: "00:00:00 - 23:59:59",
      },
      msg_list: [], //查询数据
      listLoading: false,

      form: {
        title: null,
        picture: null,
        instructions: null,
      },
      rules: {
        title: [
          {
            required: true,
            message: "请输入场所标题",
            trigger: "blur",
          },
        ],
        picture: [
          {
            required: true,
            message: "请上传场所图片",
            trigger: "blur",
          },
        ],
        instructions: [
          {
            required: true,
            message: "请填写场所说明",
            trigger: "blur",
          },
        ],
      },
      addTimeVisible: false,
      doUpload: "", //上传图片地址
      formTime_copy: {},
      formTime: {
        status: 1,
        limitNumber: 100,
        endTime: null,
        startTime: null,
      },
      rulesTime: {
        startTime: [
          {
            required: true,
            message: "请选择开始日期时间",
            trigger: "blur",
          },
        ],
        endTime: [
          {
            required: true,
            message: "请选择结束日期时间",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 查询
    getplace() {
      this.listLoading = true;
      getplace().then((res) => {
        this.msg_list = res.data.placeDetailDTOList;
        this.form.title = res.data.title;
        this.form.picture = res.data.picture;
        this.form.instructions = res.data.instructions;
        this.listLoading = false;
      });
    },
    // 基础信息保存
    placeSave() {
      placeSave(this.form).then((res) => {
        this.$message.success("保存成功！");
      });
    },
    // 打开预约时间段
    openDialog() {
      this.formTime = JSON.parse(JSON.stringify(this.formTime_copy));
      // console.log(this.formTime);
      this.addTimeVisible = true;
      this.$nextTick(() => {
        this.$refs["formTime"].clearValidate();
      });
    },
    // 添加预约时间段
    sureAppointmentTime() {
      this.$refs["formTime"].validate((valid) => {
        if (valid) {
          appointmentSave(this.formTime).then((res) => {
            this.addTimeVisible = false;
            this.getplace();
            this.$message({
              type: "success",
              message: "添加成功!",
            });
          });
        }
      });
    },
    // 删除预约信息
    appointmentDelete(id) {
      this.$confirm("确定要删除此条预约时段吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(() => {
        appointmentDelete(id).then((res) => {
          this.getplace();
          this.$message.success("删除成功！");
        });
      });
    },
    // 修改状态预约信息
    appointmentUpdate(item) {
      this.$confirm(
        "确定要" + (item.status ? "停用" : "启用") + "此条预约时段吗?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        }
      ).then(() => {
        item.status ? (item.status = 0) : (item.status = 1);
        appointmentUpdate(item).then((res) => {
          this.getplace();
          this.$message.success("操作成功！");
        });
      });
    },
    // 图片上传前
    beforeAvatarUpload(file) {
      if (
        !(
          file.type === "image/png" ||
          file.type === "image/gif" ||
          file.type === "image/jpg" ||
          file.type === "image/jpeg"
        )
      ) {
        this.$notify.warning({
          title: "警告",
          message:
            "请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片",
        });
        return;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$notify.warning({
          title: "警告",
          message: "图片大小必须小于2M",
        });
        return;
      }
    },
    doUploadAvatar(obj) {
      var avatar = new FormData();
      avatar.append("file", obj.file);
      pictureLocal(avatar).then((res) => {
        this.form.picture = res.data;
      });
    },
    defaultTime,
  },
  filters: {
    nullData(str) {
      return str ? str : "暂无";
    },
    timeText(status, endTime) {
      let str1 = "";
      if (new Date(endTime).getTime() > Date.now()) {
        status == 1 ? (str1 = "已启用") : (str1 = "已停用");
      } else {
        str1 = "已过期";
      }
      return str1;
    },
  },
  computed: {
    timeBgc() {
      return function (item) {
        return new Date(item.endTime).getTime() < Date.now()
          ? "dark-grey card-itme"
          : item.status == 1
          ? "green card-itme"
          : "gray card-itme";
      };
    },
  },
  watch: {
    "formTime.startTime"(selectTime) {
      if (selectTime) {
        var startAt = (new Date(selectTime) * 1000) / 1000;
        if (startAt < Date.now()) {
          this.formTime.startTime = this.defaultTime(0);
        }
      }
    },
    "formTime.endTime"(selectTime) {
      if (selectTime) {
        var endAt = (new Date(selectTime) * 1000) / 1000;
        if (endAt < Date.now()) {
          this.formTime.endTime = this.defaultTime(0);
        }
      }
    },
  },
  created() {
    this.formTime_copy = JSON.parse(JSON.stringify(this.formTime));
    this.getplace();
  },
  mounted() {},
};
</script>

<style scoped lang="scss">
.flex-content {
  display: flex;
  box-sizing: border-box;
  flex-wrap: wrap;
  padding-bottom: 22px;
}
.box {
  display: flex;
  justify-content: left;
  width: 100%;
}
.box-item {
  flex: 0.5;
}
.flex-box {
  display: flex;
  line-height: 22.5008px;
  padding: 8px 24px;
}
.margin-top {
  margin-top: 16px;
}
.flex {
  display: flex;
  padding: 30px 25px 0;
  box-sizing: border-box;
  flex-wrap: wrap;
}
.float {
  float: right;
  margin-left: 20px;
}
::v-deep.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 260px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 260px;
  height: 150px;
  display: block;
}
.basic-msg {
  box-shadow: 0px 1px 5px #e9ecf1;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 24px;
  position: relative;
}
.form-item {
  width: 900px;
  margin: 12px;
}
.float-left {
  width: 50%;
  float: left;
}
.float-right {
  width: 50%;
  float: right;
}

h4 {
  margin-left: 20px;
  margin-top: 20px;
}
::v-deep textarea {
  height: 210px;
}
.sure {
  margin: 32px auto;
  display: block;
}
.add-time {
  cursor: pointer;
  width: 46px;
  height: 32px;
  background: #eaf4ff;
  border-radius: 6px;
  color: #409eff;
  font-size: 32px;
  text-align: center;
  line-height: 32px;
  position: absolute;
  top: 14px;
  left: 112px;
}
.box-card {
  // height: 240px;
  width: 550px;
  box-shadow: 0px 1px 3px rgba(233, 236, 241, 0.9);
  border-radius: 10px;
  margin: 10px 20px;
}
.card-itme {
  height: 50px;
  padding: 15px 18px;
  box-sizing: border-box;
  border-radius: 10px 10px 0px 0px;
}
.flex-itme {
  flex: 0.5;
  justify-content: space-around;
}
.card-button {
  margin-top: 20px;
  margin-bottom: 24px;
  display: flex;
  justify-content: center;
}
.card-button > button {
  margin: 0 20px;
}
.green {
  background-color: #d1edc3;
  color: #61ab3c;
}
.gray {
  background-color: #e7ebf4;
  color: #6f7b96;
}
.dark-grey {
  background: #dbdada;
  color: #606266;
}
span {
  line-height: 20px;
}
</style>
