<template>
  <div>
    <div class="diy_tip_bg" v-show="tips_show">
      <el-alert class="diy-tip" @close="tips_close" type="success" description>
        <p><b>阶段排名可通过月、季、年 3个时间段，利用不同的部门范围和积分筛选条件，从各个维度作积分对比和评优</b></p>
        <li class="headLi">阶段排名包含申请、奖扣、任务、审批、考勤、管理者奖扣目标、自动积分等来源的积分</li>
        <li class="headLi">阶段排名不包含基础分和工龄分</li>
        <!-- <li class="headLi">导出时，额外支持自定义时间段排名、自动积分排名的导出（考勤相关排名请到【考勤】-【考勤分排名】导出）</li> -->
      </el-alert>
    </div>
    <div class="manager_statistics_box">
      <el-form :inline="true">
        <el-form-item label="时间">
          <el-col :span="8">
            <el-select v-model="time_type" placeholder="请选择分类" style="width: 100px;">
              <el-option v-for="item in time_types" :key="item.label" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-col>

          <el-col :span="16">
            <el-date-picker
              v-show="time_type == '2'"
              v-model="export_from.year"
              class="date-picker-width"
              type="year"
              value-format="yyyy"
              placeholder="选择年份排名"
            ></el-date-picker>
            <el-date-picker
              v-show="time_type == '1' || time_type == '月份'"
              v-model="export_from.month"
              class="date-picker-width"
              type="month"
              value-format="yyyy-MM"
              placeholder="选择月份排名"
            ></el-date-picker>

            <season v-if="time_type == '3'" :isActive="true" class="date-picker-width" @confirm="export_quarter_confirm"></season>
          </el-col>
        </el-form-item>

        <el-form-item label="部门">
          <ShowDeptName @confirm="deptConfirm"></ShowDeptName>
        </el-form-item>

        <el-form-item label="积分类型">
          <el-select v-model="formData.pt_id" clearable placeholder="请选择积分类型">
            <el-option v-for="item in point_type" :key="item.id" :label="item.name" :value="item.id" v-if="item.code != 'JX'"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="谁不参与排名" class="takePartInno">
          <div v-if="dropOuOfPerson.length > 0" class="dropOuOfPerson" @click="takePartInno">
            <WWOpenData type="userName" :openid="dropOuOfPerson[0].currentLabel"></WWOpenData>
            <span v-if="dropOuOfPerson.length > 1">&nbsp;+{{ dropOuOfPerson.length - 1 }}</span>
          </div>
          <el-select ref="dropOuOfonref" v-model="formData.exclusion" multiple collapse-tags placeholder="请选择员工">
            <el-option v-for="item in employee_map" :key="item.id" :label="item.name" :value="item.id">
              <span style="float: left"><WWOpenData type="userName" :openid="item.name"></WWOpenData></span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="规则分类" class="inquireRule">
          <el-cascader
            :show-all-levels="false"
            @change="ruleInquire"
            class="date-picker-width"
            v-model="rule_id"
            :options="rule_trees"
            :props="props"
            ref="ruleinquire"
            clearable
            collapse-tags
            placeholder="请选择规则分类"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="人员">
          <el-select v-model="formData.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>

        <el-form-item>
          <el-checkbox v-model="sort" size="medium" label="排名由低到高" border></el-checkbox>
          <el-button type="primary" @click="selectBtn" style="margin-left:20px">查询</el-button>
        </el-form-item>

        <br />
        <el-form-item>
          <el-button type="primary" plain @click="dialogVisibles">导出排名</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="typeName" 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"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :page-size="formData.page_size"
          :current-page="formData.page"
          :total="total"
        ></el-pagination>
      </center>
    </div>
    <!-- 导出弹窗 -->
    <el-dialog title="导出排名" :visible.sync="dialogVisible" width="730px">
      <div style="font-size:15px;margin-top:20px;">系统将按以下已选条件导出对应的排名报表</div>
      <el-form :inline="true">
        <div class="picker_er">
          <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="结束日期"
            ></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="部门">
            <ShowDeptName :deptId.sync="Dc_Data.dept_id"></ShowDeptName>
        </el-form-item>
        <el-form-item label="积分类型">
          <el-select v-model="Dc_Data.pt_id" style="width:120px" placeholder="积分类型">
            <el-option label="B分" :value="3"></el-option>
            <el-option label="A分" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left:20px">
          <el-select v-model="newTaskFormType" style="width:110px;" filterable placeholder="请选择">
            <el-option v-for="item in pullrow" :key="item.id" :label="item.value" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-show="newTaskFormType == 1" class="inquireRule">
          <el-cascader
            :show-all-levels="false"
            @change="ruleInquiredialog"
            class="date-picker-width"
            v-model="rule_id1"
            :options="rule_trees"
            :props="props"
            ref="derive"
            clearable
            collapse-tags
            placeholder="请选择规则分类"
          ></el-cascader>
        </el-form-item>

        <el-form-item v-show="newTaskFormType == 2">
          <el-cascader
            @change="ruleautomatic"
            class="date-picker-width"
            v-model="automaticIntegration"
            :options="rule_list"
            :props="props"
            ref="rule"
            collapse-tags
            placeholder="全部自动积分"
            clearable
          ></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>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth';
