<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="考核任务名称" prop="pcTitle">
        <el-input
          v-model="queryParams.pcTitle"
          placeholder="请输入考核任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="考核任务状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择考核任务状态" clearable>
          <el-option
            v-for="dict in dict.type.kh_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['kaohe:pingce:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['kaohe:pingce:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['kaohe:pingce:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['kaohe:pingce:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeleteUsers"
          v-hasPermi="['system:user:remove']"
        >清除评分账号</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="rwAddsUser"
        >生成评分账号</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pingceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed/>
<!--      <el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="考核任务名称" align="center" prop="pcTitle" />
      <el-table-column label="考核任务描述" align="center" prop="pcDescription" />
      <el-table-column label="模板名称" align="center" prop="templateName" />
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="110"/>
      <el-table-column label="考核任务状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.kh_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="考核任务备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="350px" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-tools"
            @click="handleSetUp(scope.row, scope.$index)"
          >发布考核
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewVote(scope.row)"
          >查看评分任务
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-grid"
            @click="goKaoHeScore(scope.row)"
            v-hasPermi="['kaohe:kh_result:generate']"
          >生成考核得分
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewKaoHeScore(scope.row)"
            v-hasPermi="['kaohe:kh_result:list']"
          >查看考核得分
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user-solid"
            @click="handleAddsUser(scope.row)"
          >生成评分账号
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewUser(scope.row)"
          >查看评分账号
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考核任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="考核任务名称" prop="pcTitle">
          <el-input v-model="form.pcTitle" placeholder="请输入考核任务名称" :disabled="form.state==='2'"/>
        </el-form-item>
        <el-form-item label="模板名称" prop="templateName">
          <el-input placeholder="请选择模板名称" v-if="form.state==='0'" readonly v-model="form.templateName" @focus="changeTemp">
            <i slot="suffix" class="el-input__icon el-icon-search" style="color: #1890ff; font-weight: bolder"></i>
          </el-input>
          <el-input v-else v-model="form.templateName" placeholder="请选择模板" disabled/>
        </el-form-item>
        <el-form-item label="考核任务描述" prop="pcDescription" :disabled="form.state!=='0'">
          <el-input v-model="form.pcDescription" type="textarea" placeholder="请输入考核任务描述" :disabled="form.state==='2'"/>
        </el-form-item>
<!--        <el-form-item label="考核任务状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择考核任务状态" clearable style="width: 100%" :disabled="form.state!=='0'">
            <el-option
              v-for="dict in dict.type.kh_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>-->
        <el-form-item label="被考核对象类型" prop="bkhdxType">
          <el-radio-group v-model="form.bkhdxType" :disabled="form.state!=='0'">
            <el-radio v-for="dict in dict.type.bkhdx_type" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="被考核对象" v-if="form.bkhdxType==='1'">
          <el-button type="primary" @click="selectEmp" size="mini" v-if="form.state==='0'">选择职工</el-button>
          <el-table :data="form_bkh_zg" style="width: 100%; margin-top: 10px" border max-height="500">
            <el-table-column label="操作" width="100" fixed align="center" v-if="form.state==='0'">
              <template slot-scope="scope">
                <i class="el-icon-remove-outline" style="font-size: 20px;color:#F56C6C;" @click="delEmpList(scope.row,scope.$index)"></i>
              </template>
            </el-table-column>
            <el-table-column label="工号" align="center" prop="wordId"/>
            <el-table-column label="部门名称" align="center" prop="deptName" :show-overflow-tooltip="true" min-width="100"/>
            <el-table-column label="职工姓名" align="center" prop="empName" :show-overflow-tooltip="true" min-width="100"/>
            <el-table-column label="身份" align="center" prop="position" />
          </el-table>
        </el-form-item>
        <el-form-item label="被考核对象" v-if="form.bkhdxType==='0'">
          <el-checkbox v-model="deptExpand" :disabled="form.state!=='0'" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" :disabled="form.state!=='0'" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.deptCheckStrictly" :disabled="form.state!=='0'" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>
          <el-tree
            :disabled="form.state!=='0'"
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            ref="dept"
            node-key="id"
            :check-strictly="!form.deptCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="考核任务备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入考核任务备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择模板信息 -->
    <el-dialog title="模板选择" :visible.sync="temp.open" width="500px">
      <div>
        <el-form :model="temp.queryParams" :inline="true" label-width="68px">
          <el-form-item label="模板名称" prop="userName" style="margin-bottom: 10px">
            <el-input
              v-model="temp.queryParams.temName"
              placeholder="请输入模板名称"
              clearable
              @keyup.enter.native="tempQuery"
            />
          </el-form-item>
          <el-form-item style="margin-bottom: 10px">
            <el-button type="primary" icon="el-icon-search" size="small" @click="tempQuery">搜索</el-button>
          </el-form-item>
        </el-form>

        <el-table border v-loading="temp.loading" :data="temp.list" @row-dblclick="tempRowChange">
          <el-table-column label="主键ID" align="center" prop="id" />
          <el-table-column label="模板名称" align="center" prop="temName" />
        </el-table>

        <pagination
          v-show="temp.total>0"
          :total="temp.total"
          :page.sync="temp.queryParams.pageNum"
          :limit.sync="temp.queryParams.pageSize"
          @pagination="tempQuery"
        />

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

    </el-dialog>

    <!-- 选择职工 -->
    <el-dialog title="选择职工" :visible.sync="emp.open" width="1200px" append-to-body>
      <div style="display:flex;width: 100%;justify-content: space-between">
        <div style="width: 30%; border-right: 1px solid #eeeeee; padding-right: 10px;">
          <div style="height: 45px;line-height: 45px;font-size: 14px;font-weight: bolder">
            选中职工 <span style="color: #39CCCC">{{ emp.selectList.length }}</span>
          </div>
          <el-table :data="emp.selectList" style="width: 100%" border max-height="500">
            <el-table-column label="操作" width="50" fixed align="center">
              <template slot-scope="scope">
                <i class="el-icon-remove-outline" style="font-size: 20px;color:#F56C6C;" @click="selectListDel(scope.row,scope.$index)"></i>
              </template>
            </el-table-column>
