<template>
  <div class="restDay">
    <el-row :gutter="10">
      <el-col :lg="12" class="left_area">
        <el-card :body-style="{ padding: '10px' }" shadow="always">
          <span class="title">休息日设置</span>
          <div class="clearfix top_time">
            <el-col :md="8" :lg="10" :xl="8" class="calendar_time">
              <span class="month1">{{ curentDay.month | monthFilter }}</span>
              <span class="year num">{{ curentDay.year }}</span>
              <span class="tip">你 好</span>
              <span class="month2 num">{{ curentDay.month | zeroPad }}-{{ curentDay.day | zeroPad }}</span>
              <span class="month3">农历{{ curentDay.lunarMonth }}{{ curentDay.lunarDay }}</span><br>
              <span class="month4">{{ curentDay.gzYear }}年 {{ curentDay.gzMonth }}月 {{ curentDay.gzDay }}日</span>
              <span class="line1"/>
              <span class="line2"/>
              <img class="line3" src="../../../assets/imgs/line3.png" alt="斜线">
            </el-col>
            <el-col :md="16" :lg="14" :xl="16">
              <img class="calendar_img" src="../../../assets/imgs/calendar.png" alt="图片">
            </el-col>
          </div>
          <calendar
            ref="calendarData"
            :zero="calendarData.zero"
            :lunar="calendarData.lunar"
            :value="calendarData.value"
            :weeks="calendarData.weeks"
            :rest-days="calendarData.restDays"
            class="calendar"
            @select="select"
            @selectMonth="selectMonth"
            @selectYear="selectYear"
            @setCurentDay="getCurentDay"/>
        </el-card>
      </el-col>

      <el-col :lg="12">
        <el-card :body-style="{ padding: '10px' }" shadow="always">
          <span class="title">上班时间段设置</span>
          <div class="filter-container">
            <el-select v-model="group" class="filter-item" filterable clearable placeholder="请选择坐席组">
              <el-option
                v-for="item in seatOptions"
                :key="item.F_ZXZID"
                :label="item.F_ZXZName"
                :value="item.F_ZXZCode"/>
            </el-select>
            <el-input v-model="keyword" placeholder="请输入关键字" class="filter-item"/>
            <el-button type="primary" class="filter-item" icon="el-icon-search" @click="btn_search">搜索</el-button>
            <el-button v-permission="'HY_add'" type="primary" class="filter-item" icon="el-icon-plus" @click="btn_add">添加</el-button>
            <el-button v-permission="'HY_deletes'" type="primary" class="filter-item" icon="el-icon-delete" @click="btn_deletes()">批量删除</el-button>
          </div>
          <el-table v-loading="loading" :data="dataLists" border stripe @selection-change="changeSelects">
            <el-table-column type="selection" width="40"/>
            <el-table-column prop="F_GroupCode" label="坐席组" align="center" min-width=""/>
            <el-table-column prop="F_StartDate" label="开始时间" align="center" min-width=""/>
            <el-table-column prop="F_EndDate" label="结束时间" align="center" min-width=""/>
            <el-table-column prop="F_Name" label="时间段名称" align="center" min-width=""/>
            <el-table-column prop="F_Remark" label="时间段备注" align="center" min-width=""/>
            <el-table-column label="操作" width="90" align="center" class-name="oparate_btn" fixed="right">
              <template slot-scope="scope">
                <!-- <el-button size="mini" plain type="primary" v-permission="'HY_edit'" @click.stop="btn_edit(scope.row.id)">编辑</el-button> -->
                <el-button v-permission="'HY_edit'" size="mini" type="text" @click.stop="btn_edit(scope.row.F_Id)">编辑</el-button>
                <el-button v-permission="'HY_delete'" size="mini" type="text" @click.stop="btn_delete(scope.row.F_Id)">删除</el-button>
                <!-- <el-button class="del_btn" size="mini" plain type="danger" v-permission="'HY_delete'" @click.stop="btn_delete(scope.row.id)">删除</el-button> -->
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="pageParams.total > 0"
            :total="pageParams.total"
            :pageindex.sync="pageParams.pageindex"
            :pagesize.sync="pageParams.pagesize"
            class="pagination"
            @pagination="getLists" />

        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import calendar from '@/components/calendar'
import CalendarFun from '@/components/calendar/calendar'
import Pagination from '@/components/Pagination'
import { getSeatGroup } from '@/api/commonAPI'
import {
  getNowDate
} from '@/utils'
import {
  getRestDayLists,
  setRestDay,
  getWordDayLists,
  deleteWorkTime
} from '@/api/telCall/restDay'
import addOrEdit from './addOrEdit'

