<template>
  <div>
    <el-card :body-style="{ padding: '5px' }" style="margin-bottom:5px">
      <header-box :search="search" @searchClick="searchClick" />
    </el-card>
    <el-card :body-style="{ padding: '10px' }">
      <el-row style="margin-bottom:5px;">
        <el-col :span="24" style="text-align: right">
          <el-button @click="btnClick(1)" type="success" size="mini">新增</el-button>
          <el-button @click="btnClick(2)" type="primary" size="mini">修改</el-button>
          <el-button @click="btnClick(3)" type="danger" size="mini">删除</el-button>
        </el-col>
      </el-row>
      <el-table ref="tableTwo" :data="tableData" :max-height="tableHeight" size="mini" border v-loading="tableLoading"
        @selection-change="handleSelectionChange($event,2)">
        <el-table-column align="center" type="selection" width="60"></el-table-column>
        <el-table-column align="center" show-overflow-tooltip prop="name" width="140">
          <template slot="header">
            <label>姓&nbsp;&nbsp;&nbsp;&nbsp;名</label>
          </template>
          <template slot-scope="scope">
            <div style="color:blue;font-size:small">
              {{scope.row.name}}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" show-overflow-tooltip label="手机号" prop="phone" width="120"></el-table-column>
        <el-table-column align="center" show-overflow-tooltip label="身份证" prop="idCard"></el-table-column>
        <el-table-column align="center" show-overflow-tooltip label="预约时间" prop="appointmentTime">
        </el-table-column>
        <el-table-column align="center" show-overflow-tooltip prop="status" width="100">
          <template slot="header">
            <label>状&nbsp;&nbsp;&nbsp;&nbsp;态</label>
          </template>
          <template slot-scope="scope">
            <el-tag :type="scope.row.status|statusColor" effect="dark">
              {{scope.row.status| statusName}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" show-overflow-tooltip label="登记人" prop="optUser" width="120"></el-table-column>
        <el-table-column align="center" show-overflow-tooltip label="创建时间" prop="createTime"></el-table-column>
        <el-table-column align="center" show-overflow-tooltip prop="note" width="100">
          <template slot="header">
            <label>备&nbsp;&nbsp;&nbsp;&nbsp;注</label>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange"
        layout="total, prev, pager, next, sizes" :page-size="pagination.pageSize" :page-sizes="[10, 20, 40, 150]"
        :current-page="pagination.pageNum" :total="pagination.total">
      </el-pagination>
    </el-card>
    <el-dialog :title="title" :visible.sync="visible" v-dialogDrag :close-on-click-modal="false" :before-close="cancel"
      width="55%">
      <el-form :model="form" ref="ruleform" label-width="100px" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="name" label="姓名">
              <el-input size="mini" maxlength="5" placeholder="请输入内容" v-model="form.name">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="phone" label="手机号">
              <el-input size="mini" placeholder="请输入内容" v-model="form.phone">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="idCard" label="身份证">
              <el-input size="mini" placeholder="请输入内容" v-model="form.idCard">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="appointmentTime" label="预约时间">
              <el-date-picker size="mini" :picker-options="pickerOptions" style="width:100%"
                v-model="form.appointmentTime" type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item prop="note" label="备注">
            <el-input size="mini" type="textarea" :rows="2" placeholder="请输入内容" v-model="form.note">
            </el-input>
          </el-form-item>
        </el-row>
        <el-form-item>
          <el-button size="mini" type="primary" @click="submitForm('ruleform')">提交</el-button>
          <el-button size="mini" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {
  getData,
  addAppointment,
  deleteAppointment,
  editAppointment,
} from "@/api/appointment";
import { getButtonList } from "@/api/user";
import headerBox from "./components/header.vue";
import moment from "moment";
import { clearObjValue, message, getCurrentTime } from "@/utils/common";
export default {
  data() {
    return {
      pickerOptions: {
        selectableRange: (() => {
          let data = new Date();
          let hour = data.getHours();
          let minute = data.getMinutes();
          let second = data.getSeconds();
          return [`${hour}:${minute}:${second} - 23:59:59`];
        })(),
        disabledDate(time) {
          var date = new Date();
          date.setFullYear(date.getFullYear() + 2);
          date.setDate(date.getDate() - 1);
          return (
            time.getTime() < Date.now() - 8.64e7 ||
            time.getTime() > date.getTime()
          );
        },
      },
      tableHeight: window.innerHeight - 250,
      showButtons: {
        qxbs: false,
      },
      search: {
        phone: "",
        name: "",
        time: "",
        status: "",
      },
      multipleSelection: [],
      tableData: [],
      pagination: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
      },
      title: "",
      tableLoading: false,
      visible: false,
      form: {
        id: "",
        idCard: "",
        name: "",
        phone: "",
        appointmentTime: "",
        note: "",
        optUser: "",
      },
      rules: {
        idCard: [
          {
            required: true,
            message: "身份证不能为空",
            trigger: ["blur", "change"],
          },
          {
            pattern:
              /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/,
            message: "请输入正确的身份证",
            trigger: ["blur", "change"],
          },
        ],
        phone: [
          {
            required: true,
            message: "手机号不能为空",
            trigger: ["blur", "change"],
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号",
            trigger: ["blur", "change"],
          },
        ],
        appointmentTime: [
          {
            required: true,
            message: "请选择预约时间",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入姓名",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  filters: {
    statusName(status) {
      const statusMap = {
        0: "未提醒",
        1: "提醒中",
        "-1": "已过期",
      };
      return statusMap[status];
    },
    statusColor(status) {
      const statusMap = {
        0: "warning",
        1: "success",
        "-1": "danger",
      };
      return statusMap[status];
    },
  },
  components: {
    headerBox,
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    submitForm(formName, key) {
      this.$refs[formName].validate((valid) => {
        this.form.appointmentTime = moment(this.form.appointmentTime).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        if (valid) {
          if (this.title === "新增") {
            this.form.optUser = sessionStorage.getItem("userCHname");
            addAppointment(this.form).then((res) => {
              message("success", "新增成功", 3000);
              this.$store.dispatch("websocket/selectCount");
              this.getTableData();
              this.cancel();
            });
          } else {
            editAppointment(this.form).then((res) => {
              message("success", "修改成功", 3000);
              this.getTableData();
              this.$store.dispatch("websocket/selectCount");
              this.cancel();
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    btnClick(key) {
      clearObjValue(this.form);
      switch (key) {
        case 1:
          this.visible = true;
          this.title = "新增";
          break;
        case 2:
          if (
            this.multipleSelection.length &&
            this.multipleSelection.length === 1
          ) {
            for (let key in this.form) {
              this.form[key] = this.multipleSelection[0][key];
            }
            this.visible = true;
            this.title = "编辑";
          } else {
            message("warning", "请选择一条消息进行修改", 3000);
          }
          break;
        case 3:
          if (!this.multipleSelection.length) {
            message("warning", "请先选择您要删除的信息", 3000);
            return;
          }
          let data = {
            ids: this.multipleSelection.map((ele) => ele.id).join(","),
          };
          this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              deleteAppointment(data).then((res) => {
                message("success", "删除成功", 3000);
                this.getTableData();
              });
            })
            .catch(() => {});

          break;
      }
    },
    searchClick() {
      this.pagination.pageNum = 1;
      this.getTableData();
    },
    getTableData() {
      this.tableLoading = true;
      let params = {
        phone: this.search.phone ? this.search.phone : "",
        name: this.search.name ? this.search.name : "",
        startTime: this.search.time ? this.search.time[0] : "",
        endTime: this.search.time ? this.search.time[1] : "",
        status: this.search.status ? this.search.status : "",
        page: this.pagination.pageNum,
        limit: this.pagination.pageSize,
      };
      getData(params)
        .then((res) => {
          this.tableData = res.body.list;
          this.pagination.total = res.body.total;
        })
        .finally((res) => {
          this.tableLoading = false;
        });
    },
    cancel() {
      clearObjValue(this.form);
      this.$refs["ruleform"].resetFields();
      this.visible = false;
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val;
      this.getTableData();
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.pageNum = 1;
      this.getTableData();
    },
  },
  created() {
    this.getTableData();
  },
};
</script>
<style lang="scss" scoped>
::v-deep {
  .el-table__body tr.current-row > td {
    background-color: #cbd7ffd4;
    color: #000000;
    font-weight: 600;
  }
}

::v-deep .el-drawer__header {
  margin-bottom: 10px;
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 17px;
}

.btnClass {
  padding: 5px;
}

.contentBox {
  display: flex;
  justify-content: space-around;

  .box-card {
    .demo-image__lazy {
      background: rgb(245, 245, 245);
      padding: 5px 15px;
      text-align: center;

      .imgs {
        width: 70%;
      }
    }

    .uploadBox {
      padding: 5px;

      ::v-deep ul {
        background: rgba(95, 95, 95, 0.2);
        width: 300px;
      }
    }
  }
}

::v-deep .el-drawer__body {
  overflow: auto;
}

::v-deep .el-drawer__container ::-webkit-scrollbar {
  display: none;
}

::v-deep .el-tabs__header {
  margin: 0;
}
</style>
