<template>
  <div v-loading="loading" class="PkDetailBox">
    <div style="padding:15px;">
      <el-row :gutter="20">
        <el-col :span="16">
          <h3 style="margin:0; font-size: 18px; margin-top:8px;">
            {{pk_info.name}}
            <span
              style="font-weight: normal; font-size: 16px;"
              v-if="pk_info.employee_ids"
            >PK总人数：{{pk_info.employee_ids.length}}人</span>
            <el-button v-if="is_manager" type="text" @click="pkInfoEdit">设置</el-button>
            <div style="font-size: 16px; color:#999; margin-top:12px;">
              <span
                style="font-weight: normal; font-family: '微软雅黑'; font-size:16px;"
              >{{pk_info.start_time}}至{{pk_info.end_time}}</span>
            </div>
          </h3>
        </el-col>
        <el-col :span="8">
          <el-row :gutter="15" v-show="mine" class="rankListBox">
            <el-col v-if="false" :span="24" style="text-align: left;">
              <span style="color:#333;" v-show="mine && myTeamName != ''">组别：{{myTeamName}}</span>
            </el-col>
            <el-col :span="8">
              <p>{{member_data.point}}</p>我的总分
            </el-col>
            <el-col :span="8">
              <p>{{member_data.rank_team}}</p>团队排名
            </el-col>
            <el-col :span="8">
              <p>{{member_data.rank_all}}</p>总排名
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>
    <el-tabs v-model="dataTab">
      <el-tab-pane label="排名" name="first">
        <div style="padding:15px;">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <PkRankLeader ref="PkRankLeaderCom" :list.sync="rankList.ranking_leader"></PkRankLeader>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <PkRankTeam ref="PkRankTeamCom" :list.sync="rankList.ranking_team"></PkRankTeam>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="grid-content bg-purple" style="border-right: none;">
                <PkRankMember ref="PkRankMemberCom" :list.sync="rankList.ranking_employee" :teams.sycn="rankList.teams"></PkRankMember>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane label="规则" name="second">
        <div style="padding:15px">
          <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">
            <PkRuleCreate v-if="is_manager" ref="PkRuleCreateCom"></PkRuleCreate>

            <div
              class="gap-right-8"
              style="display:inline-block; width:300px; margin-top:10px; margin-bottom:0;"
            >
              <el-input
                placeholder="输入关键词查找"
                ref="search-bar"
                v-model="rule_keyword"
                class="input-with-select"
                @keyup.enter.native="loadPkRule"
              >
                <el-button slot="append" icon="el-icon-search" @click="loadPkRule"></el-button>
              </el-input>
            </div>
          </div>

          <el-table
            stripe
            v-loading="loading"
            :data="RuleList"
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column label="操作" v-if="is_manager">
              <template slot-scope="scope">
                <div>
                  <el-button type="text" @click="editRule(scope.row)">修改</el-button>
                  <el-button type="text" @click="confirmDeleteRule(scope.row.id)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="积分明细" name="third">
        <div style="padding:15px;">
          <div style="padding:15px 0;" class="inline-block-btn-list">
            <el-date-picker
              class="gap-right-8 first-element-btn"
              v-model="RulePagination.filter.time_range"
              type="daterange"
              @change="loadLogList"
              value-format="timestamp"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>

            <div class="gap-right-8" style="display:inline-block; width:300px; margin-bottom:0;">
              <el-input
                placeholder="输入备注查找"
                ref="search-bar"
                v-model="RulePagination.filter.keywords"
                class="input-with-select"
                @keyup.enter.native="loadLogList"
              >
                <el-button slot="append" icon="el-icon-search" @click="loadLogList"></el-button>
              </el-input>
            </div>

             <!-- 积分时间录入 v-if="can_record && !is_manager"  管理员 -->
            <IntegralPkCreateApplicationLeaderBtn  v-if="can_record && !is_manager" :pk_id="pk_id"></IntegralPkCreateApplicationLeaderBtn>

              <!-- 积分团队录入   v-if="can_record && is_manager"  团队   -->
            <IntegralPkCreateApplicationTeamBtn   :pk_id="pk_id"></IntegralPkCreateApplicationTeamBtn>

            <!-- 录入个人积分  v-if="can_record && is_manager" -->
            <IntegralPkCreateApplicationBtn :pk_id="pk_id"></IntegralPkCreateApplicationBtn>
          </div>
          <el-table
            v-loading="loading"
            ref="multipleTable"
            :data="PointEvent"
            :border="false"
            tooltip-effect="dark"
          >
            <el-table-column prop="member.name" label="姓名">
              <template slot-scope="scope">
                <div v-if="scope.row.target_name != null">{{ scope.row.target_name }}</div>
                <div v-if="scope.row.target_name == ''">团队积分</div>
              </template>
            </el-table-column>

            <el-table-column prop="member.name" label="团队">
              <template slot-scope="scope">
                <div v-if="scope.row.target_name != null">{{ scope.row.team_name }}</div>
                <div v-if="scope.row.target_name == null">{{ scope.row.team_name }}</div>
              </template>
            </el-table-column>

            <el-table-column label="积分规则" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <div>{{ scope.row.rule.name }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" :show-overflow-tooltip="true"></el-table-column>

            <el-table-column label="分值">
              <template slot-scope="scope">
                <span
                  v-bind:class="scope.row.point < 0 ? 'point-negative' : 'point-positive'"
                >{{ scope.row.point }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createtime" label="事件日期" >
              <template slot-scope="scope">
                <span
                >{{ scope.row.event_time }}</span>
              </template>

            </el-table-column>
            <el-table-column label="操作" v-if="is_manager">
              <template slot-scope="scope">
                <el-button type="text" @click="confirmDelete(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            layout="total,prev, pager, next"
            :page-size="RulePagination.pageLimit"
            :page-sizes="[10, 20, 50, 100]"
            :total="RulePagination.totalCount"
            :current-page.sync="RulePagination.currentPage"
            @current-change="changePage"
          ></el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="参与团队" name="fourth">
        <div style="padding:15px;">
          <el-row :gutter="20">
            <el-col :lg="12" v-for="(item,index) in TeamList" :key="index">
              <a
                href="javascript:void(0);"
                @click="loadTeamEditInfo(item)"
                style="display: block;"
              >
                <el-card class="box-card card-box-item" shadow="hover" style="margin-top:15px;">
                  <div style="line-height: 3;">
                    队名：{{item.name}}
                    <el-button
                      v-show="mine===false"
                      type="text"
                      style="float:right;"
                      @click="teamDelete(item.id, $event)"
                    >删除</el-button>
                  </div>
                  <el-tag
                    v-for="tag in item.members"
                    :key="tag.id"
                    :type="item.leader_id == tag.id?'warning':''"
                  >
                    {{tag.name}}
                    <span v-if="item.leader_id==tag.id">（队长）</span>
                  </el-tag>
                </el-card>
              </a>
            </el-col>

            <el-col v-show="is_manager" :lg="12">
              <a
                href="javascript:void(0);"
                @click="addTeam()"
                style="display: block; text-align: center;"
              >
                <el-card class="box-card card-box-item" shadow="hover" style="margin-top:15px;">
                  <el-button type="text">创建新团队</el-button>
                </el-card>
              </a>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      modal-append-to-body
      :title="setTeamTitle"
      top="40px"
      width="620px"
      :visible.sync="dialogAddteamVisible"
      :close-on-click-modal="false"
    >
      <div v-loading="teameditloading">
        <div style="padding:0 40px;">
          <el-form
            :model="teamInfo"
            ref="newTeamForm"
            :rules="teamFormRules"
            @submit.native.prevent
          >
            <el-steps :active="setTeamActive" finish-status="success" simple>
              <el-step title="团队名称"></el-step>
              <el-step title="选择成员"></el-step>
              <el-step title="设置队长"></el-step>
            </el-steps>
            <el-form-item
              v-show="setTeamActive==0"
              label="队名"
              prop="name"
              label-width="55px"
              style="padding:50px 100px"
            >
              <el-input v-model="teamInfo.name" :value="teamInfo.name" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item
              prop="name"
              v-show="setTeamActive==2"
              style="padding:50px 0"
            >

              <EmployeeSelectorCell v-if="member_list.length > 0" title="选择队长" v-model="leader_list" :employee_list.sync="member_list" :multi="false" :max="1"></EmployeeSelectorCell>

            </el-form-item>
            <el-form-item v-show="setTeamActive==1" prop="member" label-width="0" style="padding:50px 0">

              <EmployeeSelectorCell :employee_not_select.sync="employee_not_select" title="选择队员" v-model="member_list" :max="20"></EmployeeSelectorCell>


            </el-form-item>
          </el-form>
        </div>

        <div
          slot="footer"
          class="dialog-footer"
          style="text-align:center;"
          v-show="setTeamActive!=2"
        >
          <el-button @click="dialogAddteamVisible = false">取 消</el-button>
          <el-button @click="setTeamActive--" v-show="setTeamActive>0">上一步</el-button>
          <el-button type="primary" @click="setTeamNext" v-show="setTeamActive!=2">下一步</el-button>
        </div>

        <div
          slot="footer"
          class="dialog-footer"
          style="text-align:center;"
          v-show="setTeamActive==2"
        >
          <el-button @click="dialogAddteamVisible = false">取 消</el-button>
          <el-button @click="setTeamActive--" v-show="setTeamActive==2">上一步</el-button>

          <el-button type="primary" :loading="loading" @click="saveTeamInfo">确 定</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      title="设置PK"
      :visible.sync="dialogPkVisible"
      width="600px"
      :close-on-click-modal="false"
      :before-close="cancelHandle"
    >
      <el-form
        :model="pkInfo"
        ref="newPkForm"
        :rules="PKFormRules"
        @submit.native.prevent
        style="padding:0 30px;"
      >
        <div style="padding:50px 65px; padding-top:30px; padding-bottom:20px;">
          <el-form-item label="名称" prop="name" label-width="55px">
            <el-input v-model="pkInfo.name" :value="pkInfo.name" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="时间" prop="time_range[0]" label-width="55px">
            <el-date-picker
              style="width:315px"
              v-model="pkInfo.time_range"
              type="daterange"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>

          <el-alert
            style="margin-bottom:10px;"
            title
            type="success"
            :closable="false"
          >管理员可以修改PK的设置，能为PK成员录入积分</el-alert>
          <el-form-item prop="manager_ids">
            <el-select
              v-model="pkInfo.manager_ids"
              filterable
              multiple
              :multiple-limit="3"
              placeholder="选择管理员（最多3个）"
              style="width:370px;"
            >
              <el-option
                v-for="item in employeeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id.toString()"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label prop="manager_ids" label-width="55px">
            <el-checkbox v-model="pkInfo.leader_can_record">队长能为队员录入积分</el-checkbox>
          </el-form-item>
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelHandle">取 消</el-button>

        <el-button type="primary" @click="savePKInfo">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import EmployeeSelectorCell from '@/views/common/EmployeeSelectorCard'
import IntegralPkCreateApplicationBtn from "./IntegralPkCreateApplicationBtn";
import IntegralPkCreateApplicationTeamBtn from "./IntegralPkCreateApplicationTeamBtn";
import PkRuleCreate from "./PkRuleCreate";
import PkRankLeader from "./PkRankLeader";
import PkRankMember from "./PkRankMember";
import PkRankTeam from "./PkRankTeam";
import IntegralPkCreateApplicationLeaderBtn from "./IntegralPkCreateApplicationLeaderBtn";
import qs from "qs";

export default {
  components: {
    EmployeeSelectorCell,
    IntegralPkCreateApplicationTeamBtn,
    IntegralPkCreateApplicationBtn,
    IntegralPkCreateApplicationLeaderBtn,
    PkRuleCreate,
    PkRankLeader,
    PkRankMember,
    PkRankTeam
  },
  props: {
    pk_id: {
      type: String,
      default: ""
    }
  },
  watch: {
    dataTab(new_val, old_val) {
      let self = this;
      if (new_val == "first") {
        //在这里获取排名
        self.loadRankList()
      }
    }
  },
  data() {
    return {
      leader_list: [],
      member_list: [],
      employee_not_select: [],
      isNew: 1,
      employeeOptions: [],
      mine: false,
      PKFormRules: {
        name: [
          { required: true, message: "请输入PK名称", trigger: "blur" },
          { min: 3, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" }
        ],
        "time_range[0]": [
          { required: true, message: "请选择时间", trigger: "blur" }
        ]
      },

      myTeamName: "",
      pkInfo: {
        id: 0,
        name: "",
        time_range: [],
        manager_ids: [],
        leader_can_record: false
      },

      log_time_range: [],

      rule_keyword: "",
      is_manager: true,

      dialogPkVisible: false,
      /*编辑团队的配置*/
      dialogAddteamVisible: false,
      setTeamTitle: "创建团队",
      is_leader: false,

      saveTeamInfoApi: "/integral.php/integral_pk_team/add",
      setTeamActive: 0,
      teameditloading: false,
      EmployeeMap: {},
      teamInfo: {
        id: 0,
        name: "",
        leader_id: 0,
        member: []
      },
      teamFormRules: {
        name: [
          { required: true, message: "请输入团队名称", trigger: "blur" },
          { min: 3, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" }
        ]
      },
      assignableList: [],
      can_record: false,
      loading: false,
      profile: this.$store.getters.user_info,
      RulePagination: {
        pageLimit: 5,
        totalCount: 0,
        currentPage: 1,
        filter: {
          keywords: "",
          time_range: null
        }
      },
      PointEvent: [],
      tableData: [],
      RuleList: [],
      TeamList: [],
      pk_info: [],
      dataTab: "first",
      rankList: {ranking_employee: [], ranking_leader: [], ranking_team: [], teams: []},
      member_data: { rank_team: 0, rank_all: 0, point: 0 }
    };
  },
  methods: {
    loadRankList: function () {
      if(this.pk_id == 0){
        return false
      }
      let params = {
        pk_id: this.pk_id
      }
      var self = this
      self.loading = true
      this.$http('get','/api/integral/pk',params).then(function (response) {
        if (response.status == 200) {
          self.loading = false
          let jsonData = response.data.data.ranking_team
          try {
            self.rankList = {
              "ranking_employee": [
                {
                  "employee_id":1,
                  "employee_name":"姓名",
                  "rank":1,
                  "point":11
                },
                {
                  "employee_id":1,
                  "employee_name":"姓名",
                  "rank":1,
                  "point":11
                },
                {
                  "employee_id":1,
                  "employee_name":"姓名",
                  "rank":1,
                  "point":11
                },
                {
                  "employee_id":1,
                  "employee_name":"姓名",
                  "rank":1,
                  "point":11
                }
              ],
              "ranking_leader": [
                {
                  "employee_id":1,
                  "employee_name":"姓名",
                  "rank":1,
                  "point":11
                }
              ],
              "ranking_team": [
                {
                  "team_id":1,
                  "team_name":"队伍名",
                  "rank":1,
                  "point":11
                },
              ],
              "teams":[
                {
                  "team_name":"队伍1",
                  "ranking":[
                    {
                      "employee_id":1,
                      "employee_name":"姓名",
                      "rank":1,
                      "point":11
                    }
                  ]
                },
                {
                  "team_name":"队伍2",
                  "ranking":[
                    {
                      "employee_id":1,
                      "employee_name":"姓名2",
                      "rank":1,
                      "point":11
                    }
                  ]
                },
                {
                  "team_name":"队伍3",
                  "ranking":[
                    {
                      "employee_id":1,
                      "employee_name":"姓名3",
                      "rank":1,
                      "point":11
                    }
                  ]
                }
              ]
            }
          } catch (err) {

          }
        }
      }).catch(function (error) {

      })
    },
    cancelHandle() {
      this.dialogPkVisible = false;
      // this.pkInfo.manager_ids = [];
    },
    dateFormatter: function(row, column, cellValue) {
     // return this.$moment(cellValue * 1000).format("YYYY年MM月DD日");
    },
    // 修改规则
    editRule(row) {
      let pk_id = this.pk_id;
      let data = {};
      data.row = row;
      data.pk_id = pk_id;
      const self = this;
      self.$refs["PkRuleCreateCom"].loadInfo(data);
    },

    pkInfoEdit() {
      const self = this;
      self.dialogPkVisible = true;
      this.loadPkDetail()
    },
    savePKInfo() {
      const self = this;
      const form = this.$refs["newPkForm"];
      self.pkInfo.leader_can_record = self.pkInfo.leader_can_record === true ? 1 : 0;
      let params = {};
      params.pk_id = self.pkInfo.id;
      params.name = self.pkInfo.name;
      params.start_time = self.pkInfo.time_range[0];
      params.end_time = self.pkInfo.time_range[1];
      params.manager_ids = self.pkInfo.manager_ids;
      params.leader_can_record = self.pkInfo.leader_can_record;
      form.validate(valid => {
        if (valid) {
          this.$http("post","/api/integral/pk",params,
            // headers: {
            //   "Content-Type": "application/x-www-form-urlencoded"
            // }
          )
            .then(function(response) {
              setTimeout(function() {
                self.isRequest = false;
              }, 200);

              var message = "";
              var status = 0;
              if (response.status == 200) {
                var data = response.data;

                message = data.msg;

                if (data.code == 1) {
                  self.$message({
                    message: message,
                    type: "success"
                  });
                  self.dialogPkVisible = false;
                  self.loadPkDetail();
                  self.$emit('getlistnew')
                  form.clearValidate();
                } else {
                  self.$message({
                    message: message,
                    type: "error"
                  });
                }
              } else {
                message = "服务器太忙了";
              }
            })
            .catch(function(error) {
              console.log(error);
            });
        } else {
          return false;
        }
      });
    },

    teamDelete(id, e) {
      e.cancelBubble = true;
      this.$confirm("确定要删除此团队吗？", "删除团队", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const self = this;

          let params = {
            team_id: id,
            pk_id: this.pk_id
          };
          this.$http("delete","/api/integral/pk/teams",params,'','',
            {transformRequest: [
              data => {
                let paramArray = new Array();
                for (let it in data) {
                  paramArray.push(
                    encodeURIComponent(it) + "=" + encodeURIComponent(data[it])
                  );
                }
                return paramArray.join("&");
              }
            ]},
            // headers: {
            //   "Content-Type": "application/x-www-form-urlencoded"
            // }
          )
            .then(function(response) {
              if (response.status == 200) {
                let jsonData = response.data;
                try {
                  if (jsonData.code == 1) {
                    self.$message({
                      message: jsonData.msg,
                      type: "success"
                    });
                    self.loadPkTeam();
                  } else {
                    self.$message({
                      message: jsonData.msg,
                      type: "error"
                    });
                  }
                } catch (err) {
                  console.log(err);
                }
              }
            })
            .catch(function(error) {
              console.log(error);
            });
        })
        .catch(() => {});
    },
    set_employee_not_select(member){
      this.employee_not_select = []
      for(let i in this.TeamList){
        for(let j in this.TeamList[i].members){
          if(member.indexOf(this.TeamList[i].members[j].id) < 0){
            this.employee_not_select.push(this.TeamList[i].members[j].id)
          }
        }
      }
    },

    //  编辑保存团队创建
    saveTeamInfo() {
      const self = this;
      const form = this.$refs["newTeamForm"];
      this.loading = true
      let params = {};
      params.team = {};

      let member = []
      for(let i in this.member_list){
        member.push(this.member_list[i].id)
      }
      let leader = this.leader_list[0].id
      this.teamInfo.member = member
      this.teamInfo.leader_id = leader


      if(this.isNew == 1) {
        // 新增
          params.team.team_name = self.teamInfo.name;
          params.team.team_member = self.teamInfo.member;
          params.team.pk_id = self.pk_id;
          params.team.team_id = 0;
          params.team.team_leader = self.teamInfo.leader_id
      }else {
          params.team.team_name = self.teamInfo.name;
          params.team.team_member = self.teamInfo.member;
          params.team.pk_id = self.pk_id;
          params.team.team_id = self.teamInfo.id;
          params.team.team_leader = self.teamInfo.leader_id
      }

      form.validate(valid => {
        if (valid) {
          this.$http("post",self.saveTeamInfoApi,params,
            // headers: {
            //   "Content-Type": "application/x-www-form-urlencoded"
            // }
          )
            .then(function(response) {
              setTimeout(function() {
                self.isRequest = false;
              }, 200);
              var message = "";
              var status = 0;
              if (response.status == 200) {
                var data = response.data;
                self.loading = false
                message = data.msg;

                if (data.code == 1) {
                  self.$message({
                    message: message,
                    type: "success"
                  });
                  self.dialogAddteamVisible = false;
                  self.loadPkTeam();
                  form.clearValidate();
                } else {
                  self.$message({
                    message: message,
                    type: "error"
                  });
                }
              } else {
                message = "服务器太忙了";
              }
            })
            .catch(function(error) {
              console.log(error);
            });
        } else {
          return false;
        }
      });
    },

    setTeamNext() {
      const self = this;
      const form = this.$refs["newTeamForm"];
      form.validate(valid => {
        if (valid) {
          self.setTeamActive++;
          if (
            self.setTeamActive == 2 &&
            self.teamInfo.member.indexOf(self.teamInfo.leader_id) < 0
          ) {
            self.teamInfo.leader_id = self.teamInfo.member[0];
          }
        }
      });
    },

    addTeam() {
      this.member_list = []
      this.leader_list = []
      this.set_employee_not_select([])
      this.isNew = 1;
      let startTime = new Date(this.pkInfo.starttime * 1000);
      let nowTime = new Date();
      if (nowTime > startTime) {
        this.$message({
          message: "当前PK进行中或者已经结束,不能添加团队",
          type: "warning"
        });
        return false
      }

      this.setTeamActive = 0;
      this.setTeamTitle = "创建团队";
      this.saveTeamInfoApi = "/api/integral/pk/teams";
      this.dialogAddteamVisible = true;
      this.teameditloading = true;
      const self = this;
      this.$nextTick(() => {
        const form = self.$refs["newTeamForm"];
        form.clearValidate();
      });
      let params = {
        pk_id: this.pk_id
      };

      //  获取员工列表
      this.$http('get',"/api/integral/pk/members",params)
        .then(function(response) {
          if (response.status == 200) {
            let jsonData = response.data.data.list;
            try {
              self.teamInfo = {
                name: "",
                leader_id: 0,
                member: [],
                pk_id: 0
              };

              self.assignableList = [];
              for (let i in jsonData) {
                self.assignableList.push({
                  key: jsonData[i].id,
                  label: jsonData[i].name
                });
              }
              self.EmployeeMap = {};
              for (let i in jsonData) {
                self.EmployeeMap[jsonData[i].id] =
                  jsonData[i]
              }
              self.teameditloading = false;
            } catch (err) {
              console.log(err);
            }
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    loadTeamEditInfo(item) {
      this.isNew = 2;
      let startTime = new Date(this.pkInfo.starttime * 1000);
      let nowTime = new Date();
      this.TeamId = item.id;
      this.dialogAddteamVisible = true;
      this.setTeamActive = 0;
      this.setTeamTitle = "修改团队";
      this.saveTeamInfoApi = "/api/integral/pk/teams";
      const self = this;
      this.$nextTick(() => {
        const form = self.$refs["newTeamForm"];
        form.clearValidate();
      });
      this.member_list = item.members
      this.leader_list = [item.leader]
      let members = []
      for(let i in this.member_list){
        members.push(this.member_list[i].id)
      }
      this.set_employee_not_select(members)
      self.teamInfo.name = item.name;
      self.teamInfo.id = item.id;
    },

    loadPkDetail() {
      if (isNaN(this.pk_id)) {
        return false;
      }
      var self = this;
      this.loadPkTeam();   // 参与团队
      this.loadPkRule();   // 规则
      this.loadLogList();  // 积分明细
      this.get_member_data();  // 排名
      this.loadWidgetData();  // 加载员工
      this.loading = true;
      this.Formdata;

      let params = {
        pk_id: this.pk_id
      };
      this.$http('get','/api/integral/pk/info',params)
      .then(function(res) {
        if(res.data.code == 1) {
          let jsonData = res.data.data;
          self.pk_info = jsonData;
          self.pkInfo.id = jsonData.id;
          self.pkInfo.name = jsonData.name;
          let time_range = [];
          var date = new Date(jsonData.start_time);
          let time3 = Date.parse(date);
          time_range.push(jsonData.start_time, jsonData.end_time)
          self.pkInfo.time_range = time_range;
          self.pkInfo.starttime = jsonData.start_time;
          self.pkInfo.manager_ids = jsonData.manager_ids;
           self.pkInfo.leader_can_record = jsonData.leader_can_record == 1 ? true : false;
           self.$nextTick(() => {
              self.$refs["PkRankMemberCom"].pk_id = jsonData.id;
              self.$refs["PkRankTeamCom"].pk_id = jsonData.id;
              self.$refs["PkRankLeaderCom"].pk_id = jsonData.id;
              self.loadRankList()
           })

        }
      })
    },
    loadPkTeam() {
      this.loading = true;
      let params = {
        pk_id: this.pk_id,
        page: 1,
        page_size: 20
      };
      var self = this;
      this.$http('get',"/api/integral/pk/teams",params)
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false;
            let jsonData = response.data.data.list.list;
            try {
              self.TeamList = jsonData;
            } catch (err) {
              console.log(err);
            }
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },

    get_member_data() {

    },

    loadPkRule() {
      this.loading = true;
      let params = {
        pk_id: this.pk_id,
        page: 1,
        page_size: 30,
        keywords: this.rule_keyword
      };
      var self = this;
      this.$http('get',"/api/integral/pk/rules",params)
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false;
            let jsonData = response.data.data;
            try {
              self.RuleList = jsonData.list.list;
            } catch (err) {
              console.log(err);
            }
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    changePage: function(current) {
      if (isNaN(current) || current < 1) {
        return false;
      }
      this.loadLogList();
    },
    loadLogList() {
      this.loading = true;
      var self = this;

      let params = {
        pk_id: this.pk_id,
        page: self.RulePagination.currentPage,

        offset:
          (self.RulePagination.currentPage == 1
            ? 0
            : self.RulePagination.currentPage - 1) *
          self.RulePagination.pageLimit,
        page_size: self.RulePagination.pageLimit,
        keywords: self.RulePagination.filter.keywords
      };
      if (self.RulePagination.filter.time_range != null) {
        params["time_range"] = [
          self.RulePagination.filter.time_range[0] / 1000,
          self.RulePagination.filter.time_range[1] / 1000
        ];
      }
      this.$http('get',"/api/integral/pk/log",params)
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false;
            let jsonData = response.data.data;
            try {
              self.PointEvent = jsonData.list;
              self.RulePagination.totalCount = jsonData.total;
            } catch (err) {
              console.log(err);
            }
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },

    deleteRule: function(id) {
      if (!id) {
        return false;
      }

      let params = {
        rule_id: id,
        pk_id: this.pk_id
      };
      var self = this;

      this.$http("delete","/api/integral/pk/rules",params,'','',
        {transformRequest: [
          data => {
            let paramArray = new Array();
            for (let it in data) {
              paramArray.push(
                encodeURIComponent(it) + "=" + encodeURIComponent(data[it])
              );
            }
            return paramArray.join("&");
          }
        ]},
        // headers: {
        //   "Content-Type": "application/x-www-form-urlencoded"
        // }
      )
        .then(function(response) {
          var message = "";
          var status = 0;
          if (response.status == 200) {
            var data = response.data;

            message = data.msg;

            if (data.code == 1) {
              self.$message({
                message: message,
                type: "success"
              });
              self.loadPkRule();
            } else {
              self.$message({
                message: message,
                type: "error"
              });
            }
          } else {
            message = "服务器太忙了";
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },

    deleteLog: function(id) {
      if (!id) {
        return false;
      }
      let params = {
        log_id: id,
        pk_id: this.pk_id
      };
      var self = this;

      this.$http("delete","/api/integral/pk/log",params,'','',
        {transformRequest: [
          data => {
            let paramArray = new Array();
            for (let it in data) {
              paramArray.push(
                encodeURIComponent(it) + "=" + encodeURIComponent(data[it])
              );
            }
            return paramArray.join("&");
          }
        ]},
        // headers: {
        //   "Content-Type": "application/x-www-form-urlencoded"
        // }
      )
        .then(function(response) {
          var message = "";
          var status = 0;
          if (response.status == 200) {
            var data = response.data;

            message = data.msg;

            if (data.code == 1) {
              self.$message({
                message: message,
                type: "success"
              });
              self.loadLogList();
            } else {
              self.$message({
                message: message,
                type: "error"
              });
            }
          } else {
            message = "服务器太忙了";
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    confirmDelete(id) {
      this.$confirm("确定要删除此事件吗？", "删除事件", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteLog(id);
        })
        .catch(() => {});
    },

    loadWidgetData: function() {
      var self = this;
      this.$http('get',"/api/integral/pk/members",{
            // id: this.profile.id,
            // employee_list: 1
            pk_id: this.pk_id})
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data.data;
            console.log(jsonData)
            try {
              self.employeeOptions = jsonData.list;
            } catch (err) {
              console.log(err);
            }
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },

    confirmDeleteRule(id) {
      this.$confirm("确定要删除此规则吗？", "删除规则", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteRule(id);
        })
        .catch(() => {});
    }
  },

  created() {
    const self = this;
  }
};
</script>
<style>
.PkDetailBox .grid-content {
  min-height: 300px;
  position: relative;
  border-right: 1px solid #eee;
  padding-right: 20px;
}
.PkDetailBox .no-data-img {
  max-width: 100%;
}
.PkDetailBox .grid-content .el-table__column-filter-trigger {
  line-height: 23px;
}
.PkDetailBox .rankListBox {
  text-align: center;
  margin-top: 9px;
  color: #999;
}
.PkDetailBox .rankListBox p {
  font-size: 24px;
  font-weight: bold;
  margin: 8px 0;
  color: #333;
}
</style>
