<template>
  <div>
    <div class="diy_tip_bg" v-show="tips_show">
      <el-alert class="diy-tip" @close="tips_close" type="success" description>
        <p><b>累计排名常用于长期激励</b></p>
        <li class="headLi">累计排名包含从入职开始至今所有的积分（包含基础分和工龄分）</li>
        <li class="headLi">导出时，额外支持自定义时间段排名、工龄分排名、管理者/员工排名的导出</li>
      </el-alert>
    </div>

    <div class="manager_statistics_box">
      <el-form :inline="true">
        <el-form-item label="部门">
          <deptData  deptStyle="height:24px;line-height:24px;margin-top:7px;" v-if="toPdept && toPdept!=0" :refsName="$refs.dept" :toPdept="toPdept"></deptData>
          <el-cascader class="date-picker-width" v-model="dept_name" :props="{ label: 'name', value: 'id'}" :options="dept_tree" ref="dept" 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-form-item>
        <el-form-item><el-checkbox v-model="agePolyethism" size="medium" label="只看工龄分" border></el-checkbox></el-form-item>
        <el-form-item><el-checkbox v-model="sort" size="medium" label="排名由低到高" border></el-checkbox></el-form-item>
        <el-form-item>
          <!-- <el-button type="primary" plain @click="dialogVisible = true">导出排名</el-button> -->
          <!-- <el-button type="primary" plain @click="byRanking">轮播排名</el-button> -->
        </el-form-item>
      </el-form>

      <el-table :data="list" style="width: 100%" v-loading="loading">
        <el-table-column label="名次" width="80" align="center">
          <template slot-scope="scope">
            <img v-if="scope.row.rank === 1" src="/static/images/statistics_NO1.png" alt="" />
            <img v-if="scope.row.rank === 2" src="/static/images/statistics_NO2.png" alt="" />
            <img v-if="scope.row.rank === 3" src="/static/images/statistics_NO3.png" alt="" />
            <span v-if="scope.row.rank > 3">{{ scope.row.rank }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="left">
          <template slot-scope="scope">
            <userImage class="fl" :id="scope.row.employee_id" :user_name="scope.row.employee_name" :img_url="scope.row.employee_img_url" width="50px" height="50px"></userImage>
            <span style="line-height: 50px; padding-left: 10px;"><WWOpenData type="userName" :openid="scope.row.employee_name"></WWOpenData></span>
          </template>
        </el-table-column>
        <el-table-column label="B分" align="left" prop="point"></el-table-column>
        <template slot="empty">
          <div class="nopoint_box">
            <div class="noimg noperson"></div>
            <span class="title">没有对应的数据</span>
          </div>
        </template>
      </el-table>

      <center style="padding: 20px 0;">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="formData.page"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :page-size="pageLimit"
          :total="total"
        ></el-pagination>
      </center>
    </div>

    <!-- 导出弹窗 -->
    <el-dialog title="导出排名" :visible.sync="dialogVisible" width="730px">
      <div style="font-size:15px;margin-top:20px;"><span>系统将按以下已选条件导出对应的排名报表 </span>
          <el-checkbox v-model="deriveAgePolyethism" style="margin-left:20px;"><b>只看工龄分</b></el-checkbox></div>
      <el-form :inline="true">
        <div class="picker_er" style="margin-top:20px">
          <el-form-item label="时间">
            <el-date-picker
              v-model="Dc_Data.value1"
              type="daterange"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :disabled="deriveAgePolyethism"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="人员" style="margin-left:30px">
            <el-select v-model="Dc_Data.DC_position" style="width:150px" placeholder="请选择">
              <el-option v-for="item in positions" :key="item.id" :label="item.name" :value="item.age"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="部门">
          <deptData deptStyle="height:24px;line-height:24px;margin-top:7px;" v-if="toPdept2 && toPdept2!=0" :refsName="$refs.dept2" :toPdept="toPdept2"></deptData>
          <el-cascader
            class="date-picker-width cascader_bm"
            v-model="Dc_Data.dept_name"
            :options="dept_tree"
            :props="{ label: 'name', value: 'id'}"
            ref="dept2"
            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-form-item>
        <!-- <el-form-item label="规则分类" style="margin-left:20px">
          <el-cascader
            class="date-picker-width"
            v-model="Dc_Data.rule_id"
            :options="rule_trees"
            :props="props"
            ref="rule"
            clearable
            collapse-tags
            placeholder="请选择规则分类"
          ></el-cascader>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="exportExcel">导 出</el-button>
      </span>
    </el-dialog>

    <el-dialog title="轮播排名" :visible.sync="byRankingShow" width="500px">
      <div>
        <el-form :inline="true" ref="byRankingData" :model="byRankingData" :rules="byRankingDataRules" label-width="90px">
          <div style="color:rgb(122 202 126);font-size: 13px;padding:5px 0 20px 0">设置后，相关排名信息可在各类智能终端屏幕上的网页浏览器滚屏展示</div>
          <el-form-item label="展示标题">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 6 }"
              v-model="titleVals"
              placeholder="请输入标题"
              maxlength="20"
              show-word-limit
              style="width: 341px"
            ></el-input>
          </el-form-item>
          <el-form-item label="选择部门">
            <deptData  deptStyle="height:24px;line-height:24px;margin-top:7px;" v-if="toPdept1 && toPdept1!=0" :refsName="$refs.dept1" :toPdept="toPdept1"></deptData>
            <el-cascader
              class="date-picker-width"
              v-model="byRankingDeptId"
              :options="dept_tree"
              :props="{ label: 'name', value: 'id'}"
              ref="dept1"
              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-form-item>
          <el-form-item label="人员范围" prop="position" :required="true">
            <el-radio-group v-model="byRankingData.position">
              <el-radio label="all">管理者和员工</el-radio>
              <el-radio label="manager">只看管理者</el-radio>
              <el-radio label="employee">只看员工</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer">
        <el-button @click="byRankingShow = false">取 消</el-button>
        <el-button type="primary" @click="swiperPage('byRankingData')">开始轮播</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth';
