<template>
  <el-dialog
    :title="$t1('设置非工作日')"
    :append-to-body="true"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    :visible.sync="showDialog"
    :modal="false"
    custom-class="dialog-style list-dialog"
    @close="dialogClose"
    v-el-drag-dialog
    v-el-dialog-center
    :fullscreen="true"
  >
    <div id="containt" style="height: calc(100vh - 58px);">
      <div class="calendar">
        <div class="chose_sd star">
          <span>{{ $t1('年份') }}：</span>
          <el-date-picker v-model="year" value-format="yyyy" size="small" type="year" :placeholder="$t1('选择年')"
                          class="choseYear" @change="changeYear" @blur="changeYear" :editable="false"
                          :clearable="false"/>
          <el-checkbox v-model="choseSaturday1" @change="changeChoseSaturday1">{{ $t1('奇数日周六') }}</el-checkbox>
          <el-checkbox v-model="choseSaturday2" @change="changeChoseSaturday2">{{ $t1('偶数日周六') }}</el-checkbox>
          <el-checkbox v-model="choseSunday" @change="changeChoseSunday">{{ $t1('周日') }}</el-checkbox>

          <!--          <el-checkbox v-model="choseCheckAll" @change="changeCheckAll">全选</el-checkbox>-->
          <el-button type="primary" plain class="button-sty" @click="reset" icon="el-icon-refresh-right">
            {{ $t1('重置') }}
          </el-button>
          <el-button type="primary" class="button-sty" icon="el-icon-check" @click="saveData">{{ $t1('保存') }}
          </el-button>
        </div>
        <div class="row">
          <calendar
            v-for="(mouth,index) in mouths"
            :key="index"
            :ref="mouth"
            :mouth="mouth"
            :calendar-optiond-day="calendarOptiondDay"
            @checkedDate="checkedDate"
            @checkedAll="checkedAll"
            @selectDay="onClick"
          />
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script>
/**
 * dateList数据格式：["2019-01-05", "2019-01-06", "2019-01-12"]
 * 日期组件数据回填，需要的格式，为数组对象，如：
 * [{date: "2019-01-05",day: 6,isToday: false,row: 0,select: true,week: 6},{date: "2019-01-06",day: 6,isToday: false,row: 0,select: true,week: 6}]
 */
import Calendar from './components/calendar2'
import moment from 'moment'

