<template>
  <div class="multimedia_contanier height100">
    <div class="height100" id="allhtml">
      <div v-if="data.showType == 'month'" key="1" class="zCalendar zCanlendar-day_contanier">
        <div class="zCalendar__title">
          <div class="fl" style="margin-left: 20px; text-align: center">当前日期</div>
          <div class="zCalendar-title__day">
            <span class="t">{{ dayName }}</span>
            <br />
            <span class="b">{{ weekName }}</span>
          </div>
          <div class="zCalendar-title__datebox">
            <span @click="cutMonth('prev')" class="zCalendar__prev zCalendar__btn">
              <i class="iconfont icon-Group-" aria-hidden="true"></i>
            </span>
            <h1 class="zCalendar-title__date">{{ allday }}</h1>
            <span @click="cutMonth('next')" class="zCalendar__next zCalendar__btn">
              <i class="iconfont icon-Group-3" aria-hidden="true"></i>
            </span>
            <a v-if="data.isHasAdd" class="zCalendar__next zCalendar__btn add" @click="opendialog">
              <i class="iconfont icon-Group-13" aria-hidden="true" style="color:#00"></i>
            </a>
          </div>
        </div>
        <div class="zCalendar__week flexbox">
          <span class="flex">周日</span>
          <span class="flex">周一</span>
          <span class="flex">周二</span>
          <span class="flex">周三</span>
          <span class="flex">周四</span>
          <span class="flex">周五</span>
          <span class="flex">周六</span>
        </div>
        <div class="zCalendar_days_line_contanier">
          <ul class="zCalendar__days" id="item.day">
            <li
              v-for="item in daysList"
              :key="item.day"
              class="li__item"
              @click="clickMonth($event, item)"
              :class="[item.class,  item.has]"
            >
              <span :class="item.ac">{{ item.time }}</span>
            </li>
          </ul>
          <!-- // 排班 -->
          <!-- <div class="zCalendar__rank flexbox">
          <div class="zCalendar-rank__title">排班：</div>
          <div class="flex" > {{'排版内容'}}</div>
          </div>-->
          <!-- // 排班
          // 时间线-->
          <div class="zCalendar__line flexbox font12">
            <biCalendarTimeLine :dataList="calendarTimeDatas" />
          </div>
        </div>

        <!-- // 时间线 -->
      </div>
      <!-- 周-横 -->
      <div
        v-if="data.showType == 'weekcol'"
        key="2"
        id="weekcol"
        class="zCalendar zCanlendar-week_contanier"
      >
        <div class="zCalendar__title flexbox">
          <h1 class="zCalendar-title__date flex" style="text-align: center;">{{ weekfullDay }}</h1>
          <div class="zCalendar-title__datebox">
            <a @click="cutWeek('today')">今天</a>
            <a @click="cutWeek('prev')" class="zCalendar__prev zCalendar__btn" style="width: 30px">
              <i class="iconfont icon-Group-" aria-hidden="true"></i>
            </a>
            <a @click="cutWeek('next')" class="zCalendar__next zCalendar__btn" style="width: 25px">
              <i class="iconfont icon-Group-3" aria-hidden="true"></i>
            </a>
            <a
              @click="opendialog"
              v-if="data.isHasAdd"
              class="zCalendar__next zCalendar__btn"
              style="width: 25px; font-size: 30px"
            >
              <i class="iconfont icon-Group-13" aria-hidden="true"></i>
            </a>
          </div>
        </div>
        <div
          class="zCalendar__week flexbox"
          :style="((data.viewType==1||data.viewType==2)&&calendarWeekList&&Object.keys(calendarWeekList).length>0?'padding-left:25px':'')"
        >
          <span class="flex">周一</span>
          <span class="flex">周二</span>
          <span class="flex">周三</span>
          <span class="flex">周四</span>
          <span class="flex">周五</span>
          <span class="flex">周六</span>
          <span class="flex">周日</span>
        </div>
        <ul
          :class="'zCalendar__days '+(data.viewType==1?'':'canClickItem') "
          :style="((data.viewType==1||data.viewType==2)&&calendarWeekList&&Object.keys(calendarWeekList).length>0?'padding-left:25px':'')"
          click="weekbox"
        >
          <li
            class="li__item"
            @click="clickWeekcol($event, item)"
            v-for="item in weekcolList"
            :class="[item.has]"
            :key="item.day"
          >
            <span :class="item.ac">{{ item.time }}</span>
          </li>
        </ul>
        <!-- <div class="zCalendar__rank flexbox">
            <div class="zCalendar-rank__title">排班：</div>
            <div class="flex" id="rank' + this.uuid + '"></div>
        </div>-->
        <div class="zCalendar__line font12" style="height: calc(100% - 124px)">
          <!-- 排班 -->
          <div
            v-if="(data.viewType==1||data.viewType==2) "
            class="zCalendar__line_week"
            :style="'height:'+(data.viewType==1?'100%':'60%')"
          >
            <template v-if="calendarWeekList&&Object.keys(calendarWeekList).length>0">
              <div
                class="zCalendar__line_week_item mrgl5"
                v-for="(item,index) of Object.keys(calendarWeekList)"
                :key="index"
                :style="'display:flex;height:calc(100% / '+Object.keys(calendarWeekList).length+' '"
              >
                <span class="title font12" style="width:25px">{{item}}</span>
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="cal.content"
                  placement="top"
                  v-for="(cal,i) of calendarWeekList[item]"
                  :key="i"
                >
                  <div
                    :style="'padding-left:30px;justify-content: center;display:flex;width: calc((100% - 30px) / 7);position: absolute;left:calc((100% - 30px) / 7 * '+cal.dayNum +')'"
                  >
                    <el-tag size="medium" class="eltag" :type="cal.type">{{cal.title}}</el-tag>
                  </div>
                </el-tooltip>
              </div>
            </template>
            <p v-else class="no_data height100">暂无排班数据</p>
          </div>
          <!-- 日程 -->
          <biCalendarTimeLine
            v-if="data.viewType==0||data.viewType==2"
            :style="'height:'+(data.viewType==0?'100%':'calc(40% - 10px);padding-top:10px')"
            :itemPaddingBottom="data.viewType==2?5:10"
            :dataList="calendarTimeDatas"
          />
        </div>
      </div>
      <!-- 竖排序 -->
      <div v-if="data.showType == 'weekrow'" key="3" class="height100">
        <div class="zCalendar__title flexbox">
          <input type="hidden" value="' + _date + '" />
          <h1 class="zCalendar-title__date flex" style="text-align: center">{{ beforeDate1 }}</h1>
          <div class="zCalendar-title__datebox">
            <a @click="cutWeek('prev')" class="zCalendar__prev zCalendar__btn" style="width: 25px">
              <i class="iconfont icon-Group-" aria-hidden="true"></i>
            </a>
            <a @click="cutWeek('next')" class="zCalendar__next zCalendar__btn" style="width: 25px">
              <i class="iconfont icon-Group-3" aria-hidden="true"></i>
            </a>
            <a
              v-if="data.isHasAdd"
              @click="opendialog"
              class="zCalendar__next zCalendar__btn"
              style="width: 25px; font-size: 30px"
            >
              <i class="iconfont icon-Group-13" aria-hidden="true"></i>
            </a>
          </div>
        </div>
        <div class="flexbox" style="height:calc(100% - 56px)">
          <div
            :class="'zCalendar-weekall__item '+(data.viewType==1?'':'canClickItem') "
            :style="'width:80px;'+(data.viewType==1?'padding-top:20px':'')"
          >
            <div
              v-for="item in weekRowScheduleList"
              :key="item.day"
              class="zCalendar-weekall__date"
              @click="clickWeekrow($event, item)"
            >
              <div class="b">
                <div class="d" :class="[item.ac, item.has]">
                  <span>{{ item.time }}</span>
                  {{ item.weekDay }}
                </div>
              </div>
            </div>
          </div>
          <biCalendarTimeLine
            v-if="!data.viewType||data.viewType==0"
            :isShowTitle="false"
            style="padding:10px 0"
            :dataList="calendarTimeDatas"
          />
          <template v-else-if="calendarWeekList&&Object.keys(calendarWeekList).length>0">
            <div class="zCalendar__line_week flexbox" style="width:calc(100% - 80px)">
              <div
                v-for="(item,index) of Object.keys(calendarWeekList)"
                :key="index"
                :style="'display:flex;justify-content:center;width:calc(100% / '+Object.keys(calendarWeekList).length+' '"
              >
                <span class="title font12">{{item}}</span>
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="cal.content"
                  placement="top"
                  v-for="(cal,i) of calendarWeekList[item]"
                  :key="i"
                >
                  <div
                    :style="'display:flex;position: absolute;top:calc(100% / 7 * '+cal.dayNum +' + 20px)'"
                  >
                    <el-tag size="medium" class="eltag" :type="cal.type">{{cal.title}}</el-tag>
                  </div>
                </el-tooltip>
              </div>
            </div>
          </template>
          <p v-else class="no_data height100">暂无排班数据</p>
        </div>
      </div>
      <diaLog :source="source" type="right" ref="d2">
        <div class="zCalendar-add__box flexYbox">
          <ts-form :data="formData" :rules="formRules" @submit="submitEvent" ref="xForm">
            <div class="laybox-dialog__box">
              <ts-form-item titleWidth="100px" field="title">
                <template slot="verify" slot-scope="data">
                  <ts-input
                    v-model="formData.title"
                    :title="'标 \xa0\xa0\xa0\xa0\xa0\xa0题'"
                    placeholder="请输入标题"
                    name
                    width="100%"
                    @input="$refs.xForm.updateStatus(data.scope)"
                  ></ts-input>
                </template>
              </ts-form-item>
              <ts-form-item titleWidth="60px" field="begin">
                <template slot="verify" slot-scope="data">
                  <ts-date
                    v-model="formData.begin"
                    title="开始时间"
                    type="datetime"
                    placeholder
                    width="100%"
                    @done="dateBack($event, data.scope)"
                  ></ts-date>
                </template>
              </ts-form-item>
              <ts-form-item titleWidth="60px" field="end">
                <template v-slot>
                  <ts-date
                    v-model="formData.end"
                    title="结束时间"
                    type="datetime"
                    placeholder
                    width="100%"
                    @done="dateBack2"
                  ></ts-date>
                </template>
              </ts-form-item>
              <div class="none">
                <ts-button type="submit" status="primary" ref="submit">基本表单</ts-button>
              </div>
            </div>
          </ts-form>
        </div>
      </diaLog>
    </div>
  </div>