<!--            <el-table-column label="主键" align="center" prop="id" />-->
            <el-table-column label="工号" align="center" prop="wordId"/>
            <el-table-column label="部门名称" align="center" prop="deptName" :show-overflow-tooltip="true" min-width="100"/>
            <el-table-column label="职工姓名" align="center" prop="empName" :show-overflow-tooltip="true" min-width="100"/>
            <el-table-column label="身份" align="center" prop="position" />
          </el-table>
        </div>
        <div style="width: 69%;">
          <el-row :gutter="20">
            <!--部门数据-->
            <el-col :span="6" :xs="24">
              <div class="head-container">
                <el-input
                  v-model="deptName"
                  placeholder="请输入部门名称"
                  clearable
                  size="small"
                  prefix-icon="el-icon-search"
                  style="margin-bottom: 20px"
                />
              </div>
              <div class="head-container">
                <el-tree
                  :data="deptOptions"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  :filter-node-method="empfilterNode"
                  ref="tree"
                  node-key="id"
                  default-expand-all
                  highlight-current
                  @node-click="empNodeClick"
                />
              </div>
            </el-col>
            <el-col :span="18" :xs="24">
              <el-form :model="emp.queryParams" :inline="true" label-width="70px">
                <el-form-item label="职工名称" prop="empName" style="margin-bottom: 10px">
                  <el-input
                    v-model="emp.queryParams.empName"
                    placeholder="请输入职工名称"
                    clearable
                    @keyup.enter.native="empQuery"
                  />
                </el-form-item>
                <el-form-item style="margin-bottom: 10px">
                  <el-button type="primary" icon="el-icon-search" size="small" @click="empQuery">搜索</el-button>
                </el-form-item>
              </el-form>
              <el-table border ref="empTable" v-loading="emp.loading" :data="emp.list" @select="empSelect" @select-all="empSelectAll">
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column label="工号" align="center" prop="wordId"/>
                <el-table-column label="部门名称" align="center" prop="deptName" :show-overflow-tooltip="true" min-width="100"/>
                <el-table-column label="职工姓名" align="center" prop="empName" :show-overflow-tooltip="true" min-width="100"/>
                <el-table-column label="身份" align="center" prop="position" />
              </el-table>

              <pagination
                v-show="emp.total>0"
                :total="emp.total"
                :page.sync="emp.queryParams.pageNum"
                :limit.sync="emp.queryParams.pageSize"
                @pagination="empQuery"
              />

            </el-col>

          </el-row>

        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="empConfirm">确 认</el-button>
      </div>
    </el-dialog>

    <!--选择发布考核信息-->
    <el-dialog title="发布考核" :visible.sync="pcSetUp.open" width="99%">
      <div style="font-size: 16px;margin-bottom: 15px;font-weight: 600">考核任务名称：{{ pcSetUp.pingceName }}</div>
      <el-alert title="评分占比请输入小于 1 的小数，评分占比合计需为 1 " style="font-weight: bold" type="info" :closable="false"></el-alert>
      <el-table border v-loading="pcSetUp.loading" :data="pcSetUpList" style="margin-top: 10px;">
        <el-table-column label="考核项主键" align="center" prop="id" width="90" fixed/>
        <el-table-column label="考核项名称" align="center" prop="itemName" min-width="120" :show-overflow-tooltip="true" fixed/>
        <el-table-column label="考核项类型" align="center" prop="type" min-width="100" fixed/>
        <el-table-column label="评分主题" align="center" prop="vote" min-width="220" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.$index=== pcSetUp.xzhIndex">
              <el-input v-model.trim="scope.row.vote.voteTitle" placeholder="请输入评分主题"
                        :disabled="scope.row.vote.id && !(new Date(scope.row.vote.sTime) > (new Date()))"/>
            </div>
            <div v-else>
              <span>{{ scope.row.vote.voteTitle }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="最大值" align="center" prop="vote" min-width="140" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.$index=== pcSetUp.xzhIndex && scope.row.typeId!==1">
              <el-input-number :disabled="scope.row.vote.id && !(new Date(scope.row.vote.sTime) > (new Date()))" controls-position="right"
                v-model="scope.row.vote.maxNum" :min="0" style="width: 120px;"></el-input-number>
            </div>
            <div v-else>
              <span>{{ scope.row.vote.maxNum }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="评优最大值" align="center" prop="vote" min-width="140" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.$index=== pcSetUp.xzhIndex && scope.row.typeId===1">
              <el-input-number :disabled="scope.row.vote.id && !(new Date(scope.row.vote.sTime) > (new Date()))" controls-position="right"
                               v-model="scope.row.vote.umax" :min="0" style="width: 120px;"></el-input-number>
            </div>
            <div v-else>
              <span>{{ scope.row.vote.umax }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="评分占比" align="center" prop="vote"  min-width="300" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.$index=== pcSetUp.xzhIndex && scope.row.typeId!==3">
              <div>
                <el-input-number :disabled="scope.row.vote.id && !(new Date(scope.row.vote.sTime) > (new Date()))" style="width: 120px;margin-right: 10px;"
                                 v-model="scope.row.vote.percentage" :precision="2" :step="0.01" :max="1" controls-position="right"></el-input-number>
                <el-switch :disabled="scope.row.vote.id && !(new Date(scope.row.vote.sTime) > (new Date()))"
                  v-model="scope.row.vote.samePercent" active-text="不一致" inactive-text="一致" active-value="1" inactive-value="0"
                  v-hasPermi="['kaohe:vote_emp:list']" @change="samePercentChange(scope.row)">
                </el-switch>
              </div>
              <div v-if="scope.row.vote.samePercent=='1'&&scope.row.vote.voteEmps" style="padding: 5px;">
                <div v-for="item in scope.row.vote.voteEmps" :key="item.bkhdxId"
                     style="margin-bottom: 5px; display: flex; justify-content: space-between;align-items: center">
                  <span>{{ item.bkhdxName }}</span>
                  <el-input-number v-model="item.percentage" :precision="2" :step="0.01" :max="1" :controls="false" style="width: 120px;"
                                   :disabled="scope.row.vote.id && !(new Date(scope.row.vote.sTime) > (new Date()))"></el-input-number>
                </div>
              </div>

            </div>
            <div v-else>
              <span>{{ scope.row.vote.percentage }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="vote"  min-width="200" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.$index=== pcSetUp.xzhIndex">
              <el-date-picker clearable style="width: 100%;" v-model="scope.row.vote.sTime"
                              :disabled="scope.row.vote.id && !(new Date(scope.row.vote.sTime) > (new Date()))"
                              type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择开始时间">
              </el-date-picker>
            </div>
            <div v-else>
              <span>{{ scope.row.vote.sTime }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="vote"  min-width="200" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.$index=== pcSetUp.xzhIndex">
              <el-date-picker clearable style="width: 100%;" v-model="scope.row.vote.eTime"
                              type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择结束时间">
              </el-date-picker>
            </div>
            <div v-else>
              <span>{{ scope.row.vote.eTime }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="评分详情描述" align="center" prop="vote" min-width="200" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.$index=== pcSetUp.xzhIndex">
              <el-input :disabled="scope.row.vote.id && !(new Date(scope.row.vote.eTime) > (new Date()))"
                        v-model="scope.row.vote.vDescription" type="textarea" placeholder="请输入评分详情描述"/>
            </div>
            <div v-else>
              <span>{{ scope.row.vote.vDescription }}</span>
            </div>

          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="vote" min-width="200" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.$index=== pcSetUp.xzhIndex">
              <el-input :disabled="scope.row.vote.id && !(new Date(scope.row.vote.eTime) > (new Date()))"
                        v-model="scope.row.vote.remark" type="textarea" placeholder="请输入备注"/>
            </div>
            <div v-else>
              <span>{{ scope.row.vote.remark }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="vote"  min-width="100" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.pf_state" :value="scope.row.vote.state"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180">
          <template slot-scope="scope">
            <div>
              <el-button v-if="!(scope.$index=== pcSetUp.xzhIndex) && !scope.row.vote.id"
                size="mini"
                type="text"
                icon="el-icon-s-tools" v-hasPermi="['kaohe:vote:add']"
                @click="setUpTouPiao(scope.row,scope.$index)"
              >发布评分规则</el-button>

              <el-button v-if="!(scope.$index=== pcSetUp.xzhIndex) && scope.row.vote.id"
                         size="mini"
                         type="text"
                         icon="el-icon-s-tools" v-hasPermi="['kaohe:vote:edit']"
                         @click="setUpTouPiao(scope.row,scope.$index)"
              >编辑评分规则</el-button>

              <el-button v-if="scope.$index=== pcSetUp.xzhIndex"
                size="mini" v-hasPermi="['kaohe:vote:add', 'kaohe:vote:edit']"
                type="text"
                @click="voteSubmitForm(scope.row)"
              >确认</el-button>

              <el-button v-if="scope.$index=== pcSetUp.xzhIndex"
                         size="mini"
                         type="text"
                         @click="cancelVote"
              >取消</el-button>

              <el-button
                v-if="scope.row.vote.id && (new Date(scope.row.vote.sTime) < (new Date())) && (new Date(scope.row.vote.eTime) > (new Date()))"
                size="mini"
                type="text"
                icon="el-icon-thumb"
                @click="goVotepage(scope.row)"
                v-hasPermi="['kaohe:vote_emp:edit']"
              >去评分</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="pcSetUp.open=false">取 消</el-button>
      </div>
    </el-dialog>

    <!--查看考核得分-->
    <el-dialog title="查看考核得分" :visible.sync="khdf.open" width="90%" top="20px !important">
      <div style="margin-bottom: 10px;">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="khdfExport"
          v-hasPermi="['kaohe:kh_result:export']"
        >导出</el-button>
      </div>
      <el-table border :data="khdf.list" height="650px">
        <template v-for="column in khdf.tableHeader">
          <table-column :key="column.label" :column="column" />
        </template>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="khdf.open=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 生成评分账号对话框 -->
    <el-dialog title="生成评分账号" :visible.sync="scpfzh.open" width="600px" append-to-body>
      <el-form ref="scpfzhForm" :model="scpfzh.form" :rules="scpfzh.rules" label-width="110px">
        <el-form-item label="所属部门" prop="deptId">
          <treeselect v-model="scpfzh.form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择所属部门" />
        </el-form-item>
        <el-form-item label="评分考核项" prop="items">
          <el-select v-model="scpfzh.form.items" multiple value-key="id"
                     placeholder="请选择评分考核项" clearable style="width: 100%">
            <el-option
              v-for="dict in scpfzh.itemsOtions"
              :key="dict.id"
              :label="dict.itemName"
              :value="dict"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生成账号数量" prop="num">
          <el-input-number v-model="scpfzh.form.num" :min="1" label="请输入生成账号数量"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="scpfzhSubmit">确 定</el-button>
        <el-button @click="scpfzhCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listPingce, getPingce, delPingce, addPingce, updatePingce, getItemVote, addsUser, generateResult } from "@/api/kaohe/pingce"
import { listKh_result } from "@/api/kaohe/kh_result"
import { deptTreeSelect } from "@/api/system/user";
import { listTemplate } from "@/api/kaohe/template"
import { listEmployee } from "@/api/kaohe/employee"
import { addVote, updateVote } from "@/api/kaohe/vote"
import { listVote_items } from "@/api/kaohe/vote_items"
import { listVote_emp } from "@/api/kaohe/vote_emp"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import TableColumn from '@/components/TableColumn'
import {delUserPingfen} from "../../../api/system/user";

export default {
  name: "Pingce",
  dicts: ['kh_state', 'sys_user_sex', 'bkhdx_type', 'pf_state'],
  components: { Treeselect, TableColumn },
  data() {
    return {
      // 考核得分
      khdf:{
        open: false,
        id: null,
        pcName: null,
        list: [],
        tableHeader: []
      },
      deptExpand: true,
      deptNodeAll: false,
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考核任务表格数据
      pingceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pcTitle: null,
        pcDescription: null,
        templateId: null,
        templateName: null,
        pcResultId: null,
        state: null,
      },
      // 表单参数
      form: {},
      //被考核职工
      form_bkh_zg: [],
      // 表单校验
      rules: {
        pcTitle: [
          { required: true, message: "考核名称不能为空", trigger: "change" }
        ],
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "change" }
        ],
      },
      /** 选择模板*/
      temp: {
        type: 1,
        // 是否显示弹出层
        open: false,
        // 列表遮罩层
        loading: false,
        // 列表查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10
        },
        // 表格数据
        list: [],
        // 总条数
        total: 0,
      },
      // 部门名称
      deptName: undefined,
      /** 选择职工*/
      emp: {
        // 是否显示弹出层
        open: false,
        // 列表遮罩层
        loading: false,
        // 列表查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          empName: undefined,
          deptId: undefined,
        },
        // 表格数据
        list: [],
        // 选中表格数据
        selectList: [],
        // 总条数
        total: 0,
      },
      // 考核发布
      pcSetUp: {
        row: null,
        // 选中行Index
        xzhIndex: null,
        isRowEdit: false,
        open: false,
        pingceId:undefined,
        pingceName:undefined,
        templateId:undefined
      },
      pcSetUpList:[],
      // 评分规则初始数据
      voteInitData:{
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        id: null,
        pingceId: null,
        pingceName: null,
        khitemId: null,
        khitemName: null,
        khitemTypeid: null,
        voteItems: null,
        voteTitle: '',
        vDescription: null,
        sTime: null,
        eTime: null,
        maxNum: null,
        umax: null,
        percentage: null,
        state: null,
        itemIds: null,
        samePercent: '0',
      },
      // 评分选项类型数据
      vote_options: [],
      // 生成评分账号
      scpfzh:{
        open: false,
        form:{},
        rules: {
          deptId: [
            { required: true, message: "所属部门不能为空", trigger: "change" }
          ],
          items: [
            { required: true, message: "评分考核项不能为空", trigger: "change" }
          ],
          num: [
            { required: true, message: "生成账号数量不能为空", trigger: "change" }
          ],
        },
        itemsOtions: [],
      },
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getVoteItemsList();
  },
  methods: {
    samePercentChange(row){
      let voteEmps = [];
      if(row.vote.samePercent==='1'){
        this.pcSetUp.row.pcBkhdxs.forEach(item => {
          voteEmps.push({
            bkhdxId: item.bkhdxId,
            bkhdxName: item.bkhdxName,
            percentage: row.vote.percentage,
          })
        })
      }
      row.vote['voteEmps'] = voteEmps;
    },
    /** 查询考核任务列表 */
    getList() {
      this.loading = true
      listPingce(this.queryParams).then(response => {
        this.pingceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.deptExpand = true;
      this.deptNodeAll = false;
      this.form_bkh_zg = [];
      this.form = {
        deptCheckStrictly: false,
        id: null,
        pcTitle: null,
        pcDescription: null,
        templateId: null,
        templateName: null,
        pcBkhdxs:[],
        pcResultId: null,
        state: '0',
        bkhdxType: '0',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.$nextTick(() => {
        this.$refs.dept.setCheckedKeys([])
      })
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加考核任务"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPingce(id).then(response => {

        if(response.data.state==='0'){
          this.form = response.data;
          if(this.form.bkhdxType==='1'){
            this.form.pcBkhdxs.forEach(item=>{
              this.form_bkh_zg.push({
                id: item.bkhdxId,
                empName: item.bkhdxName,
                deptId: item.deptId,
                deptName: item.deptName,
                position: item.position,
                wordId: item.wordId,
              })
            })
          }

          if(this.form.bkhdxType==='0'){
            let Keys = [];
            this.form.pcBkhdxs.forEach(item=>{
              Keys.push(item.bkhdxId);
            })
            this.$nextTick(() => {
              this.$refs.dept.setCheckedKeys(Keys)
            })
          }
          this.form.pcBkhdxs = [];
          this.open = true;
          this.title = "修改考核任务";
        }else {
          this.$alert(`当前状态不可修改，只有未开始状态下可执行修改操作！`, `提示`, {
            type: 'Danger'
          })
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let flag = true;
          // 被考核对象 - 职工
          if(this.form.bkhdxType==='1'){
            if( this.form_bkh_zg && this.form_bkh_zg.length <1 ){
              flag = false;
              this.$alert(`还没有选择被考核对象，请选择被考核对象！`, `提示`, {
                type: 'warning'
              })
            }else {
              this.form_bkh_zg.forEach(item=>{
                this.form.pcBkhdxs.push({
                  bkhdxId: item.id,
                  bkhdxName: item.empName,
                  deptId: item.deptId,
                  deptName: item.deptName,
                  position: item.position,
                  wordId: item.wordId,
                })
              })
            }
          }
          // 被考核对象 - 部门
          if(this.form.bkhdxType==='0'){
            // 被选中的节点所组成的数组
            let xzNodes = this.$refs.dept.getCheckedNodes();
            if(xzNodes && xzNodes.length<1){
              flag = false;
              this.$alert(`还没有选择被考核对象，请选择被考核对象！`, `提示`, {
                type: 'warning'
              })
            }else {
              xzNodes.forEach(item=>{
                this.form.pcBkhdxs.push({
                  bkhdxId: item.id,
                  bkhdxName: item.label,
                  deptId: item.id,
                  deptName: item.label,
                })
              })
            }
          }
          if(flag){
            if (this.form.id != null) {
              updatePingce(this.form).then(response => {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getList()
              })
            } else {
              this.form.state = '0'
              addPingce(this.form).then(response => {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              })
            }
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除该数据项？').then(function() {
        return delPingce(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('kaohe/pingce/export', {
        ...this.queryParams
      }, `pingce_${new Date().getTime()}.xlsx`)
    },
    /** 选择模板信息*/
    changeTemp(val) {
      this.temp.type = val;
      this.temp.open = true;
      this.temp.queryParams.pageNum = 1;
      this.tempQuery();
    },
    /** 模板信息列表查询 */
    tempQuery() {
      this.temp.loading = true;
      listTemplate(this.temp.queryParams).then(response => {
        this.temp.list = response.rows;
        this.temp.total = response.total;
        this.temp.loading = false;
      });
    },
    /** 模板信息选择弹出框关闭*/
    tempCancel() {
      this.temp.open = false
    },
    // 模板选择 选中数据
    tempRowChange(val) {
      this.form.templateId = val.id;
      this.form.templateName = val.temName;
      this.temp.open = false;
    },
    // 选择职工
    selectEmp(){
      this.emp.open = true;
      this.emp.selectList = [...this.form_bkh_zg]
      this.emp.queryParams.pageNum = 1;
      this.empQuery();
    },
    /** 职工列表查询 */
    empQuery() {
      this.emp.loading = true;
      listEmployee(this.emp.queryParams).then(response => {
        this.emp.list = response.rows;
        this.emp.total = response.total;
        this.emp.loading = false;
        this.$nextTick(()=> {
          this.emp.selectList.forEach(item =>{
            this.emp.list.forEach(row => {
              if(row.id == item.id){
                this.$refs.empTable.toggleRowSelection(row,true);
              }
            });
          })
        })
      });
    },
    /** 职工选择弹出框 确认*/
    empConfirm() {
      this.form_bkh_zg = this.emp.selectList;
      this.emp.open = false
    },
    // 当用户手动勾选数据行的 Checkbox 时触发的事件	    参数 selection, row
    empSelect(val,row) {
      let spliceIndex = undefined;
      this.emp.selectList.forEach((item,index)=>{
        if(item.id === row.id){
          spliceIndex = index
        }
      })
      if(spliceIndex===undefined){
        this.emp.selectList.push(row)
      }else {
        this.emp.selectList.splice(spliceIndex,1)
      }
    },
    // 当用户手动勾选全选 Checkbox 时触发的事件	      参数 selection
    empSelectAll(val){
      this.$nextTick(()=> {
        if(val.length > 0){
          val.forEach(item=>{
            if(this.emp.selectList.filter(item1=>{ return item1.id===item.id}).length<1){
              this.emp.selectList.push(item)
            }
          })
        }else {
          this.emp.list.forEach(item=>{
            this.emp.selectList.forEach((item1,index)=>{
              if(item1.id===item.id){
                this.emp.selectList.splice(index,1)
              }
            })
          })
        }
      })
    },
    // 职工 移除选中
    selectListDel(row,index){
      this.emp.selectList.splice(index,1)
      this.emp.list.forEach(item=>{
        if(row.id===item.id){
          this.$refs.empTable.toggleRowSelection(item,false);
        }
      })
    },
    delEmpList(row,index){
      this.form_bkh_zg.splice(index,1)
    },
    // 发布考核
    handleSetUp(row){
      this.pcSetUp.row = row;
      this.pcSetUp.pingceId = row.id;
      this.pcSetUp.pingceName = row.pcTitle;
      this.pcSetUp.templateId = row.templateId;
      this.pcSetUp.xzhIndex = null;
      this.pcSetUp.open = true;
      this.getItemVote();
    },
    // 获取评测规则数据
    getItemVote(){
      getItemVote({
        id: this.pcSetUp.templateId,
        pingceId: this.pcSetUp.pingceId,
      }).then(response => {
        let pcSetUpList = [];
        response.data.items.forEach(item=>{
          if (item.vote===null){
            item.vote={...this.voteInitData}
            item.vote.khitemId = item.id;
            item.vote.khitemName = item.itemName;
            item.vote.khitemTypeid = item.typeId;
            item.vote.pingceId = this.pcSetUp.pingceId;
            item.vote.pingceName = this.pcSetUp.pingceName;
            item.vote.voteTitle = item.itemName;
            if(item.typeId===2){
              item.vote.maxNum = 100;
            }
            if(item.typeId===3){
              item.vote.maxNum = 10;
            }
          }
          pcSetUpList.push(item);
        })
        this.pcSetUpList = pcSetUpList;
      })
    },
    // 评测规则设置
    setUpTouPiao(row,index){
      this.pcSetUp.xzhIndex = index;
      if(row.vote.samePercent&&row.vote.samePercent==='1'){
        listVote_emp({
          pageNum: 1,
          pageSize: 1000000000,
          voteId: row.vote.id,
        }).then(response1 => {
          console.log(response1.rows);
          let voteEmps = [];
          response1.rows.forEach(item => {
            voteEmps.push({
              bkhdxId: item.bkhdxId,
              bkhdxName: item.bkhdxName,
              percentage: item.percentage,
            })
          })
          getItemVote({
            id: this.pcSetUp.templateId,
            pingceId: this.pcSetUp.pingceId,
          }).then(response2 => {
            let pcSetUpList = [];
            response2.data.items.forEach((item,index) => {
              if (item.vote===null){
                item.vote={...this.voteInitData}
                item.vote.khitemId = item.id;
                item.vote.khitemName = item.itemName;
                item.vote.khitemTypeid = item.typeId;
                item.vote.pingceId = this.pcSetUp.pingceId;
                item.vote.pingceName = this.pcSetUp.pingceName;
                item.vote.voteTitle = item.itemName;
                if(item.typeId===2){
                  item.vote.maxNum = 100;
                }
                if(item.typeId===3){
                  item.vote.maxNum = 10;
                }
              }
              if(index=== this.pcSetUp.xzhIndex ){
                item.vote['voteEmps'] = voteEmps;
              }
              pcSetUpList.push(item);
            })
            this.pcSetUpList = pcSetUpList;
          })
        })
      }else {
        this.getItemVote()
      }
    },
    voteSubmitForm(row){
      let flag = true;
      let Vote = {...row.vote}
      if(!Vote.voteTitle){
        flag = false;
        this.$alert(`评分主题不能为空！`, `提示`, {
          type: 'Danger'
        })
      }
      if(!Vote.sTime){
        flag = false;
        this.$alert(`开始时间不能为空！`, `提示`, {
          type: 'Danger'
        })
      }
      if(!Vote.eTime){
        flag = false;
        this.$alert(`结束时间不能为空！`, `提示`, {
          type: 'Danger'
        })
      }
      if(!Vote.id && !(new Date(Vote.sTime) > (new Date()))){
        flag = false;
        this.$alert(`开始时间需大于当前时间！`, `提示`, {
          type: 'Danger'
        })
      }
      if(!(new Date(Vote.eTime) > (new Date()))){
        flag = false;
        this.$alert(`结束时间需大于当前时间！`, `提示`, {
          type: 'Danger'
        })
      }
      if(!(new Date(Vote.eTime) > (new Date(Vote.sTime)))){
        flag = false;
        this.$alert(`结束时间需大于开始时间！`, `提示`, {
          type: 'Danger'
        })
      }
      if(row.typeId!==1 && (!Vote.maxNum)){
        flag = false;
        this.$alert(`最大值不能为空！`, `提示`, {
          type: 'Danger'
        })
      }
      if(row.typeId===1 && (!Vote.umax)){
        flag = false;
        this.$alert(`评优最大值不能为空！`, `提示`, {
          type: 'Danger'
        })
      }
      if(row.typeId===1 && (Vote.umax>this.pcSetUp.row.pcBkhdxs.length)){
        flag = false;
        this.$alert(`评优最大值不能大于被考核对象个数！`, `提示`, {
          type: 'Danger'
        })
      }
      if(row.typeId!==3 && (!Vote.percentage)){
        flag = false;
        this.$alert(`评分占比不能为空！`, `提示`, {
          type: 'Danger'
        })
      }
      if(row.typeId!==3 && Vote.percentage){
        let allFlag = true;
        let sumPercentage = 0;
        this.pcSetUpList.forEach(item=>{
          if(item.typeId!==3){
            if(!item.vote || !item.vote.percentage){
              allFlag=false;
            }
            if(item.vote && item.vote.percentage){
              sumPercentage += item.vote.percentage
            }
          }
        })
        if(allFlag && sumPercentage!==1){
          flag = false;
          this.$alert(`评分占比合计需要为1！`, `提示`, {
            type: 'Danger'
          })
        }
        if(!allFlag && sumPercentage>1){
          flag = false;
          this.$alert(`评分占比合计不能超过1！`, `提示`, {
            type: 'Danger'
          })
        }
      }
      if(!Vote.voteTitle){
        flag = false;
        this.$alert(`评分主题不能为空！`, `提示`, {
          type: 'Danger'
        })
      }
      if(row.typeId===1){
        Vote.voteItems = '1,2,3,4'
      }
      if (Vote.id != null && flag ) {

        if(Vote.state==='2'){
          Vote.state='1';
        }
        updateVote(Vote).then(response => {
          this.$modal.msgSuccess("修改成功")
          this.cancelVote()
        })
        if(this.pcSetUp.row.state==='2'){
          // 修改考核任务状态  进行中
          this.pcSetUp.row.state='1'
          updatePingce(this.pcSetUp.row).then(response => {
            this.getList()
          })
        }
      } else if(Vote.id === null && flag){
        Vote.state = '0';
        addVote(Vote).then(response => {
          this.$modal.msgSuccess("新增成功")
          this.cancelVote();
        });
        if(this.pcSetUp.row.state==='0'){
          // 修改考核任务状态  进行中
          this.pcSetUp.row.state='1'
          updatePingce(this.pcSetUp.row).then(response => {
            this.getList()
          })
        }
      }
    },
    cancelVote(){
      this.pcSetUp.xzhIndex = null;
      this.getItemVote();
    },
    goVotepage(row){
      this.$router.push({ path: '/votepage', query: { id: row.vote.id }});
    },
    getVoteItemsList() {
      listVote_items({
        pageSize: 1000000,
        pageNum: 1
      }).then(response => {
        this.vote_options = response.rows;
        this.vote_options.forEach(e1 => {
          e1.id = String(e1.id)
        })
      })
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'dept') {
        let treeList = this.deptOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions: [])
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true: false
      }
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    empfilterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    empNodeClick(data) {
      this.emp.queryParams.deptId = data.id;
      this.empQuery();
    },
    // 生成考核得分
    goKaoHeScore(row){
      generateResult({
        id: row.id,
        pcTitle: row.pcTitle,
        bkhdxType: row.bkhdxType,
        templateName: row.templateName,
      }).then(response => {
        this.$modal.msgSuccess("生成成功")
      })
    },
    // 查看考核得分
    viewKaoHeScore(row){
      this.khdf.list = [];
      this.khdf.tableHeader = [];
      this.khdf.open = true;
      this.getListKhResult(row.id);
    },
    // 获取考核得分列表
    getListKhResult(pcId){
      listKh_result({
        pageNum: 1,
        pageSize: 10,
        pcId: pcId,
      }).then(response => {
        this.khdf.id = response.rows[0].id;
        this.khdf.pcName = response.rows[0].pcName;
        this.khdf.list = JSON.parse(response.rows[0].tableData);
        let btTabelTree = JSON.parse(response.rows[0].tableHeader);
        btTabelTree.forEach(item => {
          item.prop = item.name;
          if(item.children && item.children.length>0){
            this.setProp(item.children, item.prop)
          }
        })
        this.khdf.tableHeader = btTabelTree;
      })
    },
    // 递归函数 设置prop参数
    setProp(list, prop){
      list.forEach(item=>{
        if(prop){
          item.prop = prop+'.'+item.name;
        }else {
          item.prop = item.name;
        }
        if(item.children && item.children.length>0){
          this.setProp(item.children, item.prop)
        }
      })
    },
    // 生成评分账号
    handleAddsUser(row){
      this.scpfzh.form = {
        deptId: null,
        pcId: row.id,
        items: null,
        itemIds: null,
        num: null,
      }
      this.scpfzh.itemsOtions = []
      getItemVote({
        id: row.templateId,
        pingceId: row.id,
      }).then(response => {
        let flag = true;
        response.data.items.forEach( item =>{
          if(!item.vote){
            flag = false
          }
        })
        if(flag){
          this.scpfzh.itemsOtions = response.data.items
          this.scpfzh.open = true;
        }else {
          this.$alert(`还有未发布评分规则考核项，请发布评分规则都完成后再生成评分账号`, `提示`, {
            type: 'Danger'
          })
        }
      })
    },
    // 查看评分账号
    viewUser(row){
      this.$router.push({ path: '/system/user', query: { pcId: row.id}});
    },
    rwAddsUser(){
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认清除该评分账号数据项？').then(function() {
        return delUserPingfen(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    // 查看评分任务
    viewVote(row){
      this.$router.push({ path: '/toupiao/vote', query: { pcId: row.id}});
    },
    // 提交生成评分账号
    scpfzhSubmit(){
      this.$refs["scpfzhForm"].validate(valid => {
        if (valid) {
          this.scpfzh.form.itemIds = this.scpfzh.form.items.map(item => item.id).join(",");
          this.scpfzh.form.itemNames = this.scpfzh.form.items.map(item => item.itemName).join(",");
          console.log(this.scpfzh.form);
          addsUser(this.scpfzh.form).then(response => {
            this.scpfzh.open = false;
            this.$modal.msgSuccess("生成成功")
          })
        }
      })
    },
    // 取消生成评分账号
    scpfzhCancel(){
      this.scpfzh.open = false;
    },
    /** 清除评分账号 */
    handleDeleteUsers(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认清除该评分账号数据项？').then(function() {
        return delUserPingfen(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    // 考核得分导出
    khdfExport(){
      this.download('kaohe/kh_result/exportById?id='+this.khdf.id, {}, `${ this.khdf.pcName+''+new Date().getTime()}.xlsx`)
    }
  }
}
</script>
