<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item :label="$t('年份')" prop="years">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.years"
                        type="year"
                        value-format="yyyy"
                        :placeholder="$t('请选择') + $t('年份')"
                        @change="handleQuery" >
        </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('培训课程')" prop="course">
        <el-input
          v-model="queryParams.course"
          :placeholder="$t('请输入') + $t('培训课程')"
          clearable
          size="small"
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('培训类型')" prop="trainingType" label-width="50">
        <el-select v-model="queryParams.trainingType" @change="handleQuery"    :placeholder="$t('请选择') + $t('培训类型')" clearable size="small">
          <el-option
            v-for="dict in trainingTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('是否完成')" prop="isfinish" label-width="50">
        <el-select v-model="queryParams.isfinish" @change="handleQuery"    :placeholder="$t('请选择') + $t('是否完成')" clearable size="small">
          <el-option
            v-for="dict in isfinishOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('未参培情况')" prop="isNon" label-width="50">
        <el-select v-model="queryParams.isNon" @change="handleQuery"    :placeholder="$t('请选择') + $t('是否未参培')" clearable size="small">
          <el-option
            key="0"
            label="全部"
            value="0"
          />
          <el-option
            key="1"
            label="未参培"
            value="1"
          />
          <el-option
            key="2"
            label="已完成"
            value="2"
          />
          <el-option
            key="3"
            label="未完成"
            value="3"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('培训开始日期')" label-width="60">
        <el-date-picker
          v-model="chooseDate"
          @change="handleQuery"
          type="daterange"
          align="right"
          unlink-panels
          :range-separator="$t('至')"
          :start-placeholder="$t('开始日期')"
          :end-placeholder="$t('结束日期')"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('搜索') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['training:training:add']"
        >{{ $t('新增') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['training:training:edit']"
        >{{ $t('修改') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['training:training:remove']"
        >{{ $t('删除') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['training:training:export']"
        >{{ $t('导出') }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-button type="primary" plain @click="selectCourse('10')">定期类</el-button>
        <el-button type="primary" plain @click="selectCourse('12')">
          EHS类培训、学习及信息通告
        </el-button>
        <el-button type="primary" plain @click="selectCourse('14')">
          程序和操作手册培训更新培训
        </el-button>
        <el-button type="primary" plain @click="selectCourse('16')">事件报告和调查</el-button>
        <el-button type="primary" plain @click="selectCourse('20')">MOC培训</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="trainingList" @selection-change="handleSelectionChange" :cell-style="tableCellStyle" :height="clientHeight" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('年份')" align="center" prop="years" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('培训课程')" align="center" prop="course" width="250" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('培训类型')" align="center" prop="trainingType" width="120" :formatter="trainingTypeFormat"/>
      <el-table-column :label="$t('培训内容')" align="center" prop="content" width="250" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('课程代码')" align="center" prop="courseid" width="150" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('是否完成')" align="center" prop="isfinish" width="120">
        <template slot-scope="scope">
            <el-progress :percentage="scope.row.trainingPercent"></el-progress>
          <span > ({{ scope.row.haveTraining }}/{{ scope.row.mustTraining }})</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('培训周期')" align="center" prop="period" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('课时')" align="center" prop="duration" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('培训人')" align="center" prop="trainer" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('培训岗位')" align="center" prop="position" width="250" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('培训开始日期')" align="center" prop="courseStartdate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.courseStartdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('培训结束日期')" align="center" prop="courseEnddate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.courseEnddate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column :label="$t('未参培人员名单')" align="center" prop="nonParticipants" width="200" :show-overflow-tooltip="true" />-->
      <el-table-column :label="$t('备注')" align="center" prop="remarks" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('操作')" align="center" fixed="right" width="270" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['training:training:edit']"
          >{{ $t('修改') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleStaffmgr(scope.row)"
            v-hasPermi="['training:training:edit']"
          >人员名单</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"
            v-hasPermi="['training:training:edit']"
          >培训详情</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  :close-on-click-modal="false" v-dialogDrag :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('培训课程')" prop="course">
              <el-input v-model="form.course" :placeholder="$t('请输入') + $t('培训课程')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('培训类型')" prop="trainingType">
              <el-select v-model="form.trainingType" :placeholder="$t('请选择') + $t('培训类型')">
                <el-option
                  v-for="dict in trainingTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('培训内容')" prop="content">
              <el-input v-model="form.content" :placeholder="$t('请输入') + $t('培训内容')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('课程代码')" prop="courseid">
              <el-input v-model="form.courseid" :placeholder="$t('请输入') + $t('课程代码')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('培训周期')" prop="period">
              <el-input v-model="form.period" :placeholder="$t('请输入') + $t('培训周期')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('课时')" prop="duration">
              <el-input v-model="form.duration" :placeholder="$t('请输入') + $t('课时')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('培训人')" prop="trainer">
              <el-select v-model="form.trainer" filterable multiple :placeholder="$t('请选择') + $t('培训人')">
                <el-option
                  v-for="dict in stffmgrOptions"
                  :key="dict.staffid"
                  :label="dict.name"
                  :value="dict.staffid">
                  <span style="float: left">{{ dict.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.staffid }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('培训岗位')" prop="position">
              <el-select v-model="form.position" multiple :placeholder="$t('请选择') + $t('培训岗位')" @change="changePosition"  style="width: 400px">
                <el-option
                  v-for="dict in positionOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('是否存在') +$t('指定人员')" prop="haveDesignated" >
              <el-checkbox v-model="haveDesignated" @change="changeHave"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('年份')" prop="years">
              <el-date-picker clearable size="small" style="width: 200px"
                              v-model="form.years"
                              type="years"
                              value-format="yyyy"
                              @change="handleStaff"
                              :placeholder="$t('请选择') + $t('年份')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('指定人员') + $t('岗位')" prop="designatedPosition" v-if="haveDesignated === true">
              <el-select v-model="designatedPositions" multiple :placeholder="$t('请选择') + $t('指定岗位')" @change="changeDesignated" style="width: 400px">
                <el-option
                  v-for="dict in designatedPositionOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('培训开始日期')" prop="courseStartdate">
              <el-date-picker clearable size="small" style="width: 200px"
                              v-model="form.courseStartdate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :placeholder="$t('请选择') + $t('培训开始日期')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('指定人员')" prop="designatedStaff" v-if="haveDesignated === true && designatedPositions.length > 0">
              <el-select v-model="designatedStaffs" filterable multiple :placeholder="$t('请选择') + $t('指定人员')"  style="width: 400px">
                <el-option
                  v-for="dict in designatedStaffsOptions"
                  :key="dict.staffid"
                  :label="dict.name"
                  :value="dict.staffid">
                  <span style="float: left">{{ dict.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.staffid }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('培训结束日期')" prop="courseEnddate">
              <el-date-picker clearable size="small" style="width: 200px"
                              v-model="form.courseEnddate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :placeholder="$t('请选择') + $t('培训结束日期')">
              </el-date-picker>
            </el-form-item >
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('是否完成')" prop="isfinish">
              <el-select v-model="form.isfinish" :placeholder="$t('请选择') + $t('是否完成')">
                <el-option
                  v-for="dict in isfinishOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="parseInt(dict.dictValue)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="培训考试" prop="examId">
              <el-select v-model="form.examId" filterable  :placeholder="$t('请选择') + $t('培训考试')">
                <el-option
                  v-for="dict in examOptions"
                  :key="dict.examId"
                  :label="dict.title"
                  :value="dict.examId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('备注')" prop="remarks">
              <el-input v-model="form.remarks" :placeholder="$t('请输入') + $t('备注')" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="submitDisabled">{{ $t('确 定') }}</el-button>
        <el-button @click="cancel">{{ $t('取 消') }}</el-button>
      </div>
    </el-dialog>

    <!-- 添加参与公司级培训人员名单对话框 -->
    <el-dialog  :close-on-click-modal="false" v-dialogDrag title="培训人员名单" :visible.sync="personOpen" width="1500px" append-to-body>
      <el-form ref="personForm" :model="personForm"  label-width="80px">

        <el-form-item :label="$t('课程名称')" prop="item">
          <el-input v-model="personForm.course" disabled />
        </el-form-item>
        <el-form-item :label="$t('实际岗位')">
          <el-checkbox-group v-model="checkboxPost" size="medium" @change="postChange">
            <el-checkbox-button v-for="post in positionOptions" :label="post.dictValue" :key="post.dictValue">{{post.dictLabel}}</el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div class="staff_checked">
        <el-transfer v-model="checked" :data="selectPersonOptions" @change="staffChange" :left-default-checked="leftList" filterable
                     :titles="['无需参培人员', '需要参培人员']"
        >
          <span slot-scope="{ option }">{{ option.label }}
            <span style="float: right; color: #8492a6; font-size: 12px; padding-left: 10px;padding-right: 15px;">{{ option.staffid }}</span>
            <span style="float: right; color: #8492a6; font-size: 12px; padding-left: 10px;">{{ option.actualpost }}</span>
          </span>
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitParticipants">{{ $t('确 定') }}</el-button>
        <el-button @click="cancelParticipants">{{ $t('取 消') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listTrainingbcc,getTrainingbccStaffIds,updateTrainingbccStaffIds, getTrainingbcc, delTrainingbcc, addTrainingbcc, updateTrainingbcc, exportTrainingbcc } from "@/api/training/trainingbcc";
import nonAdd from './trainingNon'
import newAdd from './trainingNew'
import {listStaffmgrAll, listAllStaffmgr, listStaffmgr, selectTimeStaffmgr} from "@/api/plant/staffmgr";
import { treeselect } from "@/api/system/dept";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { allFileList, listCommonfile, getCommonfile, delCommonfile, addCommonfile, updateCommonfile, exportCommonfile} from "@/api/common/commonfile";
import {getCompanylevel, updateCompanylevel} from "@/api/training/companylevel";
import {listExam} from "@/api/training/elearn/exam";


export default {
  name: "Training",
  components: { Treeselect, nonAdd, newAdd},
  data() {
    return {
      // 遮罩层
      loading: true,
      positionVisible: false,
      showFlag: false,
      //确认按钮是否可点
      submitDisabled: false,
      //左侧选框默认选择
      leftList: [],
      // 选中数组
      ids: [],
      //人员筛选按钮选择数据
      checkboxPost: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 培训计划表格数据
      trainingList: [],
      positionIds: [],
      trainers: [],
      units: [],
      nonParticipants: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      clientHeight:300,
      // 是否显示弹出层
      open: false,
      personOpen: false,
      // 装置名称字典
      plantCodeOptions: [],
      // 部门字典
      unitOptions: [],
      examOptions: [],
      // 培训岗位字典
      positionOptions: [],
      //选择人员数据
      checked: [],
      trainingTypeOptions: [],
      // 是否完成字典
      isfinishOptions: [],
      // 指定岗位字典
      designatedPositionOptions: [],
      //指定人员岗位多选
      designatedPositions: [],
      //指定人员id多选
      designatedStaffs: [],
      selectPersonOptions: [],
      //是否存在岗位多选
      haveDesignated: '',
      //人员表联查
      stffmgrOptions: undefined,
      //人员表联查-包含离职
      stffmgrAllOptions: undefined,
      //指定人员选项
      designatedStaffsOptions: [],
      // 用户导入参数
      upload: {
        downloadAction: process.env.VUE_APP_BASE_API + '/common/template',
        //下载模板类型
        type: "training",
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/training/training/importData"
      },
      //未参会人员弹窗是否打开
      nonVisible: false,
      //新员工弹窗是否打开
      newVisible: false,
      // 报告附件参数
      doc: {
        file: "",
        // 是否显示弹出层（报告附件）
        open: false,
        // 弹出层标题（报告附件）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 报告附件上传位置编号
        ids: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/commonfile/uploadFile",
        commonfileList: null,
        queryParams: {
          pId: null,
          pType: 'training'
        },
        pType: 'training',
        pId: null
      },
      pdf : {
        title: '',
        pdfUrl: '',
        numPages: null,
        open: false,
        pageNum: 1,
        pageTotalNum: 1,
        loadedRatio: 0,
      },
      pic: {
        imageUrl: '',
        fileList: [],
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/training/training/uploadFile",
      },
      photoList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        course: null,
        position: [],
        years: this.getNowTime(),
        isfinish: null,
        startDate: null,
        endDate: null,
        trainingType: null,
        isNon: null,
      },
      trainingId: null,
      //地址
      downloadAction: process.env.VUE_APP_BASE_API + '/training/training/trainingReport',
      //人员表查询参数
      staffmgrQueryParams: {},
      searchStaffmgr: "",
      //日期快速选择
      pickerOptions: {
        shortcuts: [{
          text: this.$t('最近一周'),
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: this.$t('最近一个月'),
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: this.$t('最近三个月'),
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      //日期选择器
      chooseDate: [],
      // 表单参数
      form: {},
      personForm: {},
      // 表单校验
      rules: {
        course: [
          { required: true, message: this.$t('培训课程') + this.$t('不能为空'), trigger: "blur" }
        ],
        trainingType: [
          { required: true, message: this.$t('培训类型') + this.$t('不能为空'), trigger: "blur" }
        ],
        trainer: [
          { required: true, message: this.$t('培训人') + this.$t('不能为空'), trigger: "blur" }
        ],
        unit: [
          { required: true, message: this.$t('部门') + this.$t('不能为空'), trigger: "blur" }
        ],
        position: [
          { required: true, message: this.$t('培训岗位') + this.$t('不能为空'), trigger: "blur" }
        ],
        years: [
          { required: true, message: this.$t('年份') + this.$t('不能为空'), trigger: "blur" }
        ],
        courseStartdate: [
          { required: true, message: this.$t('培训开始日期') + this.$t('不能为空'), trigger: "blur" }
        ],
        isfinish: [
          { required: true, message: this.$t('是否完成') + this.$t('不能为空'), trigger: "blur" }
        ],
        deptId: [
          { required: true, message: this.$t('部门编号') + this.$t('不能为空'), trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    const queryName = this.$route.query && this.$route.query.status;
    if (queryName == '未参培'){
      this.queryParams.isNon = "1"
    }
    if (queryName == '已完成'){
      this.queryParams.isNon = "2"
    }
    if (queryName == '未完成'){
      this.queryParams.isNon = "3"
    }

    this.getStaffmar();
    this.getStaffmarAll();
    listExam({ pageNum: 1, pageSize: 1000,  examType: 2 }).then(response => {
      this.examOptions = response.rows;
    });

    //设置表格高度对应屏幕高度
    this.$nextTick(() => {
      this.clientHeight = (document.body.clientHeight - 80) * 0.8
    })
    this.getTreeselect();
    this.getDicts("PLANT_DIVIDE").then(response => {
      this.plantCodeOptions = response.data;
    });
    this.getDicts("ACTUALPOST").then(response => {
      this.positionOptions = response.data;
      this.designatedPositionOptions = response.data;
      const allData = response.data
      const data = [];
      for (let i = 0; i < allData.length; i++) {
        data.push({
          key: allData[i].dictValue,
          label: allData[i].dictLabel,
        });
      }
      this.positionOpt = response.data;
    });
    this.getDicts("YES_NO_EN").then(response => {
      this.isfinishOptions = response.data;
    });
    this.getDicts("STAFF_UNIT").then(response => {
      this.unitOptions = response.data;
    });
    this.getDicts("TRAINING_TYPE_BCC").then(response => {
      this.trainingTypeOptions = response.data;
    });
  },
  methods: {
    /** 查询培训计划列表 */
    getList() {
      let _this = this
      this.loading = true;
      listTrainingbcc(this.queryParams).then(response => {
        this.trainingList = response.rows;
        this.trainingList.forEach(function (value,key,arr) {
          var positionid = null;
          var positionName = null;
          let unitid = null;
          let unitName = null;
          if (value.position != null) {
            positionid = value.position.split(',');
            positionid.forEach(function (value, key, arr) {
              if (key != 0) {
                positionName = positionName + "," + _this.selectDictLabel(_this.positionOptions, value);
              }else if (key == 0) {
                positionName = _this.selectDictLabel(_this.positionOptions, value);
              }
            })
          }

          if (value.unit != null) {
            unitid = value.unit.split(',');
            unitid.forEach(function (value, key, arr) {
              if (key != 0) {
                unitName = unitName + "," + _this.selectDictLabel(_this.unitOptions, value);
              }else if (key == 0) {
                unitName = _this.selectDictLabel(_this.unitOptions, value);
              }
            })
          }
          _this.trainingList[key].positionid = value.position;
          _this.trainingList[key].position = positionName;
          _this.trainingList[key].unitid = value.unit;
          _this.trainingList[key].unit = unitName;

          var parentName = null;
          if (value.trainer != null) {
            let staffId = value.trainer.split(",");
            staffId.forEach(function (id, index) {
              _this.stffmgrAllOptions.forEach(function (item) {
                if (item.staffid === id) {
                  if (index === 0) {
                    parentName = item.name
                  }else {
                    parentName = parentName + "," + item.name
                  }
                }
              });
            });
          }
          _this.trainingList[key].trainer = parentName;
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取当前年份 */
    getNowTime() {
      var now = new Date();
      var year = now.getFullYear(); //得到年份
      var defaultDate = `${year}`;
      defaultDate = `${year}`
      return defaultDate;
    },
    closeChildDialog () {
      this.showFlag = false
      this.getList();
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 装置名称字典翻译
    plantCodeFormat(row, column) {
      return this.selectDictLabel(this.plantCodeOptions, row.plantCode);
    },
    // 部门字典翻译
    unitFormat(row, column) {
      return this.selectDictLabel(this.unitOptions, row.unit);
    },
    // 培训类型翻译
    trainingTypeFormat(row, column) {
      return this.selectDictLabel(this.trainingTypeOptions, row.trainingType);
    },
    // 培训岗位字典翻译
    positionFormat(row, column) {
      return this.selectDictLabel(this.positionOptions, row.position);
    },
    // 是否完成字典翻译
    isfinishFormat(row, column) {
      return this.selectDictLabel(this.isfinishOptions, row.isfinish);
    },
    //获取人员表
    getStaffmar(year) {
      this.staffmgrQueryParams.leftYear = year
      listAllStaffmgr(this.staffmgrQueryParams).then(response => {
        this.stffmgrOptions = response.rows;
        //
        const allData = response.rows
        const data = [];
        for (let i = 0; i < allData.length; i++) {
          data.push({
            key: allData[i].staffid,
            label: allData[i].name,
            staffid: allData[i].staffid,
            actualpost: this.selectDictLabel(this.positionOptions, allData[i].actualpost)
          });
        }
        this.selectPersonOptions = data;

      });
    },
    //年份选择change事件
    handleStaff(val){
      this.getStaffmar(val)
    },
    //获取人员表--包含离职
    getStaffmarAll() {
      listStaffmgrAll(this.staffmgrQueryParams).then(response => {
        this.stffmgrAllOptions = response.rows;
        this.getList();
      });
    },
    //遍历人员表
    forEachStaffmar(id) {
      let stffmgrName = "";
      this.stffmgrOptions.forEach(function (item) {
        if (item.staffid === id) {
          stffmgrName = item.name
        }
      });
      return stffmgrName
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        plantCode: null,
        course: null,
        courseid: null,
        period: null,
        duration: null,
        trainer: null,
        positionId: [],
        position: null,
        content: null,
        unit : null,
        years: null,
        courseStartdate: null,
        courseEnddate: null,
        isfinish: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        remarks: null,
        deptId: null,
        startDate: null,
        endDate: null,
        nonParticipants: null,
        trainingType: null,
        picUrl: null,
        mustTraining: null,
        haveTraining: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.startDate = this.chooseDate[0];
      this.queryParams.endDate = this.chooseDate[1];
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.chooseDate = "";
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //根据分数显示颜色提示
    tableCellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 6 && row.isfinish == 0){
        return "color: rgba(255, 26, 26, 0.98) "
      }
    },
    //培训岗位变动
    changePosition() {
      let _this = this
      this.getDicts("ACTUALPOST").then(response => {
        this.designatedPositionOptions = response.data;
        this.form.position.forEach(function (value, key, arr) {
          _this.designatedPositionOptions.forEach(function (positionValue, positionkey, arr) {
            if (positionValue.dictValue === value) {
              _this.designatedPositionOptions.splice(positionkey ,1)
            }
          })
        })
      });
    },
    //指定人员训岗位变动
    changeDesignated() {
      if (this.designatedPositions.length > 0) {
        var designatedId = null;
        this.designatedPositions.forEach(function (value,key,arr) {
          if (key != 0) {
            designatedId = designatedId + "," + value;
          }else if (key == 0) {
            designatedId = value;
          }
        })
        this.staffmgrQueryParams.actualposts = designatedId;
        listStaffmgr(this.staffmgrQueryParams).then(response => {
          this.designatedStaffsOptions = response.rows;
        });

        let _this = this
        this.getDicts("ACTUALPOST").then(response => {
          this.positionOptions = response.data;
          this.designatedPositions.forEach(function (value, key, arr) {
            _this.positionOptions.forEach(function (positionValue, positionkey, arr) {
              if (positionValue.dictValue === value) {
                _this.positionOptions.splice(positionkey ,1)
              }
            })
          })
        });
      }else {
        this.designatedStaffs = [];
      }
    },
    //指定人员按钮变动
    changeHave() {
      if (this.haveDesignated === false) {
        this.designatedPositions = []
        this.designatedStaffs = []
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.submitDisabled = false;
      this.haveDesignated = false;
      this.designatedPositions = [];
      this.getDicts("ACTUALPOST").then(response => {
        this.positionOptions = response.data;
      });
      this.getDicts("ACTUALPOST").then(response => {
        this.designatedPositionOptions = response.data;
      });
      this.form.trainingType = this.queryParams.trainingType
      this.title = this.$t('新增') + this.$t('空格') + this.$t('培训计划');
      this.getStaffmar()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      let _this = this
      this.submitDisabled = false;
      const id = row.id || this.ids
      getTrainingbcc(id).then(response => {
        this.form = response.data;
        this.getStaffmar(response.data.years)
        if (this.form.position != null) {
          this.form.position = this.form.position.split(',');
          this.getDicts("ACTUALPOST").then(response => {
            this.designatedPositionOptions = response.data;
            this.form.position.forEach(function (value, key, arr) {
              _this.designatedPositionOptions.forEach(function (positionValue, positionkey, arr) {
                if (positionValue.dictValue === value) {
                  _this.designatedPositionOptions.splice(positionkey ,1)
                }
              })
            })
          })
        }else {
          this.getDicts("ACTUALPOST").then(response => {
            this.designatedPositionOptions = response.data;
          })
          this.form.position = [];
        }
        if (this.form.designatedPosition != null) {
          this.designatedPositions = this.form.designatedPosition.split(',');
          this.getDicts("ACTUALPOST").then(response => {
            this.positionOptions = response.data;
            this.designatedPositions.forEach(function (value, key, arr) {
              _this.positionOptions.forEach(function (positionValue, positionkey, arr) {
                if (positionValue.dictValue === value) {
                  _this.positionOptions.splice(positionkey ,1)
                }
              })
            })
          });
          this.haveDesignated = true;
          var designatedId = null;
          this.designatedPositions.forEach(function (value,key,arr) {
            if (key != 0) {
              designatedId = designatedId + "," + value;
            }else if (key == 0) {
              designatedId = value;
            }
          })
          this.staffmgrQueryParams.actualposts = designatedId;
          this.$nextTick(() => {
            listAllStaffmgr(this.staffmgrQueryParams).then(response => {
              this.designatedStaffsOptions = response.rows;
            });
          })
        }else {
          this.haveDesignated = false;
          this.designatedPositions = [];
          this.getDicts("ACTUALPOST").then(response => {
            this.positionOptions = response.data;
          })
        }
        if (this.form.designatedStaff != null) {
          this.designatedStaffs = this.form.designatedStaff.split(',');
        }else {
          this.designatedStaffs = [];
        }
        if (this.form.unit != null) {
          this.form.unit = this.form.unit.split(',');
          /*this.changeUnit(this.form.unit)*/
        }else {
          this.form.unit = [];
        }
        if (this.form.nonParticipants != null) {
          this.nonParticipants = this.form.nonParticipants.split(",");
        }
        if (this.form.picUrl!= null){
          this.photoList =[]
          let fileList = this.form.picUrl.split(",")
          for (let i = 0; i < fileList.length; i++) {
            let item = {url: process.env.VUE_APP_BASE_API +fileList[i],response: {msg: fileList[i]} }
            this.photoList.push(item)
          }
        }
        if (this.form.trainer != null) {
          this.form.trainer = this.form.trainer.split(',');
        }else {
          this.form.trainer = [];
        }
        this.open = true;
        this.title = this.$t('修改')  + this.$t('培训计划');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.submitDisabled = true;
      this.$refs["form"].validate(valid => {
        if (valid) {
          var trainerId = null;
          this.form.trainer.forEach(function (value,key,arr) {
            if (key != 0) {
              trainerId = trainerId + "," + value;
            }else if (key == 0) {
              trainerId = value;
            }
          })

          var id = null;
          this.form.position.forEach(function (value,key,arr) {
            if (key != 0) {
              id = id + "," + value;
            }else if (key == 0) {
              id = value;
            }
          })

          var designatedId = null;
          this.designatedPositions.forEach(function (value,key,arr) {
            if (key != 0) {
              designatedId = designatedId + "," + value;
            }else if (key == 0) {
              designatedId = value;
            }
          })
          this.form.designatedPosition = designatedId;

          var staffId = null;
          this.designatedStaffs.forEach(function (value,key,arr) {
            if (key != 0) {
              staffId = staffId + "," + value;
            }else if (key == 0) {
              staffId = value;
            }
          })
          this.form.designatedStaff = staffId;

          var u = null;
          this.form.unit.forEach(function (value,key,arr) {
            if (key != 0) {
              u = u + "," + value;
            }else if (key == 0) {
              u = value;
            }
          })

          var parentId = null;
          this.nonParticipants.forEach(function (value,key,arr) {
            if (key != 0) {
              parentId = parentId + "," + value;
            }else if (key == 0) {
              parentId = value;
            }
          })
          this.form.trainer = trainerId;
          this.form.position = id;
          this.form.unit = u;
          // this.form.nonParticipants = parentId;
          if (this.form.id != null) {
            updateTrainingbcc(this.form).then(response => {
              this.msgSuccess(this.$t('修改成功'));
              this.open = false;
              this.submitDisabled = false;
              this.getList();
            });
          } else {
            addTrainingbcc(this.form).then(response => {
              this.msgSuccess(this.$t('新增成功'));
              this.open = false;
              this.submitDisabled = false;
              this.getList();
            });
          }
        } else {
          this.submitDisabled = false;
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: "warning"
      }).then(function() {
        return delTrainingbcc(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess(this.$t('删除成功'));
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm(this.$t('是否确认导出所有培训计划数据项?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: "warning"
      }).then(function() {
        return exportTrainingbcc(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },

    /** 参会人员名单按钮操作 */
    handleStaffmgr(row) {
      this.leftList = [];
      const id = row.id || this.ids
      getTrainingbccStaffIds(id).then(response => {
        this.personForm = response.data;
        if (response.data.staffIds != null) {
          this.checked = response.data.staffIds.split(",");
        }else {
          this.checked = [];
        }
        this.personOpen = true;
      });
    },
    handleDetail(row){
      this.$router.push({ name: 'deviceList', params: { id: row.id }})
    },
    //岗位筛选变动
    postChange() {
      this.leftList = [];
      if (this.checkboxPost.length > 0) {
        this.staffmgrQueryParams.actualposts = this.checkboxPost.toString();
        this.$nextTick(() => {
          selectTimeStaffmgr(this.staffmgrQueryParams).then(response => {
            const allData = response.rows
            const data = [];
            for (let i = 0; i < allData.length; i++) {
              data[i] = allData[i].staffid
            }
            this.leftList = data;
          })
        })
      }
    },

    //选择参会人员变动
    staffChange() {
      this.personForm.staffIds = this.checked.toString()
    },

    selectCourse(val) {
      this.queryParams.trainingType = val
      this.handleQuery()
    },
    /** 参会人员提交按钮 */
    submitParticipants() {
      this.$refs["personForm"].validate(valid => {
        if (valid) {
          updateTrainingbccStaffIds(this.personForm).then(response => {
            this.msgSuccess(this.$t('修改成功'));
            this.personOpen = false;
            this.checkboxPost = [];
            this.getList();
          });
        }
      });
    },
    // 选择参会人员取消按钮
    cancelParticipants() {
      this.personOpen = false;
      this.reset();
    },
  }
};
</script>
<style scoped>
.staff_checked >>> .el-transfer-panel {
  width : 600px;
}
.el-transfer-panel__item.el-checkbox {
  width: 553px !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