export default {
  name: 'RestDay',
  components: {
    calendar,
    Pagination
  },
  filters: {
    monthFilter: function(value) {
      const month = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
      return month[value - 1]
    },
    // 日期补零
    zeroPad: function(n) {
      return String(n < 10 ? '0' + n : n)
    },
  },
  data() {
    return {
      curentDay: {}, // 当前日期
      calendarData: {
        value: [], // 默认日期
        zero: true, // 是否小于10补零
        lunar: true, // 显示农历
        restDays: [], // 休息日 {id:'11',offdate:'2018-11-01'}
        weeks: ['Sun 日', 'Mon 一', 'Tue 二', 'Wed 三', 'Thu 四', 'Fri 五', 'Sat 六'], // 自定义星期名
        timestamp: Date.now()
      },
      seatOptions: [], // 坐席组下拉数据
      group: '', // 坐席组id
      keyword: '', // 关键字，根据备注模糊查询
      pageParams: {
        pageindex: 1, // 当前第几页
        pagesize: Number(this.$store.getters.serverConfig.PAGESIZE), // 每页几条数据
        total: 0 // 总共多少数据
      },
      dataLists: [], // 列表数据
      loading: false
    }
  },
  created() {
    const nowDay = getNowDate()
    const lunars = CalendarFun.solar2lunar(nowDay.split('-')[0], nowDay.split('-')[1], nowDay.split('-')[2])
    this.getCurentDay(lunars)
    this.calendarData.value = [nowDay.split('-')[0], nowDay.split('-')[1], nowDay.split('-')[2]]
    // 获取休息日 的数组
    this.getList()
    // 获取上班时段列表
    this.getLists()
    // 获取坐席组下拉数据
    this.getSeatGroupSelects()

    document.onkeyup = (e) => {
      if (e.keyCode === 13) {
        this.getLists()
      }
    }
  },
  methods: {
    // 获取休息日的数组
    getList() {
      return new Promise(resolve => {
        getRestDayLists().then(response => {
          if (response.state.toLowerCase() === 'success') {
            response = response.data
            this.calendarData.restDays = []
            if (response && response.length > 0) {
              response.forEach((v, i) => {
                this.calendarData.restDays.push({
                  id: v.F_Id,
                  offdate: v.F_Date.split(' ')[0]
                })
              })
            }
          }
        })
        resolve()
      })
    },

    select(value) {
      const lunars = CalendarFun.solar2lunar(value[0], value[1], value[2])
      this.getCurentDay(lunars) // 获取当前日子信息
      const offdate = value.join('-') // 是	string	日期
      let type = 0 // 是	init	类型：0休息日，1工作日
      let id = '' // 否	string	标识Id，设为工作日时必传
      // 获取当前选中日期的id 并设置 type
      const resd = this.calendarData.restDays
      if (resd && resd.length > 0) {
        for (let i = 0, len = resd.length; i < len; i++) {
          if (resd[i].offdate === offdate) {
            id = resd[i].id
            type = 1
          }
        }
      }
      this.setDays({
        offdate,
        type,
        id
      })
    },
    selectMonth(month, year) {
      const lunars = CalendarFun.solar2lunar(year, month, this.curentDay.day)
      this.getCurentDay(lunars)
    },
    selectYear(year) {
      const lunars = CalendarFun.solar2lunar(year, this.curentDay.month, this.curentDay.day)
      this.getCurentDay(lunars)
    },

    // 设置休息日
    setDays(data) {
      let msg = '您确定要将当前日期设置为休息日吗?'
      if (data.type) {
        msg = '您确定要将当前日期设置为工作日吗?'
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setRestDay(data).then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.getList()
            this.$message.success('设置成功!')
          }
        })
      }).catch(() => {
        this.$message.info('已取消设置')
      })
    },

    // 获取当前日子信息
    getCurentDay(lunars) {
      this.curentDay = {
        year: lunars.cYear, // 阳历年
        month: lunars.cMonth, // 阳历月
        day: lunars.cDay, // 阳历天
        lunarDay: lunars.IDayCn, // 农历天
        lunarMonth: lunars.IMonthCn, // 农历月
        gzYear: lunars.gzYear + lunars.Animal, // 如 戊戌狗
        gzMonth: lunars.gzMonth, // 如 癸亥月
        gzDay: lunars.gzDay // 如 癸亥天
      }
    },

    // 获取上班时段列表
    getLists() {
      return new Promise(resolve => {
        const params = {
          pageindex: this.pageParams.pageindex, // 第几页
          pagesize: this.pageParams.pagesize, // 每页几条信息
          key: this.keyword.replace(/\s+/g,""), // 否	string	关键字，根据备注模糊查询
          groupcode: this.group	// 否	string	坐席组编号（下拉）
        }
        getWordDayLists(params).then(response => {
          this.loading = false
          if (response.state.toLowerCase() === 'success') {
            this.pageParams.total = response.data.Totals
            this.dataLists = response.data.Rows
          }
        })
        resolve()
      })
    },

    // 复选框状态改变
    changeSelects(val) {
      this.multipleSelection = val
    },
    btn_search() {
      this.pageParams.pageindex = 1
      this.getLists()
    },
    btn_add() {
      this.$layer.iframe({
        content: {
          content: addOrEdit, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: { 'rowid': '' }// props//该方法会自动添加一个key为layerid的值， 该值为创建层的id， 可以直接使用
        },
        area: ['40%', '380px'],
        shadeClose: false,
        title: '添加上班时间段'
      })
    },
    btn_edit(eid) {
      this.$layer.iframe({
        content: {
          content: addOrEdit, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: { 'rowid': eid }// props//该方法会自动添加一个key为layerid的值， 该值为创建层的id， 可以直接使用
        },
        area: ['40%', '380px'],
        shadeClose: false,
        title: '编辑上班时间段'
      })
    },
    btn_delete(id) {
      this.$confirm('此操作将永久删除当前上班时间段, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteWorkTime(id).then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.getLists()
            this.$message.success('删除成功!')
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    btn_deletes() {
      const ids = []
      for (let i = 0, len = this.multipleSelection.length; i < len; i++) {
        ids.push(this.multipleSelection[i].F_Id)
      }
      if (ids.length <= 0) {
        this.$message.warning('没有可删除的选项')
        return
      }
      this.btn_delete(ids)
    },

    // 获取坐席组下拉数据
    getSeatGroupSelects() {
      return new Promise(resolve => {
        getSeatGroup().then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.seatOptions = response.data
          }
        })
        resolve()
      })
    }

  }

}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
	.restDay {
		padding: 15px;

		.title {
			color: #333333;
			font-size: 14px;
			margin-bottom: 10px;
			display: inline-block;
		}

		.left_area {
			font-family: "PingFang SC", "Hiragino Sans GB", "STHeiti", "Microsoft YaHei", "WenQuanYi Micro Hei", sans-serif;

			.top_time {
				margin-bottom: 10px;
			}

			.calendar_time {
				position: relative;
				height: 204px;
				color: #767677;
				font-size: 14px;

				span {
					display: inline-block;
				}

				.month1 {
					writing-mode: tb-rl;
					writing-mode: vertical-rl;
					color: #ffffff;
					height: 120px;
					font-size: 32px;
					padding: 6px;
					text-align: center;
					letter-spacing: 4px;
					background-color: #e87a78;
					position: absolute;
					left: 46px;
					top: 0;
				}

				.month2 {
					position: absolute;
					left: 110px;
					top: 16px;
				}

				.month3 {
					position: absolute;
					left: 110px;
					top: 36px;
				}

				.month4 {
					position: absolute;
					left: 110px;
					top: 53px;
				}

				.year {
					position: absolute;
					left: 70px;
					top: 124px;
				}

				.tip {
					position: absolute;
					left: 108px;
					top: 74px;
					writing-mode: tb-rl;
					writing-mode: vertical-rl;
					color: #e87a78;
					font-size: 40px;
				}

				.line1 {
					position: absolute;
					left: 25px;
					top: 120px;
					width: 50px;
					height: 50px;
					box-sizing: border-box;
					background: linear-gradient(-45deg, transparent 49.5%, #838384 49.5%, #838384 50.5%, transparent 50.5%);
				}

				.line2 {
					position: absolute;
					left: 158px;
					top: 10px;
					width: 26px;
					height: 26px;
					box-sizing: border-box;
					background: linear-gradient(-45deg, transparent 49.5%, #838384 49.5%, #838384 50.5%, transparent 50.5%);
				}

				.line3 {
					position: absolute;
					left: 160px;
					top: 72px;
					display: inline-block;
					width: 14px;
					height: 144px;
				}

				.num {
					font-size: 16px;
					font-weight: 500;
				}
			}

			.calendar_img {
				width: 100%;
				height: 204px;
			}
		}

		.del_btn {
			margin-left: 0;
			margin-top: 5px;
		}
	}

	@media only screen and (max-width: 990px) {
		.restDay {
			.calendar_img {
				display: none;
			}
		}
	}
</style>
