<template>
  <div class="box boxMinHeight">
    <PageHead :phName="packageName"></PageHead>
    <div class="main">
      <div class="flex-box-ce">
        <div class="flex-1">
          <span>
            参与员工：{{ package_employee_num }}人
            <span class="yellow" v-if="employee_no_config">，{{ employee_no_config }}人未加入到等级配置</span>
          </span>
          <el-button v-if="employee_no_config" type="text" style="margin-left: 10px;" @click="openCy()">查看</el-button>
        </div>
        <div>
          <el-button class="primaryBtn" @click="openConfiguration(1)">新增等级配置</el-button>
          <el-button class="primaryBtn" @click="openIsExecute()">执行等级配置</el-button>
          <!--        <el-dropdown  style="margin-left:11px;" @command="handleCommand">
              <el-button  class="primaryBtn">更多</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="(item, index) in dropdownMenu" :key="index" :command="item.key">{{ item.name }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown> -->
        </div>
      </div>
      <div class="table-box" style="margin-top: 30px;">
        <el-table stripe :data="tableData" :header-cell-style="{ background: '#ECF5FF' }" v-loading="loading">
          <el-table-column prop="name" label="等级配置名称"></el-table-column>
          <el-table-column prop="pl_exec" label="状态">
            <template slot-scope="scope">
              <span v-if="scope.row.pl_exec == 0" class="yellow">未执行配置</span>
              <span v-else class="blue">已执行配置</span>
            </template>
          </el-table-column>
          <el-table-column label="等级规则">
            <template slot-scope="scope">
              <div v-if="scope.row.config.level_type == 1" class="flex-box-ce"><span>分数区间对应</span></div>
              <div v-else class="flex-box-ce"><span>强制正态配置</span></div>
              <div v-if="scope.row.config.level_scope.levels.length > 0" class="flex-box-ce">
                <span v-for="(item, index) in scope.row.config.level_scope.levels">
                  {{ item.name }}
                  <span v-if="scope.row.config.level_scope.levels.length != index + 1">,</span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="employee_num" label="参与人员">
            <template slot-scope="scope">
              <span>{{ scope.row.employee.length }}人</span>
            </template>
          </el-table-column>
          <el-table-column prop="score_ok" label="完成评分">
            <template slot-scope="scope">
              <span>{{ scope.row.score_ok }}人</span>
            </template>
          </el-table-column>
          <el-table-column prop="score_no" label="未完成评分">
            <template slot-scope="scope">
              <span>{{ scope.row.score_no }}人</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="compileIndex(scope.row)" type="text">编辑</el-button>
              <el-button @click="deleteIndex(scope.row)" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 等级配置 -->
    <BrawerBox :drawerTitle="configurationName" :showDrawer.sync="isConfiguration" :closeModal="false">
      <template slot="main">
        <el-form :rules="classRules" :model="classFrom" ref="configuration" label-width="120px">
          <el-form-item label="等级配置名称:" prop="name"><el-input placeholder="请输入等级配置名称" v-model="classFrom.name" style="width: 250px;"></el-input></el-form-item>
          <el-form-item label="参与人员:" prop="employee_ids">
            <div class="border flex-box-ce">
              <div class="flex-1" v-if="users.length == 0">请选择参与人员</div>
              <div v-else style="width: 180px;" class="font-flex-word">
                <span v-for="(item, index) in users" :key="index">
                  <i v-if="index != 0">,</i>
                  {{ item.name }}
                </span>
              </div>
              <span v-if="users.length > 0" class="blue">{{ users.length }}人</span>
              <i class="el-icon-arrow-down icon-right" v-else></i>
              <div @click="openSelectUser" class="inputDc"></div>
            </div>
          </el-form-item>
          <ClassSet ref="ClassSet" :inputs="inputs"></ClassSet>
        </el-form>
      </template>
      <template slot="footer">
        <el-button plain @click="isConfiguration = false">取消</el-button>
        <el-button type="primary" @click="saveConfiguration('configuration')">保存</el-button>
      </template>
    </BrawerBox>
    <!-- 选择子管理员 -->
    <EmployeeSelector
      title="选择人员"
      :selected="selected"
      :is_employee_list="true"
      :employee_list="employee_list"
      :visible.sync="setUser"
      :is_filtration_creator="false"
      @confirm="confirm"
    />
    <!--执行等级配置  -->
    <BrawerBox drawerTitle="执行等级配置" :showDrawer.sync="isExecute">
      <template slot="main">
        <div class="flex-box-ce"><el-input prefix-icon="el-icon-search" placeholder="搜索等级配置" v-model="searchVal"></el-input></div>
        <template v-if="classList.length > 0">
          <div class="flex-box-ce li" style="margin-top: 20px;">
            <el-checkbox class="flex-box-ce flex-box-ce2" v-model="isAllSelectIndex" label="全选" style="padding: 15px 0;"></el-checkbox>
          </div>
          <ul class="ul">
            <li v-for="(item, index) in classList" :key="index" class="flex-box-ce li" v-if="item.name.indexOf(searchVal) >= 0">
              <el-checkbox class="flex-box-ce flex-box-ce2" v-model="item.check" style="padding: 15px 0;">
                <div class="flex-box-ce">
                  <div class="flex-1">
                    <span class="yellow" v-if="item.pl_exec == 0">未执行配置</span>
                    <span v-else class="blue">已执行配置</span>
                    {{ item.name }}
                  </div>
                  <div class="blue" v-if="item.employee_num > 0">{{ item.employee_num }} 人</div>
                </div>
              </el-checkbox>
            </li>
            <div class="fontColorC" style="text-align: center;padding: 10px 0;font-size: 12px;">没有更多了</div>
          </ul>
        </template>
        <NoData v-else></NoData>
      </template>
      <template slot="footer">
        <el-button plain @click="isExecute = false">取消</el-button>
        <el-button type="primary" @click="selectClass()">执行配置</el-button>
      </template>
    </BrawerBox>
  </div>
</template>

<script>
import EmployeeSelector from '@/components/public/EmployeeSelector';
import BrawerBox from '@/components/public/BrawerBox';
import ClassSet from '@/components/public/ClassSet';
import PageHead from '@/components/public/PageHead';
export default {
  components: { EmployeeSelector, BrawerBox, ClassSet, PageHead },
  data() {
    return {
      packageName: '',
      activeIndex: '1',
      packageId: 0,
      dropdownMenu: [{ key: 'a', name: '复用历史配置' }, { key: 'b', name: '批量生产配置' }, { key: 'c', name: '操作记录' }],
      tableData: [],
      // 等级配置
      classFrom: { level_type: 1, name: '', employee_ids: '', id: '' },
      classRules: {
        name: [{ required: true, message: '请输入等级配置名称', trigger: 'blur' }]
      },
      force: '', //是否强制使用
      isConfiguration: false,
      configurationName: '新增等级配置',
      selected: { employee: [], dept: [] },
      users: [],
      setUser: false,
      inputs: [{ name: 'C', min: 0, max: 60 }, { name: 'B', min: 60, max: 80 }, { name: 'A', min: 80, max: 100 }],
      // 执行等级
      isExecute: false,
      classList: [],
      loading: false,
      searchVal: '',
      isAllSelectIndex: false,
      package_employee_num: 0, //参与员工数量
      employee_no_config: 0, //未参与人员数量
      employee_list: [] //
    };
  },
  watch: {
    isExecute(val) {
      if (!val) {
        this.classList = [];
        this.isAllSelectIndex = false;
      }
    },
    users(val) {
      let employee_ids = val.map(item => {
        return item.id;
      });
      this.classFrom.employee_ids = employee_ids;
    },
    isAllSelectIndex(val) {
      this.classList.forEach(item => {
        item.check = val;
      });
    },
    isConfiguration(val) {
      if (!val) {
        this.closeLevel();
        this.getList();
      }
    }
  },
  created() {
    if (this.$route.query.packageId) {
      this.packageId = this.$route.query.packageId;
      this.packageName = this.$route.query.packageName;
      this.employee_list = JSON.parse(this.$route.query.employee_list);
      this.getList();
    }
  },
  methods: {
    openIsExecute() {
      this.classList = JSON.parse(JSON.stringify(this.tableData));
      this.isExecute = true;
    },
    getList() {
      this.loading = true;
      this.$axios('get', '/api/per/package/level_config/list', { package_id: this.packageId })
        .then(res => {
          res.data.data.list.forEach(item => {
            item.check = false;
          });
          this.tableData = res.data.data.list;
          this.package_employee_num = res.data.data.package_employee_num; //参与员工数量
          this.employee_no_config = res.data.data.employee_no_config;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 执行等级
    selectClass() {
      let ids = [];
	  
	  
      this.classList.forEach(item => {
        if (item.check) {
          ids.push(item.id);
        }
      });
	  if(ids.length==0){
		  this.$message.error('请选择等级配置');
		  return false
	  }
      this.$confirm('说明：如果等级配置内有员工未完成评分，这部分员工不会参与等级配置，评完分后可以重新执行等级配置。', '提示', {
        confirmButtonText: '执行等级配置',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.saveSelectClass(ids);
        })
        .catch(() => {});
    },
    saveSelectClass(ids) {
      this.$axios('post', 'api/per/package/exec_level', { ids: JSON.stringify(ids) }).then(res => {
        this.$message.success('执行成功');
        this.isExecute = false;
        this.getList();
      });
    },
    openSelectUser() {
      this.selected.employee = this.users;
      this.setUser = true;
    },
    confirm(val) {
      this.users = val.employee;
    },
    // 开打等级配置
    openConfiguration(index) {
      this.configurationName = index == 1 ? '新增等级配置' : '编辑等级配置';
      this.isConfiguration = true;
    },
    // 新增||编辑等级配置
    saveConfiguration(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let isSave = this.$refs.ClassSet.isSave;
          let inputsList = this.$refs.ClassSet.inputsList;
          let classFrom = this.classFrom;
          let is = true,
            level_scope = [];
          if (!isSave) {
            return false;
          }
          inputsList.some(item => {
            if (!item.name) {
              this.$message.error('等级的名称不能为空');
              is = false;
              return true;
            }
            if (item.max == 0) {
              this.$message.error('分值不能为空或者0');
              is = false;
              return true;
            }
            level_scope.push({ name: item.name, value: Number(item.max) });
          });
          if (!is) {
            return false;
          }
          var level_scopes = {
            //参数的数据结构
            level_type: classFrom.level_type,
            level_scope: {
              levels: level_scope
            },
            level_normal: {
              levels: [
                {
                  name: '优秀',
                  value: 80
                }
              ],
              distribution_type: 1
            }
          };
          let data = {
            package_id: this.packageId,
            name: classFrom.name,
            config: JSON.stringify(level_scopes),
            employee_ids_code: this.$returnCode(classFrom.employee_ids)
          };
          if (classFrom.id) {
            data.id = classFrom.id;
          }
          if (this.force) {
            data.force = this.force;
          }
          this.$axios('post', '/api/per/package/edit_package_level', data).then(res => {
            if (!res.data.data.result) {
              this.$confirm(res.data.data.msg + ',是否改为当前等级配置中进行考核', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
                .then(() => {
                  this.force = 1;
                  this.saveConfiguration('configuration');
                })
                .catch(() => {});
            } else {
              if (this.classFrom.id) {
                this.$message.success('保存成功');
              } else {
                this.$message.success('创建成功');
              }
              this.isConfiguration = false;
            }
          });
        } else {
          return false;
        }
      });
    },
    closeLevel() {
      this.force = '';
      this.classFrom = {
        id: '',
        level_type: 1,
        name: '',
        employee_ids: ''
      };
      this.inputs = [{ name: 'C', min: 0, max: 60 }, { name: 'B', min: 60, max: 80 }, { name: 'A', min: 80, max: 100 }];
      this.users = [];
    },
    // 打开参与人员
    openCy() {
      this.$router.push({ path: '/participation', query: { packageId: this.packageId, employee_list: this.$route.query.employee_list } });
    },
    compileIndex(item) {
      this.classFrom = {
        id: item.id,
        level_type: item.config.level_type,
        name: item.name
      };
      let levels = item.config.level_type == 1 ? item.config.level_scope.levels : item.config.level_normal.levels;
      let inputs = [];
      var max = 0; //最大值
      if (levels) {
        levels.forEach((item, index) => {
          var obj;
          if (index == 0) {
            obj = { name: item.name, max: Number(item.value), min: 0 };
          } else {
            obj = { name: item.name, max: Number(item.value), min: max }; //当不是第一个等级时，最小值为上一个的最大值
          }
          max = item.value;
          inputs.push(obj);
        });
      }
      // this.inputs=inputs
      this.users = item.employee;
      this.isConfiguration = true;
      setTimeout(() => {
        //延迟赋值， 让组件触发监听
        this.inputs = inputs;
      }, 200);
    },
    deleteIndex(item) {
      this.$confirm('请确认删除等级配置，删除不会影响生成的等级。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios('post', 'api/per/package/delete_package_level', { id: item.id }).then(res => {
            this.$message.success('删除成功');
            this.getList();
          });
        })
        .catch(() => {});
    }
  }
};
</script>
<style scoped="scoped" lang="scss">
.flex-box-ce2{
	display: flex !important;
	align-items: center!important;
}	
.box {
  position: relative;
  background-color: #fff;
  padding: 20px;
}
.main {
  margin-top: 20px;
}
.box::-webkit-scrollbar {
  width: 3px;
  height: 10px;
  background-color: #fff;
}
.box::-webkit-scrollbar-thumb {
  background-color: #d9d9d9;
}
.step-item {
  width: 140px;
  color: #777777;
  text-align: center;
  height: 60px;
  cursor: pointer;
}
.step-item span {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  text-align: center;
  line-height: 24px;
  border: 1px solid #ebebeb;
  margin-right: 10px;
}
.active-step {
  background-color: #1583f2;
  color: #fff;
}
.active-step span {
  border: 1px solid #1583f2;
  background-color: #fff;
  color: #1583f2;
}
.primaryBtn {
  color: #409eff;
  border: 1px solid #409eff;
  background-color: #fff;
}
.primaryBtn:hover {
  background-color: #ecf5ff !important;
}
.border {
  -webkit-appearance: none;
  background-color: #fff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #c0c4cf;
  font-size: inherit;
  height: auto;
  outline: 0;
  padding: 0 15px;
  width: 250px;
  position: relative;
  cursor: pointer;
}
.border .font-flex-word {
  color: #606266;
}
.inputDc {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  z-index: 9;
  cursor: pointer;
}
.li {
  border-bottom: 1px solid #f1f1f1;
}
.li:hover {
  background-color: #f5f7fa;
}
</style>
