<template>
  <div class="app-container">
    <el-card class="box-carde">
      <div slot="header" class="clearfix">
        <span>假期日历</span>
        <el-button style="float: right;padding:3px 10px 3px 3px;" type="text" @click="exportDataEvent">导出数据
        </el-button>
      </div>
      <el-button type="primary" size="small" @click="insertEvent" style="round-clip: 10px"
                 :loading="btnLonding">新增
      </el-button><!--v-loading="false"-->
      <div style="padding-top: 10px">
        <vxe-table
          :keep-source="true"
          align="center"
          :loading="loading"
          ref="xTable"
          auto-resize
          border
          resizable
          highlight-current-row
          show-overflow
          :edit-rules="rules"
          :data="tableData"
          v-show="showTable"
          :edit-config="{trigger: 'manual', mode: 'row',autoClear: false,icon:'none'}"
        >
          <vxe-table-column title="假期日历信息">
            <vxe-table-column field="name" title="假期名称"
                              :edit-render="{name:'$input',attrs:{type:'text',size:'3'}}"></vxe-table-column>
            <vxe-table-column field="holidayTypeEnum" title="假期类型"
                              :edit-render="{name: '$select', options: options}"></vxe-table-column>
            <vxe-table-column field="timeStartEnd" width="350px" title="开始时间-结束时间"
                              :edit-render="{props: {type: 'default'}}">
              <template v-slot:edit="{ row }">
                <el-date-picker
                  style="width: 100%"
                  v-model="timeStartEnd"
                  type="daterange"
                  value-format="timestamp"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions1"/>
              </template>
              <template v-slot="{ row }">{{ timestampToTime(row.startTime) }} 至 {{timestampToTime(row.endTime) }}
              </template>
            </vxe-table-column>
            <vxe-table-column field="days" title="天数"></vxe-table-column>
            <vxe-table-column width="15%" title="操作" align="center">
              <template v-slot="{ row }">
                <template v-if="$refs.xTable.isActiveByRow(row)">
                  <el-button
                    style="padding: 3px 4px 3px 4px;margin: 2px;"
                    type="success"
                    size="medium"
                    icon="el-icon-edit"
                    :loading="saveLoding"
                    @click="saveCheck(row)">保存
                  </el-button>
                  <el-button
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    class="cancel-btn"
                    icon="el-icon-refresh"
                    type="warning"
                    @click="cancelRowEvent(row)">取消
                  </el-button>
                </template>
                <template v-else>
                  <el-button
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-edit"
                    @click="editRowEvent(row)"
                    :loading="btnLonding">编辑
                  </el-button>
                  <el-button
                    type="danger"
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-delete"
                    @click="removeEvent(row)"
                    :loading=btnLonding>删除
                  </el-button>
                </template>
              </template>
            </vxe-table-column>
          </vxe-table-column>
        </vxe-table>
        <vxe-pager
          perfect
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :total="total"
          :page-sizes=[10,50,100]
          :layouts="['PrevJump', 'PrevPage','JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
          @page-change="handlePageChange"
          v-show="!btnLonding&&showTable"
        >
        </vxe-pager>
      </div>

    </el-card>
  </div>