import moment from 'moment';
import season from '@/components/season';
export default {
  data() {
    return {
      newTaskFormType: 1,
      pullrow: [
        {
          value: '规则分类',
          id: 1
        },
        {
          value: '自动积分',
          id: 2
        }
      ],
      titleVals: '',
      titleVal: {
        titleVal1: '',
        titleVal2: '',
        titleVal3: ''
      },
      automaticIntegration: [],
      Dc_Data: {
        //导出数据
        value1: '', //时间
        DC_position: '全部', //人员
        dept_id: 0, //部门
        rule_id: [] ,//规则
        pt_id:3
      },

      dialogVisible: false,
      dept_tree: [],
      loading: false,
      formData: {
        dept_id: '0',
        sort: 'DESC',
        pt_id: 3,
        time_type: 1,
        exclusion: [],
        page: 1,
        rule_id: [],
        page_size: 10,
        position: 0 //部门多选删除这个
      },
      total: null,
      rule_trees: null,
      rule_id: null,
      rule_id1: null,
      list: null,
      point_type: [],
      sort: false,
      time_types: [{ label: '月份', value: '1' }, { label: '年份', value: '2' }, { label: '季度', value: '3' }],
      props: { value: 'id', label: 'name', children: 'child', multiple: true },
      time_type: '月份',
      export_from: {
        year: '',
        month: moment().format('YYYY-MM'),
        quarter: ''
      },
      employee_map: JSON.parse(localStorage.getItem('SET_EMPLOYEE_MAP')),
      positions: [{ id: 0, age: 'all', name: '全部' }, { id: 1, age: 'manager', name: '管理者' }, { id: 2, age: 'employee', name: '员工' }],
      tips_show: false,
      byRankingShow: false,
      byRankingData: {
        month: moment().format('YYYY-MM'),
        dept_id: 0,
        position: 'all'
      },
      byRankingDeptId: '',
      byRankingDataRules: {
        month: [{ required: true, message: '请选择月份', trigger: 'blur' }],
        position: [{ required: true, message: '请选择人员范围', trigger: 'blur' }]
      },
      rule_list: [], //自动积分分类列表
      toPdept: 0,
      toPdept1: 0,
      toPdept2: 0,
      dropOuOfPerson: [],

      deriveJobId: '',
      deriveJobIf: 0,
      deriveDis: false,
      aherfUrl: '',
      typeName: 'B分'
    };
  },
  watch: {
    'formData.exclusion'(val) {
      this.$nextTick(() => {
        // .currentLabel
        this.dropOuOfPerson = this.$refs['dropOuOfonref'].selected;
      });
    },
    newTaskFormType(val) {
      this.Dc_Data.rule_id = [];
    },
    sort(val) {
      if (val) {
        this.formData.sort = 'ASC';
      } else {
        this.formData.sort = 'DESC';
      }
    },
    byRankingDeptId(val) {
      this.toPdept1 = val[val.length - 1];
      this.$refs.dept1.dropDownVisible = false;
    },
  },
  components: { season },
  methods: {
    deptConfirm(id){
      this.formData.dept_id = id;
      this.getEmployeeList();
    },
    takePartInno() {
      this.$refs['dropOuOfonref'].visible = true;
    },
    ruleautomatic() {
      let list = this.automaticIntegration;
      let ruleId = [];
      list.forEach(item => {
        ruleId.push(...item);
        // ruleId.push(item.value)
      });
      this.Dc_Data.rule_id = ruleId;
    },
    ruleInquiredialog() {
      this.ruleUtif('derive');
    },
    ruleInquire() {
      this.ruleUtif('ruleinquire');
    },
    ruleUtif(rule) {
      let ruleList = this.$refs[rule].getCheckedNodes();
      let ruleId = [];
      ruleList.forEach(item => {
        ruleId.push(item.value);
      });
      if (rule == 'ruleinquire') {
        this.formData.rule_id = ruleId;
      } else {
        this.Dc_Data.rule_id = ruleId;
      }
      this.$nextTick(() => {
        if (this.$refs[rule].presentTags[1]) {
          this.$refs[rule].presentTags[1].text = '+ ' + (ruleId.length - 1).toString();
        } else {
          if (ruleId.length > 1) {
            let list = {
              closable: false,
              key: -1,
              text: '+ ' + (ruleId.length - 1).toString()
            };
            this.$refs[rule].presentTags[1] = list;
          }
        }
      });
    },
    dialogVisibles() {
      this.newTaskFormType = 1;
      this.dialogVisible = true;
    },
    // 轮播页面跳转
    swiperPage(formName) {
      if (this.titleVals != '') {
        this.titleVal.titleVal2 = this.titleVals;
        localStorage.setItem('titleVal', JSON.stringify(this.titleVal));
      } else {
        this.titleVal.titleVal2 = '';
        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: {
              month: this.byRankingData.month || 0,
              types: '2',
              position: this.byRankingData.position,
              dept_id: this.byRankingData.dept_id,
              pt_id: 3
            }
          });
          window.open(href);
        }
      });
    },
    // // 轮播排名弹窗
    byRanking() {
      if (localStorage.getItem('titleVal')) {
        this.titleVal = JSON.parse(localStorage.getItem('titleVal'));
        this.titleVals = this.titleVal.titleVal2;
      } else {
        this.titleVals = '';
      }
      this.byRankingShow = true;
    },
    // 提示信息
    tips_close() {
      localStorage.setItem('dept_rank_tips', 'true');
      this.tips_show = false;
    },

    // 查询
    selectBtn() {
      switch (this.time_type) {
        case '1':
          this.$set(this.formData, 'month', this.export_from.month);
          this.formData.month ? '' : delete this.formData.month;
          break;
        case '2':
          this.$set(this.formData, 'year', this.export_from.year);
          this.formData.year ? '' : delete this.formData.year;
          break;
        case '月份':
          this.$set(this.formData, 'month', this.export_from.month);
          this.formData.month ? '' : delete this.formData.month;
          break;
        case '3':
          this.$set(this.formData, 'quarter', this.export_from.quarter);
          this.formData.quarter ? '' : delete this.formData.quarter;
          break;
        default:
          break;
      }
      this.formData.page = 1;
      this.$nextTick(() => {
        this.get_list(this.formData);
      });
    },
    // 页面变更
    handleCurrentChange(val) {
      this.formData.page = val;
      this.get_list(this.formData);
    },
    handleSizeChange(val) {
      this.formData.page_size = val;
      this.get_list(this.formData);
    },
    // 选择时间
    export_quarter_confirm(val) {
      this.export_from.quarter = val;
    },
    //请求数据
    get_list(data, bool) {
      if (this.time_type == 1) {
        delete data.year;
        delete data.quarter;
      } else if (this.time_type == 2) {
        delete data.month;
        delete data.quarter;
      } else if (this.time_type == '月份') {
        delete data.year;
        delete data.quarter;
      } else if (this.time_type == 3) {
        delete data.month;
        delete data.year;
      }
      if (bool) {
        data.month = moment().format('YYYY-MM');
      }
      this.loading = true;
      data ? '' : (data = this.formData);
      this.typeName = this.formData.pt_id == 3 ? 'B分' : 'A分';
      data.position = data.position == 'manager' ? 'manager' : data.position == 'employee' ? 'employee' : 'all';
      this.$http('get', '/api/integral/statistics/ranking', data, 'v2').then(res => {
            this.list = res.data.data.list;
            this.total = res.data.data.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取积分规则
    get_rule_tree() {
      this.$http('get', '/api/integral/rule/trees', { cycle_type: '1' }).then(res => {
          if (res.data.code == 1) {
            // let arr = res.data.data.tree
            this.rule_trees = this.getTreeData(res.data.data.rule_tree);
          } else {
            this.$message.error(res.data.data.msg);
          }
        })
        .catch(e => {
          this.$message.error('获取积分规则失败');
        });
    },
    // 递归判断列表，把最后的children设为undefined
    getTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].child !== undefined) {
          if (data[i].child.length < 1) {
            // children若为空数组，则将children设为undefined
            data[i].child = undefined;
          } else {
            // children若不为空数组，则继续 递归调用 本方法
            this.getTreeData(data[i].child);
          }
        }
      }
      return data;
    },
    // 规则递归 children
    recursionRule(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.recursionRule(data[i].children);
        }
      }
      return data;
    },
    getEmployeeList() {
      this.$http('get', '/api/employee/index', { dept_id: this.formData.dept_id, is_official: 1, page_size: 2000, page: 0 })
        .then(res => {
          if (res.data.code == 1) {
            this.employee_map = res.data.data.list;
          } else {
            this.$message.error(res.data.data.msg);
          }
        })
        .finally(() => {});
    },
    downloadResult() {
      if (this.deriveJobIf < 5) {
        this.$http('get', '/api/download/result', {
          job_id: this.deriveJobId
        }).then(res => {
          if (res.data.code == 1) {
            this.aherfUrl = res.data.data.url;
            this.deriveJobId = '';
            this.deriveDis = false;
            this.$nextTick(() => {
              this.$refs.aherfClick.click();
            });
          } else {
            setTimeout(() => {
              this.deriveJobIf++;
              this.downloadResult();
            }, 2000);
          }
        });
      } else {
        this.deriveJobIf = 0;
        this.deriveJobId = '';
        this.deriveDis = false;
        this.aherfUrl = '';
        this.$message.warning('导出超时');
      }
    },
    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';
      //部门
      this.deriveDis = true;
      let params = {
        employee_id: this.$store.getters.user_info.id,
        position: this.Dc_Data.DC_position,
        dept_id:this.Dc_Data.dept_id,
        pt_id:this.Dc_Data.pt_id
      };
      this.Dc_Data.value1 ? (params.start_date = this.Dc_Data.value1[0]) : '';
      this.Dc_Data.value1 ? (params.end_date = this.Dc_Data.value1[1]) : '';
      this.Dc_Data.rule_id.length > 0 ? (params.rule_id = this.Dc_Data.rule_id) : '';
      this.dialogVisible = false;
      this.$downloadFile('api/download/ranking/v2',params,this.$route.path);
    },

    // 获取规则分类 与 规则细则
    get_rule_trees() {
      this
        .$http('get', '/api/integral/rule/trees', { cycle_type: '2' })
        .then(res => {
          if (res.data.code == 1) {
            this.rule_list = this.getTreeData(res.data.data.rule_tree);
          }
        })
        .finally(() => {});
    }
  },
  mounted() {
    this.getEmployeeList();
    this.tips_show = JSON.parse(localStorage.getItem('dept_rank_tips')) ? false : true;
    if (localStorage.getItem('dept_tree')) {
      this.dept_tree = this.getTreeData(JSON.parse(localStorage.getItem('dept_tree')));
    }
    if (localStorage.getItem('SET_POINT_TYPES')) {
      this.point_type = JSON.parse(localStorage.getItem('SET_POINT_TYPES'));
    }
    this.get_list(this.formData, true);
    this.get_rule_tree();
    this.get_rule_trees(); //自动积分列表
  }
};
</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(/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(/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 {
  top: 21%;
}
.picker_er {
  margin-top: 20px;
}
.el-range-editor--medium.el-input__inner {
  width: 280px;
}
/deep/ .elCascaderWidht .el-input .el-input__inner {
  width: 210px;
}
// /deep/ .el-cascader .el-input .el-input__inner {
//   width: 150px;
// }
.el-checkbox.is-bordered.el-checkbox--medium {
  padding: 9px 20px 7px 10px;
}

/deep/ .el-dialog__body {
  padding: 0px 20px 30px;
}
.headLi {
  padding: 4px;
  list-style: disc;
  font-size: 14px;
}

.inquireRule /deep/ .el-icon-close {
  display: none;
}
.takePartInno /deep/ .el-input__inner {
  height: 36px;
  overflow: hidden;
}
.takePartInno /deep/ .el-tag.el-tag--info {
  display: none;
}
// .el-input__inner
.dropOuOfPerson {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  z-index: 9;
  margin: 1px 0 0 1px;
  padding-left: 14px;
  background-color: #ffffff;
  color: #1d1d1d;
  width: 170px;
  overflow: hidden;
  cursor: pointer;
  height: 34px;
  line-height: 34px;
  border-radius: 5px;
}
</style>
