<template>
  <div class="all boxMinHeight">
    <PageHead :routePush="pushAssMan">
      <template slot="headMent">
        <el-cascader
          v-model="headValue"
          :options="options"
          :show-all-levels="false"
          :props="{
            expandTrigger: 'hover',
            label: 'name',
            value: 'id',
            children: 'list'
          }"
        ></el-cascader>
      </template>
    </PageHead>
    <header v-loading="assDetLoad">
      <div class="flex-box flex-d-center">
        <div class="flex-box">
          <div class="dept_wdiv">
            <div class="dept_inp" @click="show_dept_selector = true">
              <span v-if="deptVisibleName != ''">{{ deptVisibleName }}</span>
              <span v-else style="color: #b9b9b9;">选择部门</span>
            </div>
            <svg-icon slot="reference" icon-class="xArrowsX" />
          </div>
          <EmployeeSelector
            :title="'选择部门'"
            :isChecKedAll="false"
            :can_select_employee="false"
            :can_select_dept="true"
            :dept_children="false"
            :selected="dept_selected"
            :visible.sync="show_dept_selector"
            @confirm="dept_confirm"
          />
          <el-select v-model="groupValue" clearable  class="margin-l" placeholder="选择考核表">
            <el-option v-for="item in groupOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <div class="margin-l" style="width:200px;"><JxSearch :screen="2"  title="请输入姓名搜索" @confirm="aDetSearch"></JxSearch></div>
        </div>
      </div>
      <div class="table-box" style="margin-top: 20px;">
        <el-tabs v-model="glIndex">
          <el-tab-pane :label="item.title" :name="item.name" v-for="(item, index) in glIist" :key="index">
            <el-table :data="glDataList" v-loading="glLoading" stripe>
              <el-table-column prop="name" label="被考核人">
                <template slot-scope="scope">
                  <div class="flex-box-ce">
                    <userImage
                      :id="scope.row.userInfo.id"
                      :user_name="scope.row.userInfo.name"
                      :img_url="scope.row.userInfo.img_url"
                      width="35px"
                      height="35px"
                      fontSize="12px"
                    ></userImage>
                    <span style="margin-left: 10px; line-height: 50px;">{{ scope.row.userInfo.name }}</span>
                    <span style="margin-left: 10px; line-height: 50px;" class="yellow" v-if="scope.row.has_finish">已归档</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="部门">
                <template slot-scope="scope">
                  <div v-if="scope.row.dept_list.length > 0">
                    <span v-for="(item, index) in scope.row.dept_list" :key="index">
                      {{ item.name }}
                      <span v-if="scope.row.dept_list.length - index > 1">,</span>
                    </span>
                  </div>
                  <span v-else>--</span>
                </template>
              </el-table-column>
              <el-table-column prop="package_name" label="考核时段"></el-table-column>
              <el-table-column prop="name" label="管理记录">
                <template slot-scope="scope">
                  <span v-if="scope.row.count_record == 0" class="fontColorB">无管理记录</span>
                  <span v-else class="blue" style="cursor: pointer;" @click="openTx(scope.row)">{{ scope.row.count_record }}条管理记录</span>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="执行计划">
                <template slot-scope="scope">
                  <template v-if="scope.row.action_update">
                     <div v-if="returnStr(scope.row.action_update).indexOf('今天')>=0" class="actionText orange">{{returnStr(scope.row.action_update)}}</div>
                     <div v-else-if="returnStr(scope.row.action_update).indexOf('昨天')>=0" class="actionText green">{{returnStr(scope.row.action_update)}}</div>
                     <div v-else class="actionText">{{returnStr(scope.row.action_update)}}</div>
                  </template>
                  <div></div>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="openTx(scope.row)" type="text" v-if="!scope.row.has_finish">填写管理记录</el-button>
                  <el-button @click="openDetail2(scope.row)" type="text">查看详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <Pagination :page_size="page_size" :page="page" :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></Pagination>
        </el-tabs>
      </div>
    </header>

    <!-- 跟踪管理 -->
    <TrackManagement
      :showDrawer.sync="isTrack"
      :id="employeeID"
      :isCz="has_finish? true:false"
      :apList="apList"
      :recordMemberIds="recordMemberIds"
      :assessId="employee_id"
      @confirm="getManagement"
    ></TrackManagement>
  </div>
