<template>
  <div class="app-container">
    <el-form :inline="true" ref="query" :model="query" size="mini">
      <el-form-item label="日历标题" prop="uuid">
        <el-select v-model="query.uuid" filterable placeholder="请输入日历标题">
          <el-option
            v-for="(item, index) in queryList"
            :key="index"
            :label="item.title"
            :value="item.uuid"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="成员" prop="user">
        <el-select v-model="query.user" filterable placeholder="请选择日历成员">
          <el-option
            v-for="(item, index) in userList"
            :key="index"
            :label="item.username"
            :value="item.uuid"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="起止时间">
        <el-date-picker
          v-model="datetime"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          align="right"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onQuery">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="onReset('query')">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="onAdd">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="isLoading"
      element-loading-text="Loading"
      :data="tableData"
      size="mini"
      border
      stripe
      fit
      highlight-current-row
    >
      <el-table-column
        v-for="(item, index) in tableHeader"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :align="item.align"
        :min-width="item.width"
        :show-overflow-tooltip="item.overflow"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="page-wrapper">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="query.pagenum"
        background
        small
        :page-size="query.pagesize"
        :pager-count="5"
        layout="pager, prev, next, total"
        :total="total"
      ></el-pagination>
    </div>
    <formdialog
      ref="formdialog"
      :title="dialogTitle"
      :visible="dialogVisible"
      @close="dialogVisible = false"
      @confirm="submitForm"
    ></formdialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import { getUserList } from "@/api/index";
import { mapTrim } from "@/utils/index";
import { formatUTCDateTime } from "@/utils/utils";

import formdialog from "./components/dialog";

const today = new Date();
const yestoday = new Date();
yestoday.setDate(today.getDate() - 1); // 昨天

export default {
  name: "CalendarTable",
  components: {
    formdialog,
  },
  data() {
    return {
      total: 0,
      tableData: [],
      isLoading: false,
      datetime: [yestoday, today],
      current: [yestoday, today],
      queryList: [],
      userList: [],
      query: {
        uuid: null,
        user: null,
        start_time: null,
        end_time: null,
        pagesize: 15,
        pagenum: 1,
      },
      dialogTitle: "",
      dialogVisible: false,
      urlPrefix: "/api/v1/evm_store/calendar",
      tableHeader: [
        {
          label: "事件标题",
          prop: "title",
          align: "center",
          width: "250",
          overflow: true,
        },
        {
          label: "开始时间",
          prop: "start_time",
          align: "center",
          width: "150",
        },
        {
          label: "结束时间",
          prop: "end_time",
          align: "center",
          width: "150",
        },
        {
          label: "创建者",
          prop: "create_by.username",
          align: "center",
          width: "150",
        },
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  methods: {
    addItem(params) {
      return request({
        url: this.urlPrefix + `/add`,
        method: "post",
        data: params,
      });
    },
    getItemList(params) {
      return request({
        url: this.urlPrefix + `/list`,
        method: "post",
        data: params,
      });
    },
    updateItem(id, params) {
      return request({
        url: `${this.urlPrefix}/update/${id}`,
        method: "post",
        data: params,
      });
    },
    deleteItem(id) {
      return request({
        url: `${this.urlPrefix}/delete/${id}`,
        method: "post",
      });
    },
    fetchUserList() {
      getUserList({ scope_type: "list" })
        .then((res) => {
          this.userList = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    fetchQueryList() {
      this.getItemList({ scope_type: "list" })
        .then((res) => {
          this.queryList = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    fetchData(params) {
      this.isLoading = true;
      this.getItemList(params)
        .then((res) => {
          this.total = res.count;
          this.tableData = res.data;
        })
        .catch((err) => {
          console.log(err.message);
          this.$message.warning("暂无数据")
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    handleSizeChange(e) {
      this.query.pagesize = e;
      this.fetchData(mapTrim(this.query));
    },
    handleCurrentChange(e) {
      this.query.pagenum = e;
      this.fetchData(mapTrim(this.query));
    },
    handleEdit(index, row) {
      this.dialogTitle = "编辑";
      this.dialogVisible = true;
      this.$refs["formdialog"].update(row);
    },
    handleDelete(index, row) {
      this.$alert(
        "您确定要删除么？删除操作将不可恢复。如需取消操作，请点击右上角关闭按钮。",
        "删除提醒",
        {
          confirmButtonText: "确定",
          callback: (action) => {
            if (action == "confirm")
              this.deleteItem(row.uuid)
                .then((res) => {
                  console.log(res);
                  this.total -= 1;
                  this.$delete(this.tableData, index);
                  this.$message({
                    type: "success",
                    message: `成功删除第${index + 1}行`,
                  });
                })
                .catch((err) => {
                  this.$message.error(err.message);
                });
          },
        }
      );
    },
    submitForm(formdata) {
      if (this.dialogTitle === "添加") {
        this.addItem(formdata)
          .then((res) => {
            console.log(res);
            this.$message({ type: "success", message: "添加成功" });
            this.fetchData(mapTrim(this.query));
          })
          .catch((err) => {
            this.$message.error(err.message);
          });
      } else if (this.dialogTitle === "编辑") {
        this.updateItem(formdata.uuid, formdata)
          .then((res) => {
            console.log(res);
            this.$message({ type: "success", message: "更新成功" });
            this.fetchData(mapTrim(this.query));
          })
          .catch((err) => {
            this.$message.error(err.message);
          });
      }
    },
    onAdd() {
      this.dialogTitle = "添加"
      this.dialogVisible = true
    },
    onQuery() {
      this.query.pagenum = 1
      this.query.pagesize = 15
      if (this.current[0].getTime() !== this.datetime[0].getTime()) {
        this.current[0] = this.datetime[0]
        this.query.start_time = formatUTCDateTime(this.datetime[0])
      }
      else this.query.start_time = null
      if (this.current[1].getTime() !== this.datetime[1].getTime()) {
        this.current[1] = this.datetime[1]
        this.query.end_time = formatUTCDateTime(this.datetime[1])
      }
      else this.query.end_time = null
      this.fetchData(mapTrim(this.query))
    },
    onReset(formName) {
      this.$refs[formName].resetFields()
      this.onQuery()
    },
  },
  mounted() {},
  created() {
    this.fetchData(mapTrim(this.query))
    this.fetchQueryList()
    this.fetchUserList()
  },
};
</script>

<style lang="less" scoped>
.app-container {
  & > div.page-wrapper {
    margin: 10px 0px;
  }
}
</style>