export default {
  name: 'CalendarDemo',
  components: {Calendar},
  data() {
    return {
      showDialog: true,
      year: moment().format('YYYY'),
      choseWorkDay: '',
      choseCheckAll: false,
      mouths: [],
      checkedDates: [], // 最终选中的全部日期
      uncheckedDates: [], // 最终未选中的全部日期
      calendarOptiondDay: [],//选中日期数组
      allCheckDay: [],
      allSelectedDay: [],
      dayObj: {
        date: '',
        day: 6,
        isToday: false,
        row: 0,
        select: true,
        week: 6
      },
      choseSaturday1: false,
      choseSaturday2: false,
      choseSunday: false
    }
  },
  watch: {},
  mounted() {
    this.$nextTick(() => {
      this.changeYear(this.year)
    })
  },
  methods: {
    dialogClose() {
      this.showDialog = false
      this.$emit('update:visiable', false);
    },
    confirm() {
      this.dialogClose();
      this.$emit('confirm', this.year);
    },
    checkedAll(checkDayObj) {
      this.mouths.forEach(moth => {
        if (moth === checkDayObj.mouth) {
          if (checkDayObj.checkedAll === false) {
            this.choseCheckAll = false
          }
        }
      })
    },
    formatDate(time) {
      var date = new Date(time);
      var time1 = moment(date).format("YYYY");
      return time1; //年月日 格式自己定义 'yyyy : MM : dd' 例 2018年12月5日的格式
    },
    async changeYear(val) {
      if (typeof val === 'string') {
        this.year = moment(val + '').format('YYYY')
      }
      this.reset();
      await this.initWfWorkCalendar()
      this.choseWorkDay = ''

      this.choseCheckAll = false
      this.mouths = []
      for (let i = 1; i <= 12; i++) {
        if (i < 10) {
          this.mouths.push(this.year + '-' + '0' + i)
        } else {
          this.mouths.push(this.year + '-' + i)
        }
      }
    },
    onClick(day) {
      if (day.select) day.select = false
      else day.select = true
    },
    check(work, noWork) {
      // 选择工作日、非工作日、全选、全不选后，先清空选中项，再添加选中数据
      this.checkedDates = []
      this.mouths.forEach(mouth => {
        this.$refs[mouth][0].checkWork(true, work)
        this.$refs[mouth][0].checkWork(false, noWork)
      })
    },
    // 获取--最终--全部选中的数据
    checkedDate(checkDayObj) {
      if (this.allCheckDay && this.allCheckDay.length > 0) {
        const mouthObj = this.allCheckDay.findIndex((mouthDay) => mouthDay.mouth === checkDayObj.mouth)
        if (mouthObj !== -1) {
          this.allCheckDay[mouthObj].checkedDay = checkDayObj.checkedDay
          this.allCheckDay[mouthObj].uncheckedDay = checkDayObj.uncheckedDay
        } else this.allCheckDay.push(checkDayObj)
      } else this.allCheckDay.push(checkDayObj)
      this.checkedDates = []
      this.uncheckedDates = []
      this.allCheckDay.forEach(mouth => {
        this.checkedDates = [...this.checkedDates, ...mouth.checkedDay]
        this.uncheckedDates = [...this.uncheckedDates, ...mouth.uncheckedDay]
      })
      /**
       * 日期列表转化字符串
       * cDatelist为最终list，按需要转化
       * 例：["2019-01-01", "2019-01-02", "2019-01-03", "2019-01-04", "2019-01-05"]
       */
      const checkedDates = [...this.checkedDates]
      const cDatelist = []
      checkedDates.forEach(val => {
        cDatelist.push(val.date)
      })
    },

    changeChoseSaturday1(value) {
      this.checkWeekend(1, value)
    },
    changeChoseSaturday2(value) {
      this.checkWeekend(2, value)
    },
    changeChoseSunday(value) {
      this.checkWeekend(3, value)
    },
    checkWeekend(flag, value) {
      // 选择工作日、非工作日、全选、全不选后，先清空选中项，再添加选中数据
      this.checkedDates = []
      this.mouths.forEach(mouth => {
        this.$refs[mouth][0].checkWeekend(flag, value)
      })
    },

    changeWorkDay(value) {
      this.choseCheckAll = false
      if (value) {
        if (value === '工作日') {
          this.check(true, false)
        } else if (value === '非工作日') {
          this.check(false, true)
        }
      }
    },
    reset() {
      this.choseSaturday1 = false;
      this.choseSaturday2 = false;
      this.choseSunday = false;
      this.changeCheckAll(false);
    },
    changeCheckAll(value) {
      this.choseWorkDay = ''
      if (value) {
        this.check(true, true)
      } else {
        this.check(false, false)
      }
    },
    async initWfWorkCalendar() {
      this.calendarOptiondDay = [];
      // return
      let year = this.year;
      let startCalendarDate = year + '-01-01';
      let endCalendarDate = year + '-12-31';
      return this.$http({
        method: 'post',
        url: USER_PREFIX + '/wf_work_calendar/listPage',
        data: {startCalendarDate: startCalendarDate, endCalendarDate: endCalendarDate, workdays: "0"},
        success: res => {
          let rows = res && res.objx && res.objx.records ? res.objx.records : [];
          this.calendarOptiondDay = rows.map(row => {
            return {
              date: row.calendarDate
            };
          });
        }
      });
    },
    saveData() {
      if (!this.checkedDates.length) {
        this.$message({
          message: this.$t1('请选择非工作日'),
          type: 'error',
          duration: 2000
        });
        return
      }
      this.$baseConfirm(this.$t1('您确定要保存吗？')).then(() => {
        var url = USER_PREFIX + '/wf_work_calendar/save';

        let requests = [];

        this.mouths.forEach(mouth => {

          this.$refs[mouth][0].calendarDay.forEach(week => {
            week.forEach(day => {
              if (day && day.day) {
                let reqData = {
                  calendarDate: day.date,
                  workdays: day.select ? "0" : "1",
                }
                requests.push(this.$http({
                  url: url,
                  method: `post`,
                  data: reqData,
                  isLoading: true,
                  success: res => {

                  }
                }));
              }
            })
          })
        })
        if (requests.length) {
          Promise.all(requests)
            .then(responses => {
              // 所有请求都成功了
              // 处理你的数据
              /*responses.forEach(response => {
                console.log(response.data);
              });*/
              this.$message({
                message: 'success',
                type: 'success',
                duration: 2000,
                onClose: t => {

                }
              });
              this.confirm();
            })
            .catch(error => {
              // 至少一个请求失败了
              console.error('An error occurred:', error);
            });
        }
      });
    },

  }
}
</script>
<style lang="scss" scoped>
.calendar {
  .chose_sd {
    display: flex;
    flex-wrap: wrap;
    align-content: space-between;
    margin: 16px;
    line-height: 28px;
    font-size: 12px;

    > span, .button-sty {
      vertical-align: middle;
    }

    .choseYear {
      vertical-align: middle;
      margin-right: 8px;
      font-weight: 600;
      font-size: 14px;

      ::v-deep .el-input__inner {
        color: #ff8d4b;
      }
    }

    .chose_detail {
      margin-right: 5px;
      margin-left: 20px;
    }

    ::v-deep .el-radio-group {
      line-height: 28px;

      .el-radio {
        margin-bottom: 0;
        line-height: 28px;
      }

    }

    ::v-deep .el-checkbox {
      margin-bottom: 0;
      margin-left: 24px;
      margin-right: 24px;
    }
  }

  .row {
    display: flex;
    flex-wrap: wrap;
    align-content: space-between;
    justify-content: flex-start;
    margin: 5px 0;
  }
}

</style>