</template>

<script>
import biCalendarTimeLine from './biCalendarTimeLine'
import _ from 'lodash'
export default {
  name: 'biCalendar',
  components: {
    biCalendarTimeLine
  },
  props: {
    isEditable: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    },
    height: {
      type: [String, Number],
      default: 0
    },
    data: {
      type: Object,
      default: () => []
    }
  },
  data() {
    return {
      source: {
        title: '添加日程', // 标题
        width: '330px', // 宽
        height: '100%', // 高
        closeBtn: false, // 关闭按钮区域，boolean 默认：false
        // 按钮
        buttons: [
          {
            text: '确认',
            event: this.submitFn
          }
          // { text: '取消',  }
        ]
      },
      formData: {
        title: '',
        rangetime: '',
        begin: '',
        end: ''
      },
      formRules: {
        title: [
          {
            required: true,
            message: '请输入标题'
          }
        ],
        rangetime: [
          {
            required: true,
            message: '请选择时间'
          }
        ],
        begin: [
          {
            required: true,
            message: '请选择开始时间'
          }
        ],
        end: [
          {
            required: true,
            message: '请选择结束时间'
          }
        ]
      },
      fixedDay: '', //周存今天那个值
      weekDay: '', //周点击的日期2020-12-12
      fullDay: '', //变化的月的 来判断上月下月
      monthDay: '', //月点击的那个值
      weekfullDay: '', //横盘显示周 的日期 2020年12月12日
      weekName: '',
      dayName: '',
      daysList: [],
      allday: '', //2020年12月
      weekcolList: [],
      weekrowList: [],
      initdate: '',
      beforeDate1: '',
      week: '',
      calendarWeekList: this.isEditable
        ? {
            上午: [
              {
                title: '门诊',
                dayNum: 4,
                type: 'warning',
                content: '备注',
                timeType: '上午'
              },
              {
                title: '临床',
                dayNum: 0,
                type: 'success',
                content: '备注'
              },
              {
                title: '临床',
                dayNum: 5,
                type: 'success',
                content: '备注'
              },
              {
                title: '临床',
                dayNum: 1,
                type: 'success',
                content: '备注'
              },
              {
                title: '门诊',
                dayNum: 2,
                type: 'warning',
                content: '备注'
              }
            ],
            午间: [
              {
                title: '门诊',
                dayNum: 4,
                type: 'warning',
                content: '备注'
              },
              {
                title: '临床',
                dayNum: 0,
                type: 'success',
                content: '备注'
              },
              {
                title: '临床',
                dayNum: 5,
                type: 'success',
                content: '备注'
              },
              {
                title: '临床',
                dayNum: 1,
                type: 'success',
                content: '备注'
              },
              {
                title: '门诊',
                dayNum: 2,
                type: 'warning',
                content: '备注'
              }
            ],
            下午: [
              {
                title: '临床',
                dayNum: 3,
                type: 'success',
                content: '备注'
              },
              {
                title: '门诊',
                dayNum: 4,
                type: 'warning',
                content: '备注'
              },
              {
                title: '临床',
                dayNum: 0,
                type: 'success',
                content: '备注'
              }
            ],
            晚间: [
              {
                title: '晚班',
                dayNum: 1,
                content: '备注'
              },
              {
                title: '晚班',
                dayNum: 5,
                content: '备注'
              }
            ]
          }
        : this.data.weekDataList
    }
  },
  computed: {
    calendarTimeDatas() {
      return this.isEditable
        ? [
            {
              time: '21:00~22:00',
              content: '行程内容'
            },
            {
              time: '21:00~22:00',
              content: '行程内容'
            },
            {
              time: '21:00~22:00',
              content: '行程内容'
            },
            {
              time: '21:00~22:00',
              content: '行程内容'
            }
          ]
        : this.data.dayDataList
    },
    scheduleList() {
      let list = [{}, {}]
      // this.data.dataList.forEach((res) => {
      //   let nowdate = this.monthDay + ' 00:00:00'
      //   let lastdate = this.monthDay + ' 23:59:59'
      //   if (res.rangetime) {
      //     let dateList = res.rangetime.split(' ~ ')
      //     let a = new Date(dateList[0]).getTime()
      //     let b = new Date(nowdate).getTime()
      //     let c = new Date(dateList[1]).getTime()
      //     if (
      //       (new Date(dateList[0]).getTime() <= new Date(nowdate).getTime() &&
      //         new Date(nowdate).getTime() <= new Date(dateList[1]).getTime()) ||
      //       (new Date(dateList[0]).getTime() <= new Date(lastdate).getTime() &&
      //         new Date(lastdate).getTime() <=
      //           new Date(dateList[1]).getTime()) ||
      //       (new Date(dateList[0]).getTime() >= new Date(nowdate).getTime() &&
      //         new Date(dateList[1]).getTime() <= new Date(lastdate).getTime())
      //     ) {
      //       list.push(res)
      //     }
      //   }
      // })
      return list
    },
    weekScheduleList() {
      let list = [{}, {}]
      // this.data.dataList.forEach((res) => {
      //   let nowdate = this.weekDay + ' 00:00:00'
      //   let lastdate = this.weekDay + ' 23:59:59'
      //   if (res.rangetime) {
      //     let dateList = res.rangetime.split(' ~ ')
      //     let a = new Date(dateList[0]).getTime()
      //     let b = new Date(nowdate).getTime()
      //     let c = new Date(dateList[1]).getTime()
      //     if (
      //       (new Date(dateList[0]).getTime() <= new Date(nowdate).getTime() &&
      //         new Date(nowdate).getTime() <= new Date(dateList[1]).getTime()) ||
      //       (new Date(dateList[0]).getTime() <= new Date(lastdate).getTime() &&
      //         new Date(lastdate).getTime() <=
      //           new Date(dateList[1]).getTime()) ||
      //       (new Date(dateList[0]).getTime() >= new Date(nowdate).getTime() &&
      //         new Date(dateList[1]).getTime() <= new Date(lastdate).getTime())
      //     ) {
      //       list.push(res)
      //     }
      //   }
      // })
      return list
    },
    weekRowScheduleList() {
      // if (this.data.dataList.length == 0 && this.data.showType == 'weekrow') {
      //   return this.weekrowList
      // } else {
      let list = []
      let bigList = JSON.parse(JSON.stringify(this.weekrowList))
      for (let day of bigList) {
        list = [{}, {}]
        // for (let res of this.data.dataList) {
        //   let nowdate = day.day + ' 00:00:00'
        //   let lastdate = day.day + ' 23:59:59'
        //   if (res.rangetime) {
        //     let dateList = res.rangetime.split(' ~ ')
        //     let a = new Date(dateList[0]).getTime()
        //     let b = new Date(nowdate).getTime()
        //     let c = new Date(dateList[1]).getTime()
        //     if (
        //       (new Date(dateList[0]).getTime() <=
        //         new Date(nowdate).getTime() &&
        //         new Date(nowdate).getTime() <=
        //           new Date(dateList[1]).getTime()) ||
        //       (new Date(dateList[0]).getTime() <=
        //         new Date(lastdate).getTime() &&
        //         new Date(lastdate).getTime() <=
        //           new Date(dateList[1]).getTime()) ||
        //       (new Date(dateList[0]).getTime() >=
        //         new Date(nowdate).getTime() &&
        //         new Date(dateList[1]).getTime() <=
        //           new Date(lastdate).getTime())
        //     ) {
        //       list.push(res)
        //     }
        //   }
        // }
        day.list = list
      }
      return bigList
      // }
    }
  },

  created() {},
  mounted() {
    this.initSquare()
    this.day7html()
  },
  methods: {
    submitFn() {
      this.$refs.xForm.submit()
      // this.$refs.submit.$el.click()
    },
    opendialog() {
      this.formData.title = ''
      if (this.data.showType == 'month') {
        this.formData.rangetime =
          this.monthDay + ' 00:00:00 ~ ' + this.monthDay + ' 23:59:59'
        this.formData.begin = this.monthDay + ' 00:00:00'
        this.formData.end = this.monthDay + ' 23:59:59'
      } else {
        this.formData.rangetime =
          this.weekDay + ' 00:00:00 ~ ' + this.weekDay + ' 23:59:59'
        this.formData.begin = this.weekDay + ' 00:00:00'
        this.formData.end = this.weekDay + ' 23:59:59'
      }
      this.formData.id = this.$utils.uuid(16)
      this.$refs.d2.open()
      this.$refs.xForm.clearValidate('title')
    },
    updateSchedule(item) {
      this.source.title = '修改日程'
      this.$refs.d2.open()
      this.formData.title = item.title
      this.formData.rangetime = item.rangetime
      this.formData.begin = item.begin
      this.formData.end = item.end

      this.formData.id = item.id
    },
    delSchedule(item) {
      this.$XModal.confirm('您确定要删除该日程吗？').then(type => {
        if (type == 'confirm' && this.data.dataList) {
          let index = this.data.dataList.findIndex(res => res.id == item.id)
          this.data.dataList.splice(index, 1)
        }
        // this.$api({
        //   url:'/ts-system/api/datasource/delete/' + d.id,
        //   method: 'post'
        // }).then(function(resp) {
        //   if (resp.success) {
        //     self.$refs.thpsDataSourceTableInst.refresh()
        //    self.$utils.msg(self, '操作成功！', 'success')
        //     self.closeHandler()
        //   } else {
        //       self.$utils.msg(self,resp.message || '操作失败.', 'error')
        //   }
        // })
        // .catch(function(error) {
        //   self.$utils.msg(self,error.message || '系统异常.', 'error')
        // })
        // }
      })
    },

    daysListHas(list) {
      let _this = this
      for (let res of _this.data.dataList) {
        if (res.rangetime) {
          for (let ev of list) {
            let nowdate = ev.day + ' 00:00:00'
            let lastdate = ev.day + ' 23:59:59'
            let dateList = res.rangetime.split(' ~ ')
            if (
              (new Date(dateList[0]).getTime() <= new Date(nowdate).getTime() &&
                new Date(nowdate).getTime() <=
                  new Date(dateList[1]).getTime()) ||
              (new Date(dateList[0]).getTime() <=
                new Date(lastdate).getTime() &&
                new Date(lastdate).getTime() <=
                  new Date(dateList[1]).getTime()) ||
              (new Date(dateList[0]).getTime() >= new Date(nowdate).getTime() &&
                new Date(dateList[1]).getTime() <= new Date(lastdate).getTime())
            ) {
              ev.has = 'redsign'
            }
          }
        }
      }
    },
    dateBack(o, data) {
      this.$refs.xForm.updateStatus(data)
      if (this.formData.rangetime) {
        let dataArr = this.formData.rangetime.split(' ~ ')
        this.formData.rangetime = o + ' ~ ' + dataArr[1]
      }
    }, //时间回调
    dateBack2(o) {
      if (this.formData.rangetime) {
        let dataArr = this.formData.rangetime.split(' ~ ')
        this.formData.rangetime = dataArr[0] + ' ~ ' + o
      }
    },
    // 点击月事件
    clickMonth(event, item) {
      this.daysList.forEach(res => (res.ac = ''))
      item.ac = 'active'
      let dayList = item.day.split('-')
      this.weekName = this.formatterDay(
        this.getDay(dayList[0], dayList[1] - 1, dayList[2])
      )
      this.dayName = item.time
      this.monthDay = item.day
    },
    // 点击横排周
    clickWeekcol(event, item) {
      if (this.data.viewType == 1) {
        // 排班
        return
      }
      this.weekcolList.forEach(res => {
        res.ac = ''
      })
      let _datearr = item.day.split('-')
      item.ac = 'active'
      this.weekfullDay =
        _datearr[0] + '年' + _datearr[1] + '月' + _datearr[2] + '日'
      this.weekDay = _datearr[0] + '-' + _datearr[1] + '-' + _datearr[2]
      this.monthDay = item.day
    },
    //点击竖排周
    clickWeekrow(event, item) {
      if (this.data.viewType == 1) {
        // 排班
        return
      }
      this.weekrowList.forEach(res => {
        res.ac = ''
        if (item.day == res.day) {
          res.ac = 'active'
        }
      })
    },
    ///按月
    initSquare() {
      var date = new Date()
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      var d = date.getDate()
      if (this.monthDay) {
        let dayarr = this.monthDay.split('-')
        y = dayarr[0]
        m = dayarr[1]
        d = dayarr[2]
      }
      var _m = m < 10 ? '0' + m : m
      var _d = d < 10 ? '0' + d : d
      var _date = this.monthDay || y + '-' + _m + '-' + _d
      var uuid = '212'
      this.daysList = []
      if (this.monthDay) {
      } else {
      }
      this.monthDay = _date
      var _prevMDH = this.daysH(y, m, d, _date, 'prev') // 上月html
      var _nowMDH = this.daysH(y, m, d, _date, 'now') // 当前月html
      var _nextMDH = this.daysH(y, m, d, _date, 'next') // 下月html
      this.weekName =
        this.weekName || this.formatterDay(this.getDay(y, m - 1, _d))
      this.dayName = this.dayName || _d
      this.fullDay = _date
      this.allday = this.allday || y + '年' + m + '月'
    },
    updateInitSquare() {},
    cutMonth(type) {
      var date = new Date(this.fullDay)
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      var _y = y
      var _m = m
      if (type == 'next') {
        m++
        if (m > 12) {
          m = 1
          y++
        }
      } else if (type == 'prev') {
        m--
        if (m < 1) {
          m = 12
          y--
        }
      }
      this.fullDay = y + '-' + m + '-' + '01'
      this.allday = y + '年' + m + '月'
      this.daysList = []
      this.dateList(y, m, 1, this.allday)
    },
    dateList(y, m, d, date) {
      var _prevMDH = this.daysH(y, m, d, date, 'prev') // 上月html
      var _nowMDH = this.daysH(y, m, d, date, 'now') // 当前月html
      var _nextMDH = this.daysH(y, m, d, date, 'next') // 下月html
    },
    daysH(y, m, d, _date, type) {
      var h = ''
      var _class = ''
      var week = 0
      var _y = y
      var _m = m
      var num = 0
      var nowDate
      if (type == 'prev') {
        // 上月
        if (m - 1 > 0) {
          _m = m - 1
        } else {
          _m = 12
          _y--
        }
        num = this.days(_y, _m) // 上月天数
        if (m - 2 > -1) {
          m = m - 2
        } else {
          m = 11
          y--
        }
        week = this.getDay(y, m, num)
        if (week == 6) {
          week = num
        } else {
          week = num - week - 1
        }
        _class = 'prev'
      } else if (type == 'next') {
        // 下月
        if (m + 1 > 12) {
          _m = 1
          _y++
        } else {
          _m = m + 1
        }
        num = this.days(_y, _m) // 下月天数
        if (m > 11) {
          m = 0
          y++
        }
        week = this.getDay(y, m, '01')
        if (week > 0) {
          num = 7 - week
          _class = 'next'
          week = 0
        } else {
          num = 0
        }
      } else {
        num = this.days(y, m) // 当前月天数
      }
      // var _d = formatterDateDay(this.data, this.obj.dateApi.dateName);
      for (var i = week; i < num; i++) {
        var n = i + 1
        n = n < 10 ? '0' + n : n
        _m = _m < 10 ? '0' + parseInt(_m) : _m
        var date = _y + '-' + _m + '-' + n
        let ac = ''
        var has = ''
        if (date == this.monthDay) {
          ac = 'active'
        }
        this.daysList.push({
          time: n,
          day: date,
          ac: ac,
          class: _class,
          has: has
        })
        //    <li class="li__item ' + _class + ' ' + ac + ' ' + has + '" type="' + _class + '" date="' + date + '"><span>' + n + '</span></li>'
      }
      if (this.data.dataList && this.data.dataList.length > 0) {
        this.daysListHas(this.daysList)
      }
      return h
    },
    // 周几
    getDay(year, month, date) {
      month = parseInt(month)
      year = parseInt(year)
      date = parseInt(date)
      var d = new Date(year, month, date)
      return d.getDay()
    },
    // 周格式化
    formatterDay(i) {
      var arr = [
        '星期日',
        '星期一',
        '星期二',
        '星期三',
        '星期四',
        '星期五',
        '星期六'
      ]
      return arr[i]
    },
    // 获取月天数
    days(y, m) {
      var d = new Date(y, m, 0)
      return d.getDate()
    },
    // 显示7天日期
    day7html(w) {
      var date = new Date()
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      var d = date.getDate()
      var _m = m < 10 ? '0' + m : m
      var _d = d < 10 ? '0' + d : d
      var _date = y + '-' + _m + '-' + _d
      if (this.weekDay) {
        let dayarr = this.weekDay.split('-')
        y = dayarr[0]
        m = dayarr[1]
        d = dayarr[2]
        _date = this.weekDay
      }
      this.weekDay = this.weekDay || _date
      this.fixedDay = this.fixedDay || _date
      this.weekfullDay = this.weekfullDay || y + '年' + _m + '月' + _d + '日'
      var week = this.getDay(y, m - 1, d)
      var days = this.days7H(y, m, d, _date)
      this.week = this.week || week //记录周几
    },
    // 一周日期
    days7H(y, m, d, _date) {
      this.weekcolList = []
      this.weekrowList = []
      var h = ''
      var _class = ''
      var week = 0
      var _y = y
      var _m = m
      var nowDate
      var week = this.getDay(y, m - 1, d)
      week = week == 0 ? 7 : week
      var initdate = this.beforeDate(_date, week - 1, -1)
      this.initdate = initdate

      this.beforeDate1 = initdate + '~' + this.beforeDate(_date, 7 - week, 1)

      for (var i = 0; i < 7; i++) {
        var date = this.beforeDate(initdate, i, 1)
        var n = date.split('-')[2]
        var ac = ''
        var _i = i + 1
        _i = _i == 7 ? 0 : _i
        if (date == this.weekDay) {
          ac = 'active'
        }
        var has = ''
        if (this.data.showType == 'weekrow') {
          this.weekrowList.push({
            ac: ac,
            time: n,
            has: has,
            day: date,
            weekDay: this.formatterDay(_i)
          })
        } else {
          this.weekcolList.push({
            ac: ac,
            has: has,
            time: n,
            day: date
          })
        }
      }
      if (this.data.dataList && this.data.dataList.length > 0) {
        this.daysListHas(this.weekcolList)
      }
      return h
    },
    // 切换周
    cutWeek(type) {
      var date = new Date(this.initdate)
      var _type = -1
      var num = 7
      var _date = this.beforeDate(date, 7, -1)
      if (type == 'prev') {
        _type = -1
        num = 1
      } else if (type == 'next') {
        _type = 1
        num = 7
      } else if (type == 'today') {
        _type = 1
        num = 7 - this.week
        let _datearr = this.fixedDay.split('-')
        this.weekfullDay =
          _datearr[0] + '年' + _datearr[1] + '月' + _datearr[2] + '日'
        this.weekDay = _datearr[0] + '-' + _datearr[1] + '-' + _datearr[2]
        date = new Date(this.fixedDay)
      }
      _date = this.beforeDate(date, num, _type)
      // var wd = this.beforeDate(_date, 7 - this.week, -1)
      var wd = _date
      var _tdate = new Date(wd)
      var y = _tdate.getFullYear()
      var m = _tdate.getMonth() + 1
      var d = _tdate.getDate()
      var days = this.days7H(y, m, d, wd)
      var _datearr = wd.split('-')
      if (this.data.showType == 'weekrow') {
        this.beforeDate1 = _date + '~' + this.beforeDate(_date, 6, 1)
      } else {
        // this.weekfullDay = _datearr[0] + '年' + _datearr[1] + '月' + _datearr[2] + '日'
      }
    },
    // 相隔n天日期
    beforeDate(date, days, type) {
      if (days == undefined || days == '') {
        days = 0
      }
      date = date ? new Date(date) : new Date()
      if (type == -1) {
        date.setDate(date.getDate() - days)
      } else {
        date.setDate(date.getDate() + days)
      }
      var month = date.getMonth() + 1
      var day = date.getDate()

      function getFormatDate(arg) {
        if (arg == undefined || arg == '') {
          return ''
        }
        var re = arg + ''
        if (re.length < 2) {
          re = '0' + re
        }
        return re
      }
      return (
        date.getFullYear() +
        '-' +
        getFormatDate(month) +
        '-' +
        getFormatDate(day)
      )
    },
    // 刷新数据
    async refreshData(item, type) {
      let parameters = []
      parameters = this.getCanlendarParameter(
        {
          ...this.data
        },
        []
      )
      const resp = await this.reqDS(item, parameters)
      // 成功
      if (resp && resp.success != false) {
        this.initCalendarData(item, resp, type)
        this.$forceUpdate()
      }
    },
    // 处理日程数据
    initCalendarData(item, response, type) {
      let respData = null
      if (item.dsType == '1') {
        // 手输url
        if (item.resNode) {
          // 取节点
          respData = response
          for (let node of item.resNode.split('.')) {
            respData = respData[node]
          }
        } else {
          respData = response.rows || response.object || []
        }
      } else if (!response.success) {
        console.warn(response.errMsg)
        // _this.$utils.msg(
        //   _this,
        //   response.errMsg || '预览请求失败，请检查参数值是否完整',
        //   'error'
        // )
      } else {
        respData = response.rows || response.object || []
      }
      if (respData && respData.length == 0) {
        if (type == 'day') {
          this.data.dayDataList = []
        } else {
          this.data.weekDataList = {}
          this.calendarWeekList = {}
        }
        return
      }
      let typeList = ['success', 'warning', 'info', 'error']
      let typeObj = {}
      for (let da of respData) {
        if (type == 'day') {
          // 日视图
          this.data.dayDataList.push({
            time: da[item.dayTime],
            content: da[item.dayContent]
          })
        } else if (type == 'week') {
          // 周视图
          let key = da[item.timeType]
          let dayNum = da[item.dayNum]
          let title = da[item.title]
          if (!this.data.weekDataList) {
            this.data.weekDataList = {}
          }
          if (!this.data.weekDataList[key]) {
            this.data.weekDataList[key] = []
          }
          if (!typeObj[title]) {
            typeObj[title] = typeList[Object.keys(typeObj).length % 4]
          }
          this.data.weekDataList[key].push({
            title: title,
            dayNum: dayNum,
            type: typeObj[title],
            content: da[this.data.weekDSData.content]
          })
        }
      }
      this.calendarWeekList = { ...this.data.weekDataList }
    },
    // 得到日程参数
    getCanlendarParameter(item, parameters) {
      if ((!item.viewType || item.viewType != '1') && item.dateParam) {
        // 日视图
        parameters.push({
          name: item.dateParam,
          value: this.monthDay + ' 00:00:00'
        })
      }
      if (
        item.viewType &&
        item.viewType != '0' &&
        Object.keys(item.weekDSData).length > 0
      ) {
        // 周视图
        parameters.push({
          name: item.weekDSData.startDate,
          value: this.beforeDate1.split('~')[0] + ' 00:00:00'
        })
        parameters.push({
          name: item.weekDSData.endDate,
          value: this.beforeDate1.split('~')[1] + ' 23:59:59'
        })
      }
      return parameters
    },
    // 提交日程--访问真是URL
    async submitEvent(e) {
      const _this = this
      if (this.isEditable) {
        _this.$refs.d2.close()
        return
      }
      let formdata = JSON.parse(JSON.stringify(this.formData))
      let url = ''
      let parameters = []
      parameters.push({
        name: this.data.addDSData.title,
        value: formdata.title
      })
      parameters.push({
        name: this.data.addDSData.stateDate,
        value: formdata.begin
      })
      parameters.push({
        name: this.data.addDSData.endDate,
        value: formdata.end
      })
      const resp = await this.reqDS(this.data.addDSData, parameters)
      if (resp.success != false) {
        this.$refs.d2.close()
        this.refreshData(
          {
            ...this.data
          },
          'day'
        )
        this.refreshData(
          {
            ...this.data.weekDSData
          },
          'week'
        )
        this.$utils.msg(this, '操作成功', 'success')
      }
    },
    // 访问服务器，包括自定义服务和URL两种方式
    reqDS(itemData, parameters) {
      let url = ''
      const _this = this
      // 自定义服务
      if (!itemData.dsType || itemData.dsType == '0') {
        if (!itemData.dataSourceId) {
          return
        }
        let isResult =
          (itemData.dataSource && itemData.dataSource.serviceType == 2) ||
          (itemData.dataSourceDataResult &&
            itemData.dataSourceDataResult.length) ||
          (itemData.selectDataSourceResultData &&
            itemData.selectDataSourceResultData.length)
        url = !isResult
          ? '/ts-query/api/user/query/table/query'
          : '/ts-query/api/user/query/procFun/query'
        return new Promise(resolve => {
          this.$api({
            method: 'post',
            url: url,
            data: {
              id: itemData.dataSourceId,
              pageSize: 3000,
              pageNo: 1,
              parameters: JSON.stringify(parameters)
            },
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
            }
          })
            .then(function(resp) {
              if (resp.success) {
                resolve(resp)
              } else {
                _this.$utils.msg(_this, resp.errMsg || '操作失败', 'error')
                resolve({
                  success: false
                })
              }
            })
            .catch(function(error) {
              resolve({
                success: false
              })
              _this.$utils.msg(_this, error.errMsg || '系统异常', 'error')
            })
        }).catch(error => {
          resolve({
            success: false
          })
          _this.$utils.msg(_this, resp.errMsg || '系统异常', 'error')
        })
      } else {
        if (!this.data.addDSData || !this.data.addDSData.reqUrl) {
          return
        }
        let data = {}
        if (parameters && parameters.length > 0) {
          for (let param of parameters) {
            data[param.name] = param.value
          }
        }
        return new Promise(resolve => {
          // URL
          this.$api({
            method: this.data.addDSData.reqType,
            url: this.data.addDSData.reqUrl,
            data: data,
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
            }
          })
            .then(function(resp) {
              resolve(resp)
            })
            .catch(function(error) {
              resolve({
                success: false
              })
              _this.$utils.msg(_this, error.message || '系统异常', 'error')
            })
        }).catch(error => {
          resolve({
            success: false
          })
        })
      }
    }
  },
  watch: {
    data: {
      handler(n, o) {
        if (
          this.isEditable &&
          (this.data.showType == 'weekcol' || this.data.showType == 'weekrow')
        ) {
          this.day7html()
        } else {
          // this.updateInitSquare()
          // this.initSquare()
        }
      },
      deep: true
    },
    // isEditable: {
    //   handler(n) {
    //     // this.initSquare()
    //   },
    //   deep: true
    // },
    monthDay: {
      handler(n, o) {
        if (
          (!this.data.viewType || this.data.viewType != '1') &&
          !this.isEditable
        ) {
          this.data.dayDataList = []
          this.refreshData(
            {
              ...this.data
            },
            'day'
          )
        }
      },
      deep: true
    },
    beforeDate1: {
      handler(n, o) {
        if (
          this.data.viewType &&
          this.data.viewType != '0' &&
          Object.keys(this.data.weekDSData).length > 0 &&
          !this.isEditable
        ) {
          this.data.weekDataList = {}
          this.refreshData(
            {
              ...this.data.weekDSData
            },
            'week'
          )
        }
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
/* z */
.zCalendar__rank {
  font-size: 12px;
}

.zCalendar-timeline__btnbox {
  min-width: 40px;
  height: 100%;
}

// #allhtml {
//   width: 100%;
//   --base-color: #3b72dc;
//   border: solid #ccc 1px;
//   border-radius: 4px;
//   box-sizing: border-box;
//   /* background: brown; */
// }

/* .zCalendar-add__boxFlex{margin:30px 60px 0 50px} */
.zCalendar-rank__title {
  padding: 0 5px;
  line-height: 26px;
}

.zCalendar {
  height: 100%;
  // min-height: 260px;
  background-color: #ffffff;
  font-size: 12px;
}

.zCalendar-title__today {
  width: 25px;
  height: 25px;
  display: inline-block;
  border-radius: 100%;
}

.zCalendar-weekall__item {
  border-bottom: 1px #f7f7f7 solid;
  margin: 0 5px;
  padding: 5px 0;
  height: 100%;

  .zCalendar-weekall__date {
    text-align: center;
    padding: 0px 2px;
    font-size: 12px;
    height: calc(100% / 7);

    .b {
      display: flex;
      align-items: top;

      // height: 100%;
      .d {
        width: 70px;
        text-align: left;
      }

      .w {
        width: calc(100% - 80px);
        height: 35px;
        overflow-x: auto;
        overflow-y: hidden;
        text-align: left;
      }
    }
  }
}

.eltag {
  margin: 0 4px 2px 4px;
  cursor: pointer;
}

.zCalendar:after {
  content: '';
  display: block;
  clear: both;
}

.zCalendar__title {
  height: 45px;
  line-height: 45px;
  overflow: hidden;
  border-bottom: 1px #f7f7f7 solid;
}

.zCalendar__btn {
  width: 25px;
  height: 45px;
  cursor: pointer;
  display: inline-block;
  text-align: center;
  font-size: 24px;
}

.zCalendar-title__day {
  width: 70px;
  text-align: center;
  float: left;
  line-height: 1.2;
  padding-top: 10px;

  .t {
    font-size: 15px;
    font-weight: bold;
    color: var(--button_color);
  }
}

.zCalendar-title__datebox {
  float: right;
  .add i{
    color:var(--button_color) !important;
    font-size:24px;
    font-weight: 500;
    margin-left:-10px;
    &:hover{
      color:#333 !important
    }
  }
}

.zCalendar-title__date {
  font-size: 12px;
  text-align: center;
  display: inline-block;
  line-height: 30px;
}

.zCalendar__week {
  height: 35px;
  line-height: 35px;
  font-size: 12px;

  span {
    height: 35px;
    display: block;
    text-align: center;
  }
}

.zCalendar__days {
  li {
    width: calc(100% / 7);
    height: 100%;
    float: left;
    text-align: center;
  }

  span {
    width: 100%;
    height: 100%;
    // display: flex;
    // align-items: center;
    // justify-content: center;
    // line-height: 100%;
    border-radius: 100%;
    margin-top: 3px;
    color: var(--base-black);
    position: relative;
  }

  font-size: 12px;
}

.zCalendar__days:after {
  content: '';
  display: block;
  clear: both;
}
.canClickItem {
  span {
    cursor: pointer;
  }
  span:hover {
    background: var(--light-back-grey);
    color: var(--button_color);
  }
}

.zCalendar__days .active {
  background-color: var(--button_color) !important;
  color: #ffffff !important;
  padding: 8px;
}

.zCanlendar-day_contanier {
  .zCalendar__days {
    height: 65%;

    li {
      width: calc(100% / 7);
      height: calc(100% / 6);
    }
  }
}

.zCanlendar-week_contanier {
  .zCalendar__days {
    height: 40px;

    li {
      height: 35px;
      float: left;
      line-height: 35px;
      text-align: center;
    }
  }
}

.zCalendar_days_line_contanier {
  height: calc(100% - 81px);
}

.b .active span {
  background-color: var(--button_color);
  color: #ffffff !important;
  // padding: 4px 0;
}

// .b .redsign span:after {
//   content: '';
//   width: 5px;
//   height: 5px;
//   display: block;
//   background-color: #ff0000;
//   border-radius: 50%;
//   position: absolute;
//   top: 2px;
//   right: -2px;
// }
.d span {
  text-align: center;
  width: 100%;
  max-width: 29px;
  // height: 29px;
  display: inline-block;
  // line-height: 29px;
  border-radius: 100%;
  margin-top: 3px;
  color: var(--base-black);
  position: relative;
}

.zCalendar__days .prev span,
.zCalendar__days .next span {
  color: #cccccc;
}

.zCalendar__days .redsign span:after {
  content: '';
  width: 5px;
  height: 5px;
  display: block;
  background-color: #ff0000;
  border-radius: 50%;
  position: absolute;
  top: 2px;
  right: -2px;
}

.zCalendar__line_week {
  width: 100%;
}

.zCalendar__line {
  position: relative;
  height: 35%;
  overflow: hidden;
  overflow-y: auto;

  .zCalendar__line_week_item {
    width: 100%;

    .title {
      height: 28px;
      line-height: 26px;
    }
  }
}

.el-tag {
  padding: 0 3px;
}

.zCalendar-add__box {
  width: 325px;
  min-height: 150px;
  background-color: #fff;
  transition: all.3s;
  -webkit-transition: all.3s;
  -ms-transition: all.3s;
  -moz-transition: all.3s;
  -o-transition: all.3s;
}

.laybox-dialog__box {
  position: relative;
}

.zCalendar-add__title {
  padding: 10px;
  border-bottom: 1px#eeeeee solid;
}

.zCalendar-add__item {
  margin-top: 5px;
}

.zCalendar-add__label {
  width: 60px;
  line-height: 30px;
  text-align: right;
  padding-right: 10px;
}

.zCalendar-add__con {
  padding-right: 10px;
}

.layui-timeline {
  margin-top: 5px;
  height: calc(100% - 5px);
  width: calc(100% - 50px);
  overflow: auto;
}

.zCalendar.layui-timeline-item:before {
  height: calc(100% - 15px);
  top: 18px;
  z-index: 11;
}

.zCalendar.shell-ui-timeline {
  margin-right: 50px;
}

.zCalendar-timeline__btnbox {
  min-width: 60px;
  height: 100%;
}

a.zCalendar-timeline__del {
  width: 30px;
  height: 30px;
  display: none;
  text-align: center;
  line-height: 30px;
  font-size: 16px;
  color: #999999 !important;
}

a.zCalendar-timeline__del:hover {
  color: var(--button_color) !important;
}

.zCalendar__line .layui-timeline-item:hover a.zCalendar-timeline__del {
  display: inline-block;
}

.zCalendar__line.layui-timeline-item:hover.zCalendar-timeline__del {
  display: inline-block;
}

/* .zCalendar-line__title{margin: 0 0 0 20px; padding: 0 5px 5px;} */
/* .zCalendar-add__boxFlex{margin:30px 60px 0 50px} */
</style>
