<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-03-20 14:36:37
 * @LastEditors  : 无尘
 * @LastEditTime : 2019-12-26 14:58:35
 -->

<!--

 -->
<template>
  <div class="app-detail-wrap">
    <div>
      <div class="common-detail-tab">
        <el-tabs v-model="activeName" class="daily-set-tab" @tab-click="handleTabClick">
          <el-tab-pane label="考勤组管理" name="first"></el-tab-pane>
          <el-tab-pane label="班次管理" name="second"></el-tab-pane>
        </el-tabs>
      </div>
      <div v-show="activeName == 'first'" class="app-detail-pane border-box p-20">
        <div class="m-b-20">
          <div class="switch-wrap">
            <div class="flex flex-space-between">
              <div>
                <el-input placeholder="请输入考勤组名称" v-model="conditionObj.attenceGroupName" class="w-264" style="width: 264px;" prefix-icon="el-icon-search" @keyup.native="value => toInput(value, conditionObj.attenceGroupName)" clearable @clear="clearInput"></el-input>
              </div>
              <div><span class="font-14 color-606266 p-r-10">配置说明：考勤组管理，可以添加不同部门或分组的考勤</span><el-button type="primary" @click="toWorkGroupSet">新建考勤组</el-button></div>
            </div>
          </div>
        </div>
        <div>
          <el-table class="select-table" ref="multipleTable" :data="groupListData" tooltip-effect="dark" :style="{ width: '100%' }">
            <el-table-column label="考勤组名称" width="120" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.attenceGroupName }}</template>
            </el-table-column>
            <el-table-column prop="" label="人数">
              <template slot-scope="scope">{{ scope.row.personCount }}</template>
            </el-table-column>
            <el-table-column prop="" label="类型" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.attenceType == 1 ? '固定排班' : scope.row.attenceType == 2 ? '排班制' : '自由排班' }}</template>
            </el-table-column>
            <el-table-column prop="" label="考勤时间" show-overflow-tooltip>
              <template slot-scope="scope">
                <div v-if="scope.row.attenceType == 1">
                  <div v-for="(item, index) in scope.row.attenceWorkJson" :key="index + 'json'" class="text-ellipsis">
                    <span>{{ weekDays[item.weekDay] }} </span>
                    <span>班次{{ item.classesName }}：</span>
                    <span v-if="!!item.classessTimesJson">
                      <span v-for="(child, cindex) in item.classessTimesJson" :key="cindex"> {{ child.startTime }}-{{ child.endTime }} </span>
                    </span>
                    <span v-if="item.classesId == '-1'">休息</span>
                  </div>
                </div>
                <div v-if="scope.row.attenceType == 2">
                  <div v-for="(item, index) in scope.row.classesJson" :key="index + 'json2'" class="text-ellipsis">
                    <span>班次{{ item.classesName }}：</span>
                    <span v-if="!!item.classessTimesJson">
                      <span v-for="(child, cindex) in item.classessTimesJson" :key="cindex"> {{ child.startTime }}-{{ child.endTime }} </span>
                    </span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="" label="最近更新时间" show-overflow-tooltip>
              <template slot-scope="scope">
                <div>{{ scope.row.updateTime | timeStampToYmd }}</div>
                <div>{{ scope.row.updateTime | timeStampToHms }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button v-if="scope.row.attenceType == 2 && scope.row.personCount" type="text" size="small" @click="toEditWorkTime(scope.$index, scope.row)">编辑排班</el-button>
                <el-button type="text" size="small" @click="toEditGroup(scope.$index, scope.row)">修改规则</el-button>
                <el-button type="text" size="small" @click="toDel(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block common-wrap__page text-right m-t-24" v-if="groupListData.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 v-show="activeName == 'second'" class="app-detail-pane border-box p-20">
        <div class="m-b-20">
          <div class="switch-wrap">
            <div class="flex flex-space-between">
              <div>
                <el-input placeholder="请输入班次名称" v-model="conditionObj.classesName" class="w-264" style="width: 264px;" prefix-icon="el-icon-search" @keyup.native="value => toInput(value, conditionObj.classesName)" clearable @clear="clearInput"></el-input>
              </div>
              <div>
                <el-button type="primary" @click="toWorkClassSet">新建班次</el-button>
              </div>
            </div>
          </div>
        </div>
        <div>
          <el-table class="select-table" ref="multipleTable" :data="classifyList" tooltip-effect="dark" :style="{ width: '100%' }">
            <el-table-column label="班次名称" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.classesName }}</template>
            </el-table-column>
            <el-table-column prop="" label="考勤时间">
              <template slot-scope="scope">
                <div v-for="(item, index) in scope.row.classessTimesJson" :key="index + 'time'">{{ item.startTime }}-{{ item.endTime }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="toEditClass(scope.$index, scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="toDel(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block common-wrap__page text-right m-t-24" v-if="classifyList.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>
    <create-work-class :classesId="classesId" :workClassShow="workClassShow" @hideDetailDialog="hideDetailDialog"> </create-work-class>
  </div>
</template>
<script>
import createWorkClass from '@/components/app/dailyAttendance/create-work-class.vue';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
import { postRequest } from '@/api/api';
export default {
  name: 'app-detail',
  components: { createWorkClass },
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    tabType: {
      type: String,
      default() {
        return '1';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      projectName: '', // 当前项目名
      activeName: 'first',
      activeBrand: this.brandId,
      activeGroup: this.activeGroupId, // 商户(品牌) groupId
      enterpriseId: JSON.parse(localStorage.getItem('userInfo')).enterpriseId,
      // 搜索
      weekDays: {
        '0': '周日',
        '1': '周一',
        '2': '周二',
        '3': '周三',
        '4': '周四',
        '5': '周五',
        '6': '周六'
      },
      conditionObj: {
        attenceGroupName: '',
        classesName: ''
      },
      groupListData: [], // 考勤组列表数据
      classifyList: [], // 班次列表数据
      currentPage: 1,
      pageSize: 20,
      total: 0,
      // 新建班次
      workClassShow: false,
      classesId: ''
    };
  },

  methods: {
    /* eslint-disable */
    /**
     * 切换 tab
     */
    async handleTabClick(tab, event) {
      const that = this;
      that.pageSize = 20;
      that.currentPage = 1;
      that.activeName == 'first' ? that.getTableList(that.brandId) : that.getClassesList(that.brandId);
    },
    /**
     * 新建考勤组
     */
    toWorkGroupSet() {
      const that = this;
      that.$router.push(`/workGroupSet?appIcon=${that.$route.query.appIcon}`)
    },
    /**
     * 编辑排班
     */
    toEditWorkTime(index, row) {
      const that = this;
      that.$router.push(`/workTimeManage?appIcon=${that.$route.query.appIcon}&attenceGroupId=${row.attenceGroupId}`);
    },
    /**
     * 编辑考勤组（即：规则）
     */
    toEditGroup(index, row) {
      const that = this;
      that.$router.push(`/workGroupSet?appIcon=${that.$route.query.appIcon}&attenceGroupId=${row.attenceGroupId}`);
    },
    /**
     * 新建班次
     */
    toWorkClassSet() {
      const that = this;
      that.workClassShow = true;
    },
    /**
     * 编辑班次
     */
    toEditClass(index, row) {
      const that = this;
      that.workClassShow = true;
      that.classesId = row.classesId;
    },
    /*
     *
     */
    hideDetailDialog() {
      const that = this;
      that.workClassShow = false;
      that.classesId = '';
      that.currentPage = 1;
      that.activeName == 'first' ? that.getTableList(that.brandId) : that.getClassesList(that.brandId);
    },
    /**
     * 删除
     */
    toDel(index, item) {
      const that = this;
      that
        .$confirm(`是否要删除该${that.activeName == 'first'? '考勤组': '班次'}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.postDel(index, item);
        })
        .catch(() => {});
    },
    /**
     * 删除
     */
    postDel(index, item) {
      const that = this;
      let para = {};
      if(that.activeName == 'first') {
        para.attenceGroupId = item.attenceGroupId;
      }else {
        para.classesId = item.classesId;
      }
      postRequest(that.activeName == 'first'? '/haoban-app-attence-web/attence-del':'/haoban-app-attence-web/classes-del', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('删除成功', 'success');
            that.activeName == 'first' ? that.getTableList(that.brandId) : that.getClassesList(that.brandId);
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      that.currentPage = 1;
      that.activeName == 'first' ? that.getTableList(that.brandId) : that.getClassesList(that.brandId);
    }, 500),
    // 搜索清除
    clearInput() {
      const that = this;
      that.currentPage = 1;
      that.activeName == 'first' ? that.getTableList(that.brandId) : that.getClassesList(that.brandId);
    },
    changeCondition() {
      const that = this;
      that.currentPage = 1;
      that.activeName == 'first' ? that.getTableList(that.brandId) : that.getClassesList(that.brandId);
    },

    /**
     * 分页---页码变化
     */
    handleSizeChange(val) {
      const that = this;
      that.pageSize = val;
      that.activeName == 'first' ? that.getTableList(that.brandId) : that.getClassesList(that.brandId);
    },

    /**
     * 分页---当前页变化
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      that.activeName == 'first' ? that.getTableList(that.brandId) : that.getClassesList(that.brandId);
    },

    /**
     * 获取列表数据
     */
    getTableList(brandId) {
      const that = this;
      let para = {
        brandId: brandId || that.activeBrand,
        enterpriseId: that.enterpriseId,
        attenceGroupName: that.conditionObj.attenceGroupName,
        classesName: that.conditionObj.classesName,
        pageNum: that.currentPage,
        pageSize: that.pageSize
      };
      postRequest('/haoban-app-attence-web/attence-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if(resData.result.list && resData.result.list.length) {
              resData.result.list.forEach(ele => {
                if (ele.attenceWorkJson) {
                  ele.attenceWorkJson = JSON.parse(ele.attenceWorkJson)
                }
                if (!!ele.classesJson) {
                  ele.classesJson = JSON.parse(ele.classesJson)
                }
              })
              resData.result.list.forEach(ele => {
                if (!!ele.attenceWorkJson && ele.attenceWorkJson.length) {
                  ele.attenceWorkJson.forEach(child => {
                    child.classessTimesJson =  child.classessTimesJson? JSON.parse(child.classessTimesJson): []
                  });
                }
                if (!!ele.classesJson&& ele.classesJson.length) {
                  ele.classesJson.forEach(child => {
                    child.classessTimesJson =  child.classessTimesJson? JSON.parse(child.classessTimesJson): []
                  })
                }
              })
            }
            that.groupListData = resData.result.list || [];
            that.total = resData.result.total;
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    getClassesList(brandId) {
      const that = this;
      let para = {
        brandId: brandId || that.activeBrand,
        enterpriseId: that.enterpriseId,
        attenceGroupName: that.conditionObj.attenceGroupName,
        classesName: that.conditionObj.classesName,
        pageNum: that.currentPage,
        pageSize: that.pageSize
      };
      postRequest('/haoban-app-attence-web/classes-page', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if(resData.result.list && resData.result.list.length) {
              resData.result.list.forEach(ele => {
                if (ele.classessTimesJson) {
                  ele.classessTimesJson = JSON.parse(ele.classessTimesJson)
                }
              })
            }
            that.classifyList = resData.result.list || [];
            that.total = resData.result.total;
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 保存
     */
    submit: _debounce(function(type) {
      const that = this;
      that.setData(type);
    }, 500),
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      if(!!newData) {
        that.activeBrand = newData;
      }
    },
    activeGroupId: function(newData, oldData) {
      let that = this;
      if (!!newData) {
        that.activeGroup = newData;
      }
    },
    tabType: function(newData, oldData) {
      const that = this;

    }
  },
   mounted() {
    const that = this;
    that.$emit('showTab', '2');
    if(that.brandId && that.brandId != 1) {
      that.activeBrand = that.brandId;

    }
    that.getTableList(that.brandId);
  },

};
</script>
<style lang="less" scoped>
.w-500 {
  width: 500px;
}

.w-195 {
  width: 195px;
}

.color-1890ff {
  color: #1890ff;
}

.p-20 {
  padding: 20px;
}

.p-l-38 {
  padding-left: 38px;
}

.app-detail-wrap {
  height: 100%;
  background: #fff;
  .el-tabs {
    background: #fff;
    /deep/ .el-tabs__nav-wrap {
      /* height: 48px;
      line-height: 48px; */
      &::after {
        height: 1px;
      }
      /* .el-tabs__nav-scroll {
        padding-left: 20px;
      } */
    }
  }
  .condition-tip {
    width: 740px;
    .el-alert--info {
      background: #E6F7FF;
      border: 1px solid rgba(145,213,255,1);
      .el-alert__icon {
        font-size: 12px;
      }
    }
  }
}
</style>
