<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-09-18 15:25:12
 * @LastEditors  : 无尘
 * @LastEditTime : 2019-12-21 17:22:15
 -->

<template>
  <div class="app-detail-wrap">
    <div class="work-time border-box">
      <common-detail-top :topMenuData="topMenuData" :activeId="activeId"></common-detail-top>
      <div class="work-time-content border-box">
        <div class="classes-wrap m-b-20">
          <span class="fl font-13 color-303133">班次说明：</span>
          <div class="class-row-tags">
            <div :class="['class-tag', pIndex % 7 == 0 ? 'day-tag-blue' : '', pIndex % 7 == 1 ? 'day-tag-red' : '', pIndex % 7 == 2 ? 'day-tag-purple' : '', pIndex % 7 == 3 ? 'day-tag-orange' : '', pIndex % 7 == 4 ? 'day-tag-green' : '', pIndex % 7 == 5 ? 'day-tag-pink' : '', pIndex % 7 == 6 ? 'day-tag-cyan' : '']" v-for="(pItem, pIndex) in classes" :key="pIndex">
              <span class="class-tag-text">班次{{ pItem.classesName }}：</span>
              <span v-for="(item, index) in pItem.classess" :key="index + 'time'">{{ item.startTime }}-{{ item.endTime }}</span>
            </div>
            <div class="schedule-content_tag">
              <div class="class-tag">
                <span class="class-tag-text">休息: 休息</span>
              </div>
            </div>
            <div class="schedule-content_tag">
              <div class="class-tag"><span class="class-tag-text">清空: 休息</span></div>
            </div>
          </div>
        </div>
        <div class="range-wrap m-b-20">
          <span class="fl font-13 color-303133">排班周期：</span>
          <div class="class-row-tags">
            <div class="class-tag" v-for="(item, index) in cycleData" :key="index + 'cycle'">
              <span class="ant-tag-text">{{ item.rangeName }}：</span>
              <span>{{ item.classesList.map(ele => ele.classesName).join('-') }}</span>
            </div>
            <el-button type="text" @click="toWorkGroup">设置</el-button>
          </div>
        </div>
        <div class="work-time-opt m-b-20 flex flex-space-between">
          <div class="work-time-opt_left">
            <el-date-picker v-model="yearMonth" type="month" format="yyyy-MM" placeholder="选择月" @change="changeMonth"> </el-date-picker>
            <span class="p-l-10 font-12 color-606266">未排班时，员工可选择班次打卡</span>
          </div>
          <div class="work-time-opt_right">
            <el-button type="primary" @click="toSave">保存</el-button>
            <el-button @click="toReset">恢复</el-button>
          </div>
        </div>
        <div class="work-time-table">
          <el-table class="select-table" border ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: calc(100% - 20px);">
            <el-table-column prop="" show-overflow-tooltip fixed :resizable="false">
              <template slot="header" slot-scope="scope">
                姓名
              </template>
              <template slot-scope="scope">
                <div class="row-username">
                  {{ scope.row.userName }}
                  <!-- 设置该员工当月所有班次 -->
                  <!-- <el-popover placement="bottom" width="231" trigger="click">
                  <div class="tool-tip-body" slot="reference">
                    <el-tooltip class="item" effect="dark" :content="scope.row.user.name" placement="top-start">
                      <p>{{ scope.row.user.name }}</p>
                    </el-tooltip>
                  </div>
                </el-popover> -->
                </div>
              </template>
            </el-table-column>
            <template v-for="(item, index) in dates">
              <el-table-column prop="" show-overflow-tooltip :key="index + 'thead'" :resizable="false">
                <template slot="header" slot-scope="scope">
                  <div :class="['text-center', item.dayOfWeek == '六' || item.dayOfWeek == '日' ? 'color-red' : '']">
                    {{ item.weekDay ? parseInt(item.weekDay.split('-')[2]) : '' }} <br />
                    {{ item.dayOfWeek }}
                  </div>
                </template>
                <template slot-scope="scope">
                  <div class="day-work">
                    <el-popover placement="bottom" width="231" trigger="click">
                      <!-- 当前员工当天排版设置 -->
                      <people-day-class :dates="dates" :itemSchedule="scope.row" :weekDay="item.weekDay" :classData="classes" :cycleData="cycleData" @refreshData="refreshData"></people-day-class>
                      <div class="tool-tip-body" slot="reference">
                        <div :class="['day-work-cell schedule_del_class', scope.row.setClassesList[index].classColor]">
                          <div class="day-work-cell_text">{{ scope.row.setClassesList[index].classesName || '清空' }}</div>
                        </div>
                      </div>
                    </el-popover>
                  </div>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </div>
        <div class="block common-wrap__page text-right m-t-24" v-if="tableData.length != 0">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import commonDetailTop from '@/components/app/common-detail-top.vue';