</template>
<script>

  export default {
    data() {
      return {
        checkSign: false,
        checkTableDate: [],
        holidayType: '',
        timeStartEnd: [],
        loading: false,
        saveLoding: false,
        showTable: true,
        btnLonding: false,
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        options: [
          {
            value: "E1",
            label: "假期"
          },
          {
            value: "E2",
            label: "特殊工作日"
          }
        ],
        //表单验证规则
        rules: {
          name: [
            {required: true, message: '假期名称不能为空'},
            {min: 1, max: 9, message: '假期名称长度在 3 到 9 个字符'}
          ],
          holidayTypeEnum: [
            {required: true, message: '请选择假期类型'}
          ]
        },
        //当前日期之前日期不可选
        pickerOptions1: {
          disabledDate(time) {
            // return time.getTime() < Date.now() - 8.64e7;
            return time.getTime() <= Date.now();
          }
        }
      }
    },
    created() {
      this.getAll()
    },
    methods: {
      checkDate(v1, v2, v3, v4) {
        let result = false
        const item = ''
        // 修改时所需便利集合
        const v5 = []
        // 所有假期存放集合

        // 在修改时，把当前在所有信息集合里要修改的信息去掉（如果不去掉会影响校验）
        for (let i = 0; i < v2.length; i++) {
          if (v2[i].id == v4.id) {
            continue
          }
          v5.push(v2[i])
        }
        // 在编辑假期信息时 当前时间已存在于所有假期信息中，为防止当前时间被校验，在所有假期信息集合中删除该记录。
        // 编辑修改
        if (v3) {
          // 假期修改
          for (let i = 0; i < v5.length; i++) {
            if (v1[0] >= v5[i].startTime && v1[0] <= v5[i].endTime) {
              result = true
              break
            }
            if (v1[1] >= v5[i].startTime && v1[1] <= v5[i].endTime) {
              result = true
              break
            }
            if (v1[0] <= v5[i].startTime && v1[1] >= v5[i].endTime) {
              result = true
              break
            }
            if (v1[0] >= v5[i].startTime && v1[1] <= v5[i].endTime) {
              result = true
              break
            }
          }
        } else {
          for (let i = 0; i < v2.length; i++) {
            if (v1[0] >= v2[i].startTime && v1[0] <= v2[i].endTime) {
              result = true
              break
            }
            if (v1[1] >= v2[i].startTime && v1[1] <= v2[i].endTime) {
              result = true
              break
            }
            if (v1[0] <= v2[i].startTime && v1[1] >= v2[i].endTime) {
              result = true
              break
            }
            if (v1[0] >= v2[i].startTime && v1[1] <= v2[i].endTime) {
              result = true
              break
            }
          }
        }
        return result
      },
      getAll() {
        this.loading = true
        this.saveLoding = false
        this.btnLonding = false
        this.$axios.get("/holidayCalendar/" + this.currentPage + '/' + this.pageSize).then(response => {
          if (response.data.content == "") {
            this.showTable = false
          } else {
            this.showTable = true
          }
          this.tableData = response.data.content
          this.total = response.data.totalElements
          this.loading = false
        })
        this.$axios.get("/holidayCalendar/").then(response => {
          this.checkTableDate = response.data
        })
      },
      //编辑框改变
      editRowEvent(row) {
        this.checkSign = true
        this.timeStartEnd = [row.startTime, row.endTime]
        this.btnLonding = true
        this.$refs.xTable.setActiveRow(row)
      },
      //数据校验
      saveCheck(row) {
        this.$refs.xTable.validate(row, callback => {
          if (this.timeStartEnd == null) {
            // callback(new Error('开始结束日期不能为空'))
            this.$XModal.message({status: 'error', message: '开始结束日期不能为空！'})
          } else {
            // 判断开始时间是否是大于当前日期
            if (row.holidayTypeEnum == 'E2') {
              const startTime = new Date(this.timeStartEnd[0])
              const endTime = new Date(this.timeStartEnd[1])
              // 判断开始时间和结束时间是否是周六周日，切是相邻的周六周日
              //if ((startTime.getDay() == 6 || startTime.getDay() == 0||endTime.getDay() == 6 || endTime.getDay() == 0) && (this.timeStartEnd[1] - this.timeStartEnd[0] <= 1000 * 60 * 60 * 24 * 2)) {
              if ((startTime.getDay() < 1 || startTime.getDay() > 5) && (endTime.getDay() < 1 || endTime.getDay() > 5) && (this.timeStartEnd[1] - this.timeStartEnd[0] <= 1000 * 60 * 60 * 24 * 2)) {
                if (this.checkDate(this.timeStartEnd, this.checkTableDate, this.checkSign, row)) {
                  this.$XModal.message({status: 'error', message: '当前假日已存在于已有的假期中！'})
                } else {
                  callback:this.saveRowEvent(row)
                }
              } else {

                this.$XModal.message({status: 'error', message: '特殊工作日必须为周六周日且开始日期和结束日期相邻！'})
              }
            } else {
              if (this.checkDate(this.timeStartEnd, this.checkTableDate, this.checkSign, row)) {
                this.$XModal.message({status: 'error', message: '当前假日已存在于已有的假期中！'})
              } else {
                callback:this.saveRowEvent(row)
              }
            }
          }
        })
      },
      //保存数据操作
      saveRowEvent(row) {
        row.startTime = this.timeStartEnd[0]
        row.endTime = this.timeStartEnd[1]
        row.days = (row.endTime -row.startTime) / 86400000 + 1
        this.saveLoding = true

        this.$refs.xTable.validate(valid => {
          if (valid) {
            if (row.id == undefined) {

              this.$axios.post("/holidayCalendar/", row).then(response => {
                this.btnLonding = false
                this.saveLoding = false
                this.getAll()
                this.$XModal.message({status: 'warning', message: response.message})

              })
            } else {
              this.$axios.put("/holidayCalendar/", row).then(response => {
                this.saveLoding = false
                this.getAll()
                this.$XModal.message({status: 'warning', message: response.message})
              })
            }
          } else {
            this.$XModal.message({status: 'error', message: '校验不通过！'})
            this.saveLoding = false
          }
        })
      },
      //取消编辑或添加操作
      cancelRowEvent(row) {
        this.saveLoding = false
        this.btnLonding = false
        const xTable = this.$refs.xTable
        if (row.id == undefined) {
          this.$refs.xTable.remove(row)
        } else {
          xTable.clearActived().then(() => {
            // 还原行数据
            xTable.revertData(row)
          })
        }
      },
      //删除数据
      removeEvent(row) {
        this.$XModal.confirm('您确定要删除该数据?').then(type => {
          if (type === 'confirm') {
            this.$axios.delete("/holidayCalendar/", {data: row}).then(response => {
              this.$XModal.message({status: 'warning', message: response.message})
              this.getAll()
            })
          }
        })
      },
      //时间戳日期转换器
      timestampToTime(time) {
        const date = new Date(time) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
        const Y = date.getFullYear() + '-'
        const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
        const D = date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()
        return Y + M + D
      },
      //新增编辑框
      insertEvent() {
        this.timeStartEnd = []
        this.showTable = true
        this.btnLonding = true
        this.checkSign = false
        this.$refs.xTable.insert()
          .then(({row}) => this.$refs.xTable.setActiveRow(row))
      },
      //分页触发事件
      handlePageChange({currentPage, pageSize}) {
        this.currentPage = currentPage
        this.pageSize = pageSize
        this.getAll()
      },
      //导出
      exportDataEvent() {
        this.loading = true
        this.$axios.get('/holidayCalendar/').then(res => {
          const data = res.data.content
          this.$refs.xTable.exportData({
            filename: '假期日历信息',
            type: 'csv',
            isHeader: true,
            isFooter: true,
            data
          })
          this.loading = false
          // this.loading = false
        }).catch(e => {
          this.loading = false

        })
      },
      //导入
      // importDataEvent() {
      //   this.$refs.xTable.importData({types: ['csv']})
      // }
    }
  }
</script>

<style lang="scss" scoped>
  .app-container {
    /*left: 0;*/
    /*width: 100%;*/
    /*min-height: 100%;*/
    /*height: auto;*/
    /*background-image: linear-gradient(25deg, #05362d, #145d44, #24875d, #35b477)*/
  }

  .pagination {
    margin: 20px 0;
    text-align: right;
  }
</style>