export default {
  data() {
    return {
      dialogVisible: false,
      Dc_Data: {
        //导出数据
        value1: '', //时间
        DC_position: '全部', //人员
        dept_name: [], //部门
        work_age:0
        // rule_id: [], //规则
      },
      // positions: [
      // 	{ id: 0, age: "all", name: "全部" },
      // 	{ id: 1, age: "manager", name: "管理者" },
      // 	{ id: 2, age: "employee", name: "员工" },
      // ],
      titleVals: '',
      titleVal: {
        titleVal1: '',
        titleVal2: '',
        titleVal3: ''
      },

      DC_position: 0,
      positions: [{ id: 0, age: 'all', name: '全部' }, { id: 1, age: 'manager', name: '管理者' }, { id: 2, age: 'employee', name: '员工' }],
      byRankingDeptId: '', //部门
      byRankingData: {
        //部门ID
        dept_id: 0,
        position: 'all'
      },
      byRankingShow: false, //轮播排名弹窗
      byRankingDataRules: {
        //提示
        // dept_id: [
        // 	{ required: true, message: '请选择部门', trigger: 'blur' }
        // ],
      },

      // 20200806
      dept_name: [],
      dept_tree: [],
      loading: false,
      formData: {
        dept_id: '0',
        sort: 'DESC',
        page: 1,
        page_size: 10,
        pt_id: 3,
        type: 'all',
        work_age:0,
      },
      agePolyethism:false,
      deriveAgePolyethism:false,
      sort: false,
      list: null,
      pageLimit: 10,
      total: null,
      tips_show: false,
      toPdept:0,
      toPdept1:0,
      toPdept2:0,
    };
  },
  watch: {
    deriveAgePolyethism(val){
      if(val){
        this.Dc_Data.work_age = 1
        this.Dc_Data.value1 = null
      }else{
        this.Dc_Data.work_age = 0
      }
    },
    agePolyethism(val){
      if(val){
        this.formData.work_age = 1
      }else{
        this.formData.work_age = 0
      }
      this.formData.page = 1;
      this.get_list();
    },
    sort(val) {
      if (val) {
        this.formData.sort = 'ASC';
      } else {
        this.formData.sort = 'DESC';
      }
      this.formData.page = 1;
      this.get_list();
    },
    dept_name(val) {
      this.toPdept = val[val.length-1]
      if (val.length !== 0) {
        this.formData.dept_id = val[val.length - 1];
      } else {
        this.formData.dept_id = '0';
      }
      this.formData.page = 1;
      this.$nextTick(() => {
        this.$refs.dept.dropDownVisible = false;
        this.get_list();
      });
    },

    byRankingDeptId(val) {
      this.toPdept1 = val[val.length-1]
      this.byRankingDeptId = val;
      this.$refs.dept1.dropDownVisible = false;
    },
    'Dc_Data.dept_name': function(val) {
      this.toPdept2 = val[val.length-1]
      this.$refs.dept2.dropDownVisible = false;
    }
  },
  methods: {
    exportExcel() {

      //人员
      this.Dc_Data.DC_position =
        this.Dc_Data.DC_position == 'manager' ? 'manager' : this.Dc_Data.DC_position == 'employee' ? 'employee' : this.Dc_Data.DC_position == '全部' ? 'all' : 'all';
      //部门
      let dept_name;
      for (let i in this.Dc_Data.dept_name) {
        dept_name = this.Dc_Data.dept_name[i];
      }
      this.Dc_Data.dept_name = dept_name;
      let data = '';
      if (this.Dc_Data.value1) {
        data += '&start_date=' + this.Dc_Data.value1[0];
        data += '&end_date=' + this.Dc_Data.value1[1];
      }
      data += '&position=' + this.Dc_Data.DC_position;
      data += '&work_age=' + this.Dc_Data.work_age
      this.Dc_Data.dept_name > 0 ? (data += '&dept_id=' + this.Dc_Data.dept_name) : (data += '&dept_id=0');
      // var id = window.open(
      // 	process.env.BASE_API +
      // 	"/api/download/ranking/v2?pt_id=3&type=all&employee_id=" +
      // 	this.$store.getters.user_info.id +
      // 	data,
      // 	"_blank"
      // );
      var tempwindow = window.open('_blank'); // 先打开页面
      tempwindow.document.write(
        "<p style='text-align:center;padding-top:50px;font-size:24px'>数据报表正在生成，生成后将自动下载，请不要关闭此标签页<br/><span style='font-size:17px'>（如网络错误请刷新后重试)<span/></p>"
      );
      tempwindow.document.title = '导出';
      let token = this.$getToken?this.$getToken:getToken()
      tempwindow.location = process.env.BASE_API + '/api/download/ranking/v2?pt_id=3&type=all&employee_id=' + this.$store.getters.user_info.id + data+'&token='+token; // 后更改页面地址
      this.dialogVisible = false;

      // var img = new Image(); //创建img标签
      // img.src = 'http://5b0988e595225.cdn.sohucs.com/images/20170930/89fe9e8a782645048fb826e074208862.jpeg';
      // let imgSty = 'width: 100%; height: 100%;';
      // img.style = imgSty;
      // img.style.width = '50%';
      // img.style.height = '50%';
      // img.style.position='absolute'
      // img.style.top='50%'
      // img.style.left='50%'
      // img.style.margin ='-12.5% 0 0 -25%'
      // tempwindow.document.write(img.outerHTML);
    },
    //轮播排名弹窗
    byRanking() {
      if (localStorage.getItem('titleVal')) {
        this.titleVal = JSON.parse(localStorage.getItem('titleVal'));
        this.titleVals = this.titleVal.titleVal3;
      } else {
        this.titleVals = '';
      }
      this.byRankingShow = true;
    },
    // 轮播页面跳转
    swiperPage(formName) {
      if (this.titleVals != '') {
        this.titleVal.titleVal3 = this.titleVals;
        localStorage.setItem('titleVal', JSON.stringify(this.titleVal));
      } else {
        this.titleVal.titleVal3 = '';
        localStorage.setItem('titleVal', JSON.stringify(this.titleVal));
      }
      //拿到当前点击的部门id
      let byRankingDeptId_bl = '';
      for (let i in this.byRankingDeptId) {
        byRankingDeptId_bl = this.byRankingDeptId[i];
      }
      if (byRankingDeptId_bl == '' || byRankingDeptId_bl == 0) {
        byRankingDeptId_bl = 0;
      }
      this.byRankingData.dept_id = byRankingDeptId_bl;
      this.$refs[formName].validate(valid => {
        if (valid) {
          var { href } = this.$router.resolve({
            path: '/deptRankSwiper',
            query: {
              types: '3',
              dept_id: this.byRankingData.dept_id,
              pt_id: 3,
              type: 'all',
              position: this.byRankingData.position
            }
          });
          window.open(href);
        }
      });
    },
    // 提示信息
    tips_close() {
      localStorage.setItem('total_rank_tips', 'true');
      this.tips_show = false;
    },

    // 页面变更
    handleCurrentChange(val) {
      this.formData.page = val;
      this.get_list();
    },
    handleSizeChange(val) {
      this.pageLimit = val;
      this.formData.page_size = this.pageLimit;
      this.get_list();
    },

    get_list() {
      let self = this;
      self.loading = true;
      self.$http('get','/api/integral/statistics/ranking',self.formData,'v2')
        .then(res => {
          if (res.data.code == 1) {
            self.list = res.data.data.list;
            self.total = res.data.data.total;
          } else {
            self.$message.error(res.data.data.msg);
          }
        })
        .finally(() => {
          self.loading = false;
        });
    },
    // 递归判断列表，把最后的children设为undefined
    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;
    }
  },
  mounted() {
    this.tips_show = JSON.parse(localStorage.getItem('total_rank_tips')) ? false : true;

    if (localStorage.getItem('dept_tree')) {
      this.dept_tree = this.getTreeData(JSON.parse(localStorage.getItem('dept_tree')));
    }
    this.get_list();
  }
};
</script>
<style scoped lang="scss">
.search_box {
  /deep/ button:active {
    background: #26a2ff;
  }
  /deep/ button:active .el-icon-search {
    color: #fff;
  }
}
.date-picker-width {
  width: 100% !important;
}
.color_green {
  color: #67c23a;
}
.nopoint_box {
  display: inline-block;
  text-align: center;
  width: 100%;
  margin-bottom: 10px;
}
.noimg {
  display: inline-block;
  width: 110px;
  height: 110px;
  margin: 22px auto 16px;
  /* background:url("/static/images/nodata_default.png") no-repeat center; */
  background-size: 99%;
}
.noperson {
  display: inline-block;
  width: 110px;
  height: 110px;
  line-height: none;
  margin: 22px auto 16px;
  background: url('/static/images/noperson_default.png') no-repeat center;
  background-size: 99%;
}
.title {
  display: block;
  text-align: center;
  font-size: 12px !important;
  line-height: 30px;
  color: #909399 !important;
  padding: 0;
}
.nopoint_box a {
  color: #26a2ff;
}
.chart_content {
  .chart-legend__wrap {
    text-align: right;
    padding: 20px;
    padding-right: 50px;
    & .chart-legend__pink {
      position: relative;
      padding-left: 12px;
      padding-right: 5px;
      &:after {
        content: '';
        position: absolute;
        margin-top: -2px;
        top: 35%;
        left: 0;
        width: 8px;
        height: 8px;
        background: #f56c6c;
        border-radius: 100%;
      }
    }

    & .chart-legend__green {
      position: relative;
      padding-left: 12px;
      &:after {
        content: '';
        position: absolute;
        margin-top: -2px;
        top: 35%;
        left: 0;
        width: 8px;
        height: 8px;
        background: #53b87f;
        border-radius: 100%;
      }
    }
  }
}
.drawer_title {
  font-size: 18px;
  padding: 20px;
}
.manager_statistics_box {
  background-color: #ffffff;
  padding: 20px;
  min-height: calc(100vh - 160px);
  /deep/ .el-row .el-checkbox .el-checkbox__label {
    line-height: 20px;
  }
}
.diy_tip_bg {
  background: #f5f6f9;
  overflow: hidden;
  .diy-tip {
    margin-bottom: 15px;
    border: 1px solid #67c23a;
    padding: 20px 16px;
    p {
      color: #67c23a !important;
      font-size: 15px;
      margin: 0 !important;
      padding-bottom: 4px;
    }
  }
}
/deep/ .el-dialog__body{
  padding:0px 20px 30px;
}
.headLi{
  padding: 4px;
  list-style:disc;
  font-size:14px;
}
</style>
