<template>
  <div class="box">
    <div class="header flex-box flex-v-ce">
      <el-button type="primary" @click="openAdd" v-if="deptManagerRouters">+月绩效</el-button>
      <div class="search"><el-date-picker :clearable="false" v-model="month" type="month" placeholder="选择月" value-format="yyyy-MM"></el-date-picker></div>
      <el-row><el-col>
        <deptData  v-if="toPdept1 && toPdept1!=0" :refsName="$refs.dept1" :toPdept="toPdept1"></deptData>
        <el-cascader class="date-picker-width"	v-model="dept_name" ref="dept1"	:options="dept_tree" :props="{ label: 'name', value: 'id'}" clearable	filterable	change-on-select	placeholder="全公司" >
          <template slot-scope="{ node, data }">
            <span>
              <WWOpenData type="departmentName" :openid="data.name"></WWOpenData>
            </span>
            <!-- <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span> -->
          </template>
        </el-cascader>
      </el-col></el-row>
      <div class="search"><el-button type="primary" @click="excelImportShow = true" v-if="deptManagerRouters">导入绩效工作</el-button></div>
      <div class="flex-1"></div>
      <el-input placeholder="输入同事姓名" v-model="keyword" style="width: 200px;">
        <el-button slot="append" icon="el-icon-search" @click="getData()"></el-button>
      </el-input>
    </div>

    <div class="table_page">
      <el-table :data="dataList" style="width:100%" ref="dataList" tooltip-effect="dark" @row-click="row_click" v-loading="loading">
        <el-table-column prop="task_name" label="姓名" align="center">
          <template slot-scope="scope">
            <div class="flex-box flex-v-ce">
              <userImage class="user_img person_imghead" :id="scope.row.id" width="46px" height="46px" :user_name="scope.row.name" :img_url="scope.row.img_url"></userImage>
              <span style="margin-left: 20px;"><WWOpenData type="userName" :openid="scope.row.name"></WWOpenData></span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" align="center">
          <template slot-scope="scope">
            <el-progress type="circle" :percentage="scope.row.progress" :width="width"></el-progress>
          </template>
        </el-table-column>
        <el-table-column prop="base_point" align="center">
          <template slot="header" slot-scope="scope">
            <span>月平衡分</span>
            <el-tooltip placement="top">
              <div slot="content">当月绩效总分，按预期完成可得月平衡分。</div>
              <span class="tips">?</span>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <span>{{ scope.row.base_point || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="review_point" label="最终得分" align="center">
          <template slot="header" slot-scope="scope">
            <span>最终得分</span>
            <el-tooltip placement="top">
              <div slot="content">当月绩效实际得分，由评审人员根据实际完成情况打分。</div>
              <span class="tips">?</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center"  v-if="deptManagerRouters">
          <template slot-scope="scope">
            <el-button type="text" @click.stop="openDetail(scope.row)">创建绩效工作</el-button>
            <el-button type="text" v-show=" scope.row.publisher_id == employee_id " @click.stop="editTeamPerformance(scope.row)">修改</el-button>
          </template>
        </el-table-column>
        <template slot="empty">
          <noData :isSolt="true">
              <template v-slot:default>
                <div class="fontColorF"> 还没有绩效工作 <span class="blue" @click="openAdd" v-if="deptManagerRouters">【创建月绩效】</span></div>
              </template>
          </noData>
          </template>
      </el-table> 
      <div class="page">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="this.page"
          :page-size="this.perPage"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, prev, pager, next"
          :total="this.total"
        ></el-pagination>
      </div>
    </div>
        <!-- 导入数据 -->
    <el-dialog
      title="导入绩效工作"
      width="600px"
      :visible.sync="excelImportShow"
      :close-on-click-modal="false"
      :before-close="close_import">
      <div style="padding:0 50px;">
        <div class="align-center" style="margin-bottom:20px;">
          <p>1、下载绩效工作模版，批量录入绩效工作
            <el-button type="primary" @click="downloadTemplate" plain>下载模板</el-button>
          </p>
          <el-upload
            :limit = '1'
            :headers="ATOKEN"
            ref="upload1"
            :action="integralUpload"
            :data="{type: 'performance'}"
            :on-success="handlePictureCardPreview"
            :before-upload="beforeFilesUpload"
            >
            <p>3、上传绩效工作数据Excel表
                <el-button type="primary" plain>选择文件</el-button>
            </p>

          </el-upload>
          <p>2、选择文件后点击下方【上传】按钮</p>
        </div>


        <div class="align-center" style="margin-bottom:20px; float:left; margin-left:10px;">

        </div>
        <div class="align-center" style="margin-bottom:20px; float:left; margin-left:10px;">
          <!-- <el-button type="primary" @click="downloadSheet">Excel导出</el-button> -->
        </div>
        <div style="clear:both;"></div>
      </div>
        <div slot="footer" class="dialog-footer">
        <el-button @click="close_import">取 消</el-button>
        <el-button type="primary" @click="uploadFile(1)" :loading="update_btn" plain>上传</el-button>
      </div>
    </el-dialog>


    <el-dialog
      title="提交结果"
      :visible.sync="importErrorInfoShow"
      width="600px">
        <el-table :data="error_list" border stripe>
          <el-table-column label="备注信息">
            <template slot-scope="scope">
              <span class="color_red">{{scope.row}}</span>
            </template>
          </el-table-column>
        </el-table>
    </el-dialog>
    
  </div>
</template>

<script>
import noData from '@/components/noData'
import { getToken } from '@/utils/auth'
export default {
  name: 'team_performance',
  components:{noData},
  data() {
    return {
      deptManagerRouters:!this.$authoritys('dept_manager'),
      integralUpload:process.env.BASE_API + '/api/upload/excel',
      ATOKEN: { 'A-TOKEN': getToken()},
      page: 1,
      perPage: 10,
      total: 0,
      loading: false,
      employee_id: this.$store.getters.user_info.id,
      dataList: [],
      dept_tree: [],//部门集合
      dept_name:'',//部门名称
      width: 46,
      // 参数
      dept_id:0,//部门ID
      month: this.$moment().format('YYYY-MM'),
      keyword:'',
      excelImportShow: false,
      update_btn:false,
      file: [],
      importErrorInfoShow: false,
      error_list: [],
      toPdept1:0,
    };
  },
  watch: {
    month() {
      this.getData();
    },
    dept_name(val){
      this.toPdept1 = val[val.length-1]
      if(val !== null && val.length > 0){
        this.dept_id=val[val.length-1];
      }else{
       this.dept_id=0;
      }
      this.getData();
    },
  },
  mounted() {
    // let user_infos = this.$store.getters.user_info.employee_detail.role_list;
    // let deptManagerRouters = []
    // for(let i in user_infos){
    //   if(user_infos[i].name == "dept_manager" && (user_infos[i].name != "admin" || user_infos[i].name != "point_manager" || user_infos[i].name != "creator")){
    //   }else{
    //   }
    // }
    // this.$store.getters.user_info.deptManagerRouters = false
    if(sessionStorage.getItem("current_time") !== null){
      this.month = sessionStorage.getItem("current_time")
    }
    if (localStorage.getItem('dept_tree')) {
    	this.dept_tree = 	this.getTreeData(JSON.parse(localStorage.getItem('dept_tree')))
    }
    this.getData();
  },
  methods: {
    row_click(row, event, column){
      this.$router.push({
        path: '/team_detail',
        query: { date: this.month, package_id: row.package_id }
      });
      sessionStorage.setItem("current_time",this.month)
    },
    downloadTemplate(){
      window.open(process.env.BASE_API+'/api/download/performance/template')
    },
    // 文件上传
    close_import(){
      this.excelImportShow = false
    },
    uploadFile(){
      let params = {};
      params.file = this.file;
      this.update_btn = true
      this.$http('post','/api/integral/performance/import', params).then(res => {
        if(res.data.code == 1) {
          if(res.data.data.error.length == 0){
            this.$message({type:'success',message:"导入成功",})
            this.excelImportShow = false
          }else{
            this.$message({type:'error',message:"导入错误",})
            this.error_list = res.data.data.error
            this.importErrorInfoShow = true
          }
        }else{
          this.$message({type:'error',message:res.data.msg,})
        }
      }).finally(()=>{
        setTimeout(() => {this.update_btn = false}, 3000);
      })
    },
    handlePictureCardPreview(response) {
      if(response.code == 1) {
        this.file = response.data;
      }
    },
    beforeFilesUpload(file) {
      const $ext_list = ['xlsx', 'xls'];
        let len =  file.name.split('.').length - 1;
        const $ext_name = file.name.split('.')[len]
        if ($ext_list.indexOf($ext_name) != -1) {

        }else {
          this.$message.warning('文件格式上传错误,仅支持上传xlsx,xls）')
          return false
        }
    },
    // end文件上传

    editTeamPerformance(item){
      this.$router.push({
        path: '/add_team_performance',
        query: { type: '2', package_id: item.package_id,date: this.month}
      });
      
      sessionStorage.setItem("current_time",this.month)
    },
    openAdd(){
      this.$router.push({
        path: '/add_team_performance',
        // query: { date: this.month, package_id: item.package_id }
        query: { date: this.month }//传入当前页的日期
      });
    },
    getTreeData(data){
    	for(var i=0;i<data.length;i++){
    		if(data[i].children.length<1){
    			// children若为空数组，则将children设为undefined
    			data[i].children=undefined;
    		}else {
    			// children若不为空数组，则继续 递归调用 本方法
    			this.getTreeData(data[i].children);
    		}
    	}
    	return data;
    },
    //点击某一行
    openDetail(item) {
      this.$router.push({
        path: '/team_detail',
        query: { date: this.month, package_id: item.package_id , cT:true}
      });
      sessionStorage.setItem("current_time",this.month)
    },
    getData() {
      let self = this;
      self.loading = true;
      // self.$http.get('/api/integral/performance/employee', { params: { dept_id:self.dept_id, month: self.month,keyword:self.keyword,page:self.page,page_size:10 } },)
        
      const headers = {'Accept':'application/vnd.test.v3+json'}
      self.$http('get','/api/integral/performance/employee',{ dept_id:self.dept_id, month: self.month,keyword:self.keyword,page:self.page,page_size:10 },'v3').then(res => {
        if (res.data.code == 1) {
          self.dataList = res.data.data.list || [];
          self.total = res.data.data.total || 0;
        } else {
          self.$message.error(res.data.msg);
        }
      }).finally(() => {
        self.loading = false;
      });
    },
    //页码变更
    handleCurrentChange: function(val) {
      this.page = val;
      this.getData();
    }
  },
//   destroyed: function () {
//    setTimeout(()=>{
//     sessionStorage.removeItem("current_time"); 
//    },2000)
//  },
};
</script>

<style lang="scss" scoped="scoped">
$blue: #26a2ff;
$red: #f56c6c;
$yellow: #e6a23c;
$green: #67c23a;
$fontColorZ: #303133;
$fontColorF: #909399;
$fontColorT: #c0c4cc;
.color_red{
  color: $red;
}
.green {
  color: #67c23a;
}
.blue {
  color: #26a2ff;
  cursor: pointer;
}
.fontColorF {
  color: #909399;
}
.box{
  overflow: hidden;
  padding: 20px;
}
.box {
  overflow: hidden;
  .header{
    margin-bottom: 20px;
  }
  .search {
    margin: 0 10px;
  }
  .page {
    text-align: center;
    padding: 20px 0;
  }
  .tips {
    background: $fontColorT;
    border-radius: 50%;
    width: 14px;
    height: 14px;
    color: #fff;
    display: inline-block;
    font-size: 12px;
    line-height: 14px;
    text-align: center;
  }
}
 /deep/ .el-table tr:hover{
  cursor:pointer
}
</style>