import { getRequest, postRequest } from '@/api/api';
import errMsg from '@/common/js/error';
import showMsg from '@/common/js/showmsg';
// import { _debounce } from '@/common/js/public';

import peopleDayClass from '@/components/app/dailyAttendance/people-day-class.vue';
export default {
  name: 'workTimeManage',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  components: {
    peopleDayClass,
    commonDetailTop
  },
  filters: {
    filterDay(weekDay) {
      return new Date(weekDay).getDate();
    }
  },
  data() {
    return {
      activeBrand: this.brandId, // 商户(品牌) id
      activeGroup: this.activeGroupId, // 商户(品牌) groupId
      enterpriseId: JSON.parse(localStorage.getItem('userInfo')).enterpriseId,
      activeId: '2',
      topMenuData: [
        {
          id: '1',
          name: '考勤组管理',
          path: `/workSet?appIcon=${this.$route.query.appIcon}`
        },
        {
          id: '2',
          name: '编辑排班表'
        }
      ],
      yearMonth: '' + new Date().getFullYear() + '-' + (new Date().getMonth() + 1),
      // 分页参数
      currentPage: 1,
      pageSize: 20,
      total: 0,
      // 排班周期
      cycleData: [
        /* {
          rangeName: '555555',
          id: 287955018,
          isValid: true,
          classesList: [{ classesId: 468090517, classesName: '3', isValid: true }]
          // 接口这里考勤哪里是 classes， 这里变成了 classesList
        } */
      ],
      // 班次
      classes: [],
      weekData: ['日', '一', '二', '三', '四', '五', '六'],
      // 日期
      dates: [
        /*  {
          dayOfWeek: '一',
          weekDay: 1
        } */
      ],
      // 表格数据必须要有，不能空，获取数据的时候就要处理
      tableData: [
        /* {
          userName: '朱瑞泽',
          userId: '016858095226338128',
          setClassesList: [
            {
              classesId: '',
              classesName: '3',
              isRest: false,
              weekDay: 1575129600000
            }
          ]
        } */
      ]
    };
  },
  methods: {
    /**
     * 保存
     */
    toSave() {
      const that = this;
      const data = JSON.parse(JSON.stringify(that.tableData));
      let arr = [];
      data.forEach(ele => {
        ele.setClassesList.forEach(child => {
          arr.push({
            attenceGroupId: that.$route.query.attenceGroupId,
            classesId: child.classesId,
            userId: ele.userId,
            weekDay: child.weekDay
          });
        });
      });
      that.postSave(arr);
    },
    postSave(data) {
      const that = this;
      let para = {
        enterpriseId: that.enterpriseId,
        attenceGroupId: that.$route.query.attenceGroupId,
        setClassesJson: JSON.stringify(data)
        // taskType: 1 //0不良评价，1话务任务
      };
      postRequest('/haoban-app-attence-web/set-classes', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('保存成功', 'success');
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 恢复
     */
    toReset() {
      const that = this;
      that.pageSize = 1;
      that.getTableList(that.brandId);
    },
    /**
     * 选择月份
     */
    changeMonth() {
      const that = this;
      that.pageSize = 1;
      that.getTableList(that.brandId);
    },
    /**
     * 分页---页码变化
     */
    handleSizeChange(val) {
      const that = this;
      that.pageSize = val;
      that.getTableList(that.brandId);
    },

    /**
     * 分页---当前页变化
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      that.getTableList(that.brandId);
    },
    /**
     * toWorkGroup
     */
    toWorkGroup() {
      const that = this;
      that.$router.push(`/workGroupSet?appIcon=${that.$route.query.appIcon}&attenceGroupId=${that.$route.query.attenceGroupId}`);
    },
    /**
     * 刷新数据
     */
    refreshData(item) {
      const that = this;
      if (!item) {
        return false;
      }
      const tableCopy = JSON.parse(JSON.stringify(that.tableData));
      tableCopy.forEach(ele => {
        if (ele.userId == item.userId) {
          ele.setClassesList = item.setClassesList;
        }
      });
      that.tableData = JSON.parse(JSON.stringify(tableCopy));
      that.$forceUpdate();
    },
    /**
     * 获取班次
     */
    getClassifyData() {
      const that = this;
      let para = {
        enterpriseId: that.enterpriseId,
        attenceGroupId: that.$route.query.attenceGroupId
      };
      getRequest('/haoban-app-attence-web/attence-classes-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (resData.result && resData.result.length) {
              resData.result.forEach((ele, index) => {
                if (index % 7 == 0) {
                  ele.classColor = 'day-tag-blue';
                }
                if (index % 7 == 1) {
                  ele.classColor = 'day-tag-red';
                }
                if (index % 7 == 2) {
                  ele.classColor = 'day-tag-purple';
                }
                if (index % 7 == 3) {
                  ele.classColor = 'day-tag-orange';
                }
                if (index % 7 == 4) {
                  ele.classColor = 'day-tag-green';
                }
                if (index % 7 == 5) {
                  ele.classColor = 'day-tag-pink';
                }
                if (index % 7 == 6) {
                  ele.classColor = 'day-tag-cyan';
                }
                if (ele.classessTimesJson) {
                  ele.classessTimesJson = JSON.parse(ele.classessTimesJson);
                }
              });
            }
            that.classes = resData.result || [];
            that.getCycleData();
          }
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 获取周期
     */
    getCycleData() {
      const that = this;
      let para = {
        enterpriseId: that.enterpriseId,
        attenceGroupId: that.$route.query.attenceGroupId
      };
      getRequest('/haoban-app-attence-web/attence-range-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (resData.result && resData.result.length) {
              resData.result.forEach(ele => {
                if (ele.classesList && ele.classesList.length) {
                  ele.classesList.forEach(child => {
                    that.classes.forEach(item => {
                      if (child.classesId == item.classesId) {
                        child.classColor = item.classColor;
                      }
                    });
                  });
                }
              });
            }
            that.cycleData = resData.result || [];
          }
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 获取数据
     */
    getTableList(val) {
      const that = this;
      let para = {
        month: that.yearMonth,
        enterpriseId: that.enterpriseId,
        attenceGroupId: that.$route.query.attenceGroupId
      };
      postRequest('/haoban-app-attence-web/set-classes-detail', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.total = resData.result.totalCount;
            that.dates = JSON.parse(JSON.stringify(resData.result.params.dateList));
            resData.result.params.userList.forEach(ele => {
              ele.setClassesList.forEach(child => {
                child.classColor = !!child.classColor ? child.classColor : '';
                that.classes.forEach(item => {
                  if (child.classesId == item.classesId) {
                    child.classColor = item.classColor;
                  }
                });
              });
            });
            that.tableData = JSON.parse(JSON.stringify(resData.result.params.userList)) || [];
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      if (!!newData) {
        that.activeBrand = newData;
        that.getTableList();
      }
    },
    activeGroupId: function(newData, oldData) {
      const that = this;
      if (!!newData) {
        that.activeGroup = newData;
      }
    }
  },
  mounted() {
    const that = this;
    that.$emit('showTab', '2');
    that.getClassifyData();
  }
};
</script>
<style type="text/less" lang="less" scoped>
.schedule_del_class {
  color: #fff;
}
.classes-wrap {
  line-height: 22px;
  position: relative;
}
.classes-wrap {
  line-height: 22px;
  position: relative;
}
.class-row-tags {
  margin-left: 60px;
  width: 70%;
  .schedule-content_tag {
    display: inline-block;
  }
}
.color-red {
  color: #ff0000;
}
.work-time {
  width: 100%;
  .work-time-content {
    padding: 20px;
    .work-time-table {
      width: 100%;
    }
    .row-username {
      white-space: nowrap;
      position: relative;
      cursor: pointer;
      border: 0;
      line-height: 35px;
      text-align: center;
      p {
        line-height: 35px;
        height: 35px;
        width: 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

    .day-work {
      .day-work-cell {
        cursor: pointer;
        border: 0;
        text-align: center;
        width: 100%;
        height: 35px;
        &.day-tag-blue {
          background: #5e90ff;
          border-color: #5e90ff;
          color: #fff;
        }
        &.day-tag-red {
          background: #fb6370;
          border-color: #fb6370;
          color: #fff;
        }
        &.day-tag-purple {
          background: #7e6bd4;
          border-color: #7e6bd4;
          color: #fff;
        }
        &.day-tag-orange {
          background: #ff943e;
          border-color: #ff943e;
          color: #fff;
        }
        &.day-tag-green {
          background: #15bc83;
          border-color: #15bc83;
          color: #fff;
        }
        &.day-tag-pink {
          background: #ed4dae;
          border-color: #ed4dae;
          color: #fff;
        }
        &.day-tag-grey {
          background: #f6f6f6;
          border-color: #f6f6f6;
          color: #989898;
        }
        .day-work-cell_text {
          line-height: 35px;
        }
        .day-work-cell_icon {
          position: absolute;
          top: 0;
          right: 0;
          border-top: 5px solid red;
          border-left: 5px solid transparent;
        }
      }
    }
  }
}
.el-table {
  /deep/ tbody {
    td {
      padding: 0;
    }
  }
  /deep/ .cell {
    padding: 0;
  }
}
</style>
