<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="serialNum">
        <el-input
          v-model="queryParams.serialNum"
          :placeholder="$t('请输入') + $t('序号')"
          clearable
          size="small"
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('课程代码')" prop="courseCode">
        <el-input
          v-model="queryParams.courseCode"
          :placeholder="$t('请输入') + $t('课程代码')"
          clearable
          size="small"
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('课程名称')" prop="item">
        <el-input
          v-model="queryParams.item"
          :placeholder="$t('请输入') + $t('课程名称')"
          clearable
          size="small"
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('参会人员名单')" prop="staffId">
        <el-input
          v-model="queryParams.staffId"
          :placeholder="$t('请输入') + $t('需参会人员')+ $t('空格') + $t('员工号')"
          clearable
          size="small"
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('备注')" prop="remarks">
        <el-input
          v-model="queryParams.remarks"
          :placeholder="$t('请输入') + $t('备注')"
          clearable
          size="small"
          @input="handleQuery"
        />
      </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:companylevel:add']"
        >{{ $t('新增') }}</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          @click="handleDeleteAll"
          v-hasPermi="['training:companylevel:remove']"
        >清除历史参会数据</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:companylevel:remove']"
        >{{ $t('删除') }}</el-button>
      </el-col>
        <el-col :span="1.5">
            <el-button
                    type="info"
                    icon="el-icon-upload2"
                    size="mini"
                    @click="handleImport"
                    v-hasPermi="['training:companylevel:edit']"
            >{{ $t('导入培训记录') }}</el-button>
        </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-refresh"
          size="mini"
          @click="handleScore"
        >{{ $t('更新培训成绩') }}</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="companylevelList" @selection-change="handleSelectionChange" :height="clientHeight" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('序号')" align="center" prop="serialNum" width="70" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('课程代码')" align="center" prop="courseCode" width="150" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('课程名称')" align="center" prop="item" width="500" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('频率')" align="center" prop="frequency" width="100" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          <span v-if="scope.row.frequency !== null">每{{scope.row.frequency}}年一次</span>
          <span v-else>一次</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('参会人员名单')" align="center" prop="staffId" width="400" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('备注')" align="center" prop="remarks" width="300" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('操作')" align="center" fixed="right" width="300" 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:companylevel:edit']"
          >{{ $t('修改') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleStaffmgr(scope.row)"
          >{{ $t('参会人员名单') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['training:companylevel:remove']"
          >{{ $t('删除') }}</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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item :label="$t('序号')" prop="serialNum">
          <el-input v-model="form.serialNum" :placeholder="$t('请输入') + $t('序号')" />
        </el-form-item>
        <el-form-item :label="$t('课程代码')" prop="courseCode">
          <el-input v-model="form.courseCode" :placeholder="$t('请输入') + $t('课程代码')" />
        </el-form-item>
        <el-form-item :label="$t('课程名称')" prop="item">
          <el-input v-model="form.item" :placeholder="$t('请输入') + $t('课程名称')" />
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('是否需要重复培训')" prop="needFrequency" label-width="125px">
              <el-checkbox v-model="needFrequency"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item :label="$t('频率')" prop="frequency" v-if="needFrequency === true">
              {{ $t('每') }}
              <el-input-number v-model="form.frequency" controls-position="right" :min="1" :max="10" size="mini"></el-input-number>
              {{ $t('年一次') }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item :label="$t('参会人员名单')" prop="staffId">
          <el-input v-model="form.staffId" :placeholder="$t('请输入') + $t('参会人员名单')" type="textarea"/>
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remarks">
          <el-input v-model="form.remarks" :placeholder="$t('请输入') + $t('备注')" />
        </el-form-item>
          <el-form-item :label="$t('归属部门')" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :placeholder="$t('请选择') + $t('归属部门')" />
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('确 定') }}</el-button>
        <el-button @click="cancel">{{ $t('取 消') }}</el-button>
      </div>
    </el-dialog>
    <!-- 添加参与公司级培训人员名单对话框 -->
    <el-dialog  :close-on-click-modal="false" v-dialogDrag :title="participantsTitle" :visible.sync="participantsOpen" width="1500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item :label="$t('序号')" prop="serialNum">
          <el-input v-model="form.serialNum" disabled />
        </el-form-item>
        <el-form-item :label="$t('课程代码')" prop="courseCode">
          <el-input v-model="form.courseCode" disabled />
        </el-form-item>
        <el-form-item :label="$t('课程名称')" prop="item">
          <el-input v-model="form.item" 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 actualpostOptions" :label="post.key" :key="post.key">{{post.label}}</el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="$t('人员姓名')">
          <el-select v-model="searchStaffmgr" filterable :placeholder="$t('请选择') + $t('人员')">
            <el-option
              v-for="dict in stffmgrOptions"
              :key="dict.staffid"
              :label="dict.label"
              :value="dict.staffid">
              <span style="float: left">{{ dict.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.staffid }}</span>
            </el-option>
          </el-select>
          <el-button type="primary" @click="insertSearchStaffmgr" style="margin-left: 15px;">{{ $t('添加') }}</el-button>
        </el-form-item>
      </el-form>
      <div class="staff_checked">
        <el-transfer v-model="checked" :data="stffmgrOptions" @change="staffChange" :left-default-checked="leftList" >
          <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>
    <!-- 用户导入对话框 -->
    <el-dialog  :close-on-click-modal="false" v-loading="upload.isUploading" v-dialogDrag :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
                ref="upload"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
        >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
          {{ $t('将文件拖到此处，或') }}
          <em>{{ $t('点击上传') }}</em>
        </div>
            <div class="el-upload__tip" slot="tip">
                <!--<el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据-->
                <el-link type="info" style="font-size:12px" @click="importTemplate">{{ $t('下载模板') }}</el-link>
            </div>
          <form ref="downloadFileForm" :action="upload.downloadAction" target="FORMSUBMIT">
            <input name="type" :value="upload.type" hidden />
          </form>
            <div class="el-upload__tip" style="color:#ff0000" slot="tip">{{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}</div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">{{ $t('确 定') }}</el-button>
        <el-button @click="upload.open = false">{{ $t('取 消') }}</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCompanylevel, updateScore, resetCompanylevel, getCompanylevel, delCompanylevel, addCompanylevel, updateCompanylevel, exportCompanylevel, importTemplate} from "@/api/training/companylevel";
import { deleteAll } from "@/api/training/participants";
import {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";

export default {
  name: "Companylevel",
  components: { Treeselect },
  data() {
    return {
      //选择人员数据
      checked: [],
      //岗位字典数据
      actualpostOptions: [],
      //人员筛选按钮选择数据
      checkboxPost: [],
      // 遮罩层
      loading: true,
      uploadLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 公司级培训表格数据
      companylevelList: [],
      // 培训岗位字典
      positionOptions: [],
      //左侧选框默认选择
      leftList: [],
      // 弹出层标题
      title: "",
      participantsTitle: "",
      // 部门树选项
      deptOptions: undefined,
      clientHeight:300,
      // 是否显示弹出层
      open: false,
      participantsOpen: false,
      //搜索人员
      searchStaffmgr: "",
      // 用户导入参数
      upload: {
        downloadAction: process.env.VUE_APP_BASE_API + '/common/template',
        //下载模板类型
        type: "companyLevelRecord",
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/training/hisparticipants/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        serialNum: null,
        courseCode: null,
        item: null,
        staffId: null,
        remarks: null,
      },
      //人员表查询参数
      staffmgrQueryParams: {
        units: "10,18,20,30",
        leftYear: this.getNowTime(),
        actualpost: null
      },
      //人员表联查
      stffmgrOptions: undefined,
      // 表单参数
      form: {},
      //是否需要重复培训
      needFrequency: '',
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: this.$t('部门编号') + this.$t('不能为空') , trigger: "blur" }
        ]
      }
    };
  },
  watch: {
      // 根据名称筛选部门树
      deptName(val) {
          this.$refs.tree.filter(val);
      }
   },
  created() {
    //设置表格高度对应屏幕高度
    this.$nextTick(() => {
        this.clientHeight = document.body.clientHeight -250
    })
    this.getStaffmar();
    this.getPost();
    this.getTreeselect();
    this.getDicts("ACTUALPOST").then(response => {
      this.positionOptions = response.data;
    });
  },
  methods: {
    /** 查询公司级培训列表 */
    getList() {
      this.loading = true;
      let _this = this
      listCompanylevel(this.queryParams).then(response => {
        this.companylevelList = response.rows;
        this.companylevelList.forEach(function (value,key,arr) {
          let stffmgrName = "";
          if (value.staffId != null) {
            let staffId = value.staffId.split(",");
            staffId.forEach(function (id, index) {
              _this.stffmgrOptions.forEach(function (item) {
                if (item.key === id) {
                  if (index === 0) {
                    stffmgrName = item.label
                  }else {
                    stffmgrName = stffmgrName + "," + item.label
                  }
                }
              });
            });
          }
          _this.companylevelList[key].staffId = stffmgrName
        });
        this.total = response.total;
        this.loading = false;
      });
    },
     /** 查询部门下拉树结构 */
     getTreeselect() {
          treeselect().then(response => {
              this.deptOptions = response.data;
          });
     },
    /** 获取当前年份 */
    getNowTime() {
      var now = new Date();
      var year = now.getFullYear(); //得到年份
      var defaultDate = `${year}`;
      defaultDate = `${year}`
      return defaultDate;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 选择参会人员取消按钮
    cancelParticipants() {
      this.participantsOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serialNum: null,
        courseCode: null,
        item: null,
        staffId: null,
        remarks: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        frequency: null,
        deptId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //获取人员表
    getStaffmar() {
      selectTimeStaffmgr(this.staffmgrQueryParams).then(response => {
        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.stffmgrOptions = data;
        this.getList();
      })
    },
    //获取岗位字典
    getPost() {
      this.getDicts("ACTUALPOST").then(response => {
        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.actualpostOptions = data
      });
    },
    //选择参会人员变动
    staffChange() {
      this.form.staffId = this.checked.toString()
    },
    //岗位筛选变动
    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;
          })
        })
      }
    },
    // 多选框选中数据
    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.needFrequency = false;
      this.title = this.$t('新增') + this.$t('空格') + this.$t('公司级培训');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCompanylevel(id).then(response => {
        this.form = response.data;
        //是否需要重复培训内容
        if (this.form.frequency != null) {
          this.needFrequency = true;
        }else {
          this.needFrequency = false;
        }
        this.open = true;
        this.title = this.$t('修改') + this.$t('公司级培训');
      });
    },
    /** 参会人员名单按钮操作 */
    handleStaffmgr(row) {
      this.leftList = [];
      const id = row.id || this.ids
      getCompanylevel(id).then(response => {
        this.form = response.data;
        if (response.data.staffId != null) {
          this.checked = response.data.staffId.split(",");
        }else {
          this.checked = [];
        }
        this.participantsOpen = true;
        this.participantsTitle = this.$t('参加') +this.$t('空格')+ this.$t('公司级') + this.$t('空格') + this.$t('培训人员') + this.$t('空格') + this.$t('名单');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.needFrequency === false) {
            this.form.frequency = null
          }
          if (this.form.id != null) {
            updateCompanylevel(this.form).then(response => {
              this.msgSuccess(this.$t('修改成功'));
              this.open = false;
              this.getList();
              this.handleScore();
            });
          } else {
            addCompanylevel(this.form).then(response => {
              this.msgSuccess(this.$t('新增成功'));
              this.open = false;
              this.getList();
              this.handleScore();
            });
          }
        }
      });
    },
    /** 参会人员提交按钮 */
    submitParticipants() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateCompanylevel(this.form).then(response => {
            this.msgSuccess(this.$t('修改成功'));
            this.participantsOpen = false;
            this.checkboxPost = [];
            this.getList();
            this.handleScore();
          });
        }
      });
    },
    /** 参会人员人名搜索添加按钮 */
    insertSearchStaffmgr() {
      const data = [];
      for (let i = 0; i < this.leftList.length; i++) {
        data.push(this.leftList[i])
      }
      data.push(this.searchStaffmgr)
      this.leftList = data
      this.$nextTick(() => {
        this.searchStaffmgr = "";
      })
    },
    /** 删除按钮操作 */
    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 delCompanylevel(ids);
      }).then(() => {
        this.getList();
        this.handleScore();
        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 exportCompanylevel(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    /** 导入按钮操作 */
    handleImport() {
        this.upload.title = this.$t('导入培训记录');
        this.upload.open = true;
    },
    handleScore(){
      updateScore().then(response => {
        const allData = response
        this.msgSuccess(this.$t('更新成功'));
      })
    },
    /** 下载模板操作 */
    importTemplate() {
      this.$refs['downloadFileForm'].submit()
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if (response.data[0] != null) {
        this.$alert(this.$t('成功导入') + response.msg + this.$t('条数据') + "，" + this.$t('第') + response.data + this.$t('行数据出现错误导入失败')+"。", this.$t('导入结果'), { dangerouslyUseHTMLString: true });
      }else {
        this.$alert(this.$t('成功导入') + response.msg + this.$t('条数据'), this.$t('导入结果'), { dangerouslyUseHTMLString: true });
      }
      this.handleScore();
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
        this.$refs.upload.submit();
    },
    //清除所有历史数据
    handleDeleteAll() {
      let _this = this
      this.$confirm(this.$t('是否确认重置公司级培训参会人员信息?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: "warning"
      }).then(function() {
        deleteAll().then(response => {
          resetCompanylevel(_this.form).then(response => {
            _this.msgSuccess(this.$t('清除成功'));
            _this.getList();
          });
        })
      })
    }
  }
};
</script>

<style scoped>
  .staff_checked >>> .el-transfer-panel {
    width : 600px;
  }
  .el-transfer-panel__item.el-checkbox {
    width: 553px !important;
  }
</style>