</template>
<script>
import PageHead from '@/components/public/PageHead'; //头部---返回
import JxSearch from '@/components/public/JxSearch'; //搜索
import moment from 'moment';
import TrackManagement from '@/components/public/TrackManagement';
import EmployeeSelector from '@/components/public/EmployeeSelector';
export default {
  name:'management',
  data() {
    return {
      day: moment().format('YYYY-MM-DD'),
      page: 1,
      page_size: 10,
      total: 0,
      nowass: false, //已开始评分显示隐藏
      pushAssMan: null, //头部跳转
      assDetLoad: false, //loading
      headValue: [], //顶部选择考核
      options: [], //顶部考核数据
      groupValue: '', //选择考核表val
      groupOptions: [], //选择考核表数据
      scoreGroup: [], //评分考核表

      deptVisibleName: '', //部门名称
      dept_selected: { dept: [], employee: [] },
      show_dept_selector: false,
      deptList_id: [],
      package_id: '',

      name: '', //搜索名称
      glIndex: '0',
      glIist: [{ name: '0', title: '全部' }, { name: '1', title: '我的团队' }, { name: '2', title: '我协助管理的' }],
      glLoading: false,
      glDataList: [],

      isTrack: false,
      apList: [], //管理记录源数据
      employee_id: 0, //被考核人ID
      employeeID: 0,
      staffLoad: false,
      recordMemberIds: [],
      has_finish:0,//是否归档
    };
  },
  components: { PageHead, JxSearch, EmployeeSelector, TrackManagement },
  computed: {},
  watch: {
    groupValue(val) {
      this.getManagement();
    },
    glIndex(val) {
      this.page = 1;
      this.getManagement();
    },
    headValue(val) {
      this.package_id = val[val.length - 1];
      this.groupValue = '';
      this.getGroup();
      this.getManagement();
      this.$setCache("cache_s_m",val)//缓存我的管理列表和我的评分列表选择的考核包
    }
  },
  created() {
    this.assessTree();
  },
  mounted() {},
  methods: {
    returnStr(time){
      let date=`${time}000`
      let res = moment(Number(date)).format('YYYY/MM/DD HH:mm');
      return this.fnTime(res);
    },
    fnTime( time ){
        let staer=time.slice(0,11);
        let ptime = new Date(time).getTime()
        const twentyFourHours = 24 * 60 * 60 * 1000;
        const fortyEightHours = 24 * 60 * 60 * 1000 * 2;
        const today=moment().format('YYYY/MM/DD');
        const todayTime = new Date(today).getTime();
        const yesterdayTime = new Date(todayTime - twentyFourHours).getTime();
        const lastYesterdayTime = new Date(todayTime - fortyEightHours).getTime();

        if( ptime >= todayTime ){
            return '今天 '+time.split(' ')[1]+' 更新了执行计划';
        }
        else if( ptime < todayTime && yesterdayTime <= ptime ){
            return '昨天 '+time.split(' ')[1]+' 更新了执行计划';
        }
        else if( ptime < yesterdayTime && lastYesterdayTime <= ptime ){
            return '前天 '+time.split(' ')[1]+' 更新了执行计划';
        }else if(this.dateSum(this.day,staer)>30){
            return '近30天无计划更新';
        } else{
            return time+' 更新了执行计划';
        }
    },
    dateSum(sDate1, sDate2){   //sDate1和sDate2是2008-12-13格式
        var aDate, oDate1, oDate2, iDays
        aDate = sDate1.split("-")
        oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])   //转换为12-13-2008格式
        aDate = sDate2.split("-")
        oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
        iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 /24)   //把相差的毫秒数转换为天数
        return iDays
    },
    openTx(item) {
      this.employee_id = item.employee_id;
      this.employeeID = item.record_id;
      this.has_finish=item.record_id;
      this.employeeDet(item.record_id, () => {
        this.isTrack = true;
      });
    },
    employeeDet(id, callBack) {
      this.staffLoad = true;
      this.$axios('get', '/api/per/package/employee/info', { id: id })
        .then(res => {
          let data = res.data.data;
          this.apList = data.dimension;
          this.recordMemberIds = data.record_member_ids;
          callBack && callBack();
        })
        .finally(() => {
          this.staffLoad = false;
        });
    },
    openTrack(item) {
      this.employeeID = item.record_id;
      this.employID = item.employee_id;
      this.isTrack = true;
    },
    openDetail2(item) {
      this.$router.push({
        path: '/staffAssDet',
        query: {
          assID: this.package_id,
          employeeID: item.record_id,
          employeeIDs: item.employee_id
        }
      });
    },
    //我评分的
    getManagement() {
      if(this.headValue.length==0){
        return false
      }
      this.glLoading = true;
      let data = {
        range: this.glIndex,
        package_id: this.package_id||0,
        name: this.name,
        page: this.page,
        page_size: this.page_size,
        dept_id: JSON.stringify(this.deptList_id)
      };
      if (this.groupValue) {
        data.group_id = this.groupValue;
      }
      this.$axios('get', '/api/per/package/management_record', data)
        .then(res => {
          let list = res.data.data.list;
          list.forEach(item => {
            if (item.employee_id) {
              //当是导入导出时，显示登录者
              item.userInfo = this.$getEmployeeList()[item.employee_id];
			  if(this.$getEmployeeList()[item.employee_id]){
			  	item.dept_list = this.$getEmployeeList()[item.employee_id].dept_list;
			  }
            }
          });
          this.glDataList = list;
          this.total = res.data.data.total;
        })
        .finally(() => {
          this.glLoading = false;
        });
    },
    //获取考核表
    getGroup() {
      if(!this.package_id){
        return false
      }
      this.$axios('get', '/api/per/package/group', { package_id: this.package_id }).then(res => {
        if (res.data.code == 1) {
          this.groupOptions = res.data.data;
        }
      });
    },
    aDetSearch(data) {
      //搜索回调
      this.page = 1;
      this.name = data;
      this.getManagement();
    },
    //请求绩效树
    assessTree() {
      this.$axios('get', '/api/per/package/tree').then(res => {
        if (res.data.code == 1) {
          this.options = res.data.data;
          let headValue = [];
          this.options.some(item => {
            if (item.list.length > 0) {
              headValue.push(item.id);
              headValue.push(item.list[0].id);
              return true;
            }
          });
          let cache_s_m=this.$getCache('cache_s_m');//缓存的数据
          if(cache_s_m){
            this.headValue=cache_s_m
          }else if(this.$route.query.headValue){
            this.headValue=JSON.parse(this.$route.query.headValue)
          }else{
            if (headValue.length > 0) {
              this.headValue = headValue;
            }
          };
        }
      });
    },
    dept_confirm(data) {
      //部门选择
      this.dept_selected = { dept: [], employee: [] };
      let deptList_id = [];
      this.deptVisibleName = '';
      if (data.dept !== null && data.dept.length != 0) {
        this.dept_selected = data;
        data.dept.forEach((element, index) => {
          deptList_id.push(element.dept_id);
          this.deptVisibleName += element.dept_name;
          if (data.dept.length - index > 1) {
            this.deptVisibleName += ',';
          }
        });
      }
      this.deptList_id = deptList_id;
      this.getManagement();
    },
    // 页面变更
    handleCurrentChange(val) {
      this.page = val;
      this.getManagement();
    },
    // 页面跳转
    handleSizeChange(val) {
      this.page_size = val;
      this.getManagement();
    }
  },
  beforeRouteLeave(to, from, next) {
    if(to.name!='staffAssDet'){
      localStorage.removeItem("cache_s_m")
    }
    next();
  }
};
</script>
<style scoped lang="scss">
.all {
  padding: 20px;
  background-color: #fff;
  font-size: 14px;
}
header {
  margin-top: 20px;
  .dept_wdiv {
    width: 150px;
    position: relative;
    .dept_inp {
      position: absolute;
      top: 0;
      right: 0;
      left: 0;
      bottom: 0;
      z-index: 9;
      border: 1px solid #e0e0e0;
      border-radius: 3px;
      line-height: 40px;
      font-size: 14px;
      padding: 0 10px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      cursor: pointer;
      color: #676767;
    }
    svg {
      position: absolute;
      top: 0;
      right: 0;
      top: 14px;
      right: 10px;
      font-size: 14px;
      color: #b5b5b5;
    }
  }
  .navigationL {
    background-color: #f5f5f5;
    border: 1px solid #e4e4e4;
    width: 100%;
    height: 50px;
    margin: 25px 0px 15px 0;
    ::v-deep .action {
      color: #428eff;
    }
    span:hover {
      color: #428eff;
    }
    span {
      display: flex;
      cursor: pointer;
      font-size: 14px;
      padding: 15px;
      position: relative;
      width: 100%;
      justify-content: center;
      svg {
      }
      .navsvg1 {
        color: #3a3a3a;
        font-size: 15px;
        position: relative;
        margin-top: 2px;
      }
      .navsvg2,
      .navsvg3 {
        position: absolute;
        top: 16px;
        right: 0;
      }
      .navsvg2 {
        color: rgb(140, 140, 140);
        font-size: 15px;
      }
      .navsvg3 {
        transform: rotate(270deg);
        color: #8c8c8c;
      }
    }
  }

  ::v-deep .el-table tr:hover {
    cursor: pointer;
  }
}

.braTab {
  padding: 20px 0 0 20px;
  ::v-deep .el-table tr:hover {
    cursor: pointer;
  }
  ::v-deep .el-table__row {
    .cell {
      padding-left: 10px;
    }
  }
  ::v-deep td .cell {
    padding: 10px 0;
  }
}

.margin-l {
  margin-left: 10px;
}
.width-300 {
  width: 300px;
}
.m-content {
}
.m-title {
  color: #909399;
}
.ul {
  margin: 20px 0;
  margin-top: 0;
}
.li {
  border-bottom: 1px solid #ebebeb;
}
.li .flex-box-ce {
  padding: 15px 0;
}
.li:hover {
  background-color: #f5f7fa;
}
</style>
