<template>
  <el-card :header="dept.name" style="height: 100%">
    <template #header>
      <el-row type="flex" style="text-align: center">
        <el-col :span="8">
          <el-button type="primary" size="mini" :disabled="!(dept && dept.id)" @click="toAdd()">添加</el-button>
        </el-col>
        <el-col :span="8" style="color: red">{{ dept.name || '未选择分局,无法进行安排' }}</el-col>
        <el-col :span="8">
          <el-switch v-model="view" active-text="列表" active-value="列表" inactive-text="日历" inactive-value="日历" :disabled="!(dept && dept.id)" />
        </el-col>
      </el-row>
    </template>
    <el-calendar v-if="view === '日历'" :value="viewDate" @input="toInput">
      <template #dateCell="{ date }">
        <el-row class="rows" @click.native="toEdit(date)">
          <el-col :span="4">{{ getDay(date) }}</el-col>
          <el-col :span="20" v-for="(i, index) in getThisDay(date)" :key="`day-${index}`">
            <el-alert :closable="false" :style="getStyle(date, i.collect_time_start)">
              <el-row>
                <el-col :span="24" style="color: #000">{{ getTimeStr(i) }};预计{{ i.number }}人</el-col>
                <el-col :span="24" style="color: red">剩余:{{ computeNumber(i) }}人</el-col>
              </el-row>
            </el-alert>
          </el-col>
        </el-row>
      </template>
    </el-calendar>
    <template v-else>
      <el-row>
        <el-col :span="24" style="text-align: center; margin: 10px 0">
          <el-date-picker :value="viewDate" @input="toInput" type="month" placeholder="选择月"> </el-date-picker>
        </el-col>
      </el-row>
      <el-table :data="list" border :span-method="spanTable">
        <el-table-column align="center" label="日期" prop="collect_date"></el-table-column>
        <el-table-column align="center" label="开始时间" prop="collect_time_start" />
        <el-table-column align="center" label="开始时间" prop="collect_time_end" />
        <el-table-column align="center" label="可预约人数" prop="number" />
        <el-table-column align="center" label="已预约人数" prop="reserve_number" />
        <el-table-column align="center" label="操作" prop="opera">
          <template #default="{ row }">
            <el-row type="flex" justify="space-around" v-if="!checkCanEditOrDelete(row.collect_date).result">
              <el-col :span="4">
                <el-link type="primary" :underline="false" icon="el-icon-edit" @click="toEdit(row.collect_date)"></el-link>
              </el-col>
              <el-col :span="4">
                <el-link type="danger" :underline="false" icon="el-icon-delete" @click="toDelete(row)"></el-link>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </el-card>
</template>

<script>
const _ = require('lodash');
const moment = require('moment');
import { mapState, createNamespacedHelpers } from 'vuex';
export default {
  name: 'calendar',
  props: {
    viewDate: { type: Date },
    dept: { type: Object, default: () => {} }, // 部门信息
    list: { type: Array, default: () => [] }, // 预约安排列表
    recordList: { type: Array, default: () => [] }, // 已预约的列表
  },
  model: {
    prop: 'viewDate',
    event: 'change',
  },
  components: {},
  data: function () {
    return {
      mocolor: '#BBFFFF', // 上午颜色
      afcolor: '#FFA500', // 下午颜色
      colorLimit: '13:00', //上下午判定解限
      view: '日历',
    };
  },
  created() {},
  methods: {
    // 格式化 日
    getDay(date) {
      const d = moment(date).format('D');
      return d;
    },
    // 取出该天的安排
    getThisDay(date) {
      const fdate = moment(date).format('YYYY-MM-DD');
      let list = this.list.filter((f) => f.collect_date === fdate);
      list = _.orderBy(list, ['collect_date', 'collect_time_start', 'collect_time_end'], ['asc', 'asc', 'asc']);
      return list;
    },
    // 时间显示
    getTimeStr(arrange) {
      let str;
      if (_.get(arrange, 'collect_time_start') && _.get(arrange, 'collect_time_end')) {
        const s = `${moment().format('YYYY-MM-DD')} ${_.get(arrange, 'collect_time_start')}`;
        const e = `${moment().format('YYYY-MM-DD')} ${_.get(arrange, 'collect_time_end')}`;
        str = `${moment(s).format('H:mm')}-${moment(e).format('H:mm')}`;
      }
      return str;
    },
    // 计算剩余人数数
    computeNumber(arrange) {
      const total = _.get(arrange, 'number', 0);
      const use = _.get(arrange, 'reserve_number', 0);
      return _.subtract(total, use);
    },
    // 判断是否是 下午
    isAfternooe(date, time) {
      const tarr = time.split('-');
      const sd = `${moment(date).format('YYYY-MM-DD')} ${tarr[0]}`;
      const limitDate = `${moment(date).format('YYYY-MM-DD')} ${this.colorLimit}`;
      return moment(sd).isSameOrAfter(limitDate);
    },
    // 设置样式
    getStyle(date, time) {
      const style = { background: this.mocolor, fontWeight: 800, padding: 0 };
      if (this.isAfternooe(date, time)) style.background = this.afcolor;
      return style;
    },
    // 编辑
    toEdit(date) {
      if (!_.get(this.dept, 'id')) return;
      // 检查这天是否有安排,有了不允许修改或删除了
      const result = this.checkCanEditOrDelete(date);
      if (result.result) {
        this.$message.warning(result.msg);
        return false;
      }
      date = moment(date).format('YYYY-MM-DD');
      const r = this.list.filter((f) => f.collect_date === date);
      if (r.length > 0) this.$emit('select', r);
    },
    // 添加
    toAdd() {
      this.$emit('add');
    },
    // 删除
    toDelete(row) {
      this.$confirm('确定要删除这天的安排吗?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$emit('delete', _.cloneDeep(row));
      });
    },
    // 检查是否有安排
    checkCanEditOrDelete(date) {
      let res = { result: false, msg: '' };
      if (moment().isSameOrAfter(date)) {
        res.result = true;
        res.msg = '今天 及 以前的安排不允许修改';
        return res;
      }
      const r = this.recordList.find((f) => f.collect_date === moment(date).format('YYYY-MM-DD'));
      if (r) {
        res.result = true;
        res.msg = '该天已经有人预约,不能进行修改';
        return res;
      }
      return res;
    },
    toInput(e) {
      this.$emit('change', e);
    },
    // 合并表格,日期和操作栏
    spanTable({ row, column }) {
      const prop = _.get(column, 'property');
      if (!(prop === 'opera' || prop === 'collect_date')) return [1, 1];
      const { id, collect_date } = row;
      const list = this.list.filter((f) => f.collect_date === collect_date);
      const index = list.findIndex((f) => f.id === id);
      if (index !== 0) return [0, 0];
      return [list.length, 1];
    },
  },
};
</script>

<style lang="less" scoped>
.rows {
  height: 100%;
  .el-col {
    padding: 2px 0;
  }
  .el-col:first-child {
    height: 100%;
  }
}
/deep/.el-calendar__body {
  overflow: auto;
}
/deep/.el-card__body {
  height: 100%;
  overflow: auto;
}
.rows__list {
  .el-col:not(:last-child) {
    border-bottom: 1px solid #ebeef5;
  }
}
/deep/.cell {
  padding: 0;
}
</style>
