<template>
  <basic-container>
    <!-- 培训记录管理 -->
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model="form"
      v-model:page="page"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu-left>
        <el-button type="primary" @click="handleIssue('all')">批量下发</el-button>
        <el-button type="primary" @click="handleUpload('all')">资料批量上传</el-button>
        <el-button type="primary" @click="handleFinish('all')">培训完成</el-button>
      </template>

      <template #menu="scope">
        <el-button type="text" v-if="scope.row.caStatus == 1" @click="handleUpdate(scope.row)"
          >修改</el-button
        >
        <el-button
          type="text"
          v-if="scope.row.caStatus == 3 || scope.row.caStatus == 4 || scope.row.caStatus == 5"
          @click="handleDetail(scope.row)"
          >培训详情</el-button
        >
        <el-button type="text" v-if="scope.row.caStatus == 2" @click="handleIssue('one', scope.row)"
          >下发</el-button
        >
        <el-button
          type="text"
          v-if="scope.row.caStatus == 3"
          @click="handleUpload('one', scope.row)"
          >资料上传</el-button
        >
        <el-button
          type="text"
          v-if="scope.row.caStatus == 5"
          @click="handleFinish('one', scope.row)"
          >完成</el-button
        >
      </template>
    </avue-crud>

    <!-- 资料上传 -->
    <el-dialog title="资料上传" append-to-body v-model="fileDialog" width="555px" v-if="fileDialog">
      <avue-form :option="fileOption" v-model="fileForm" :upload-after="uploadAfter"> </avue-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="submitUpload()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="培训详情" append-to-body v-model="detailDialog">
      <el-table :data="detailData">
        <el-table-column align="center" label="培训师" prop="teacherName"></el-table-column>
        <el-table-column align="center" label="完成时间" prop="finishTime"></el-table-column>
        <el-table-column align="center" label="状态" prop="caStatusName"></el-table-column>
        <el-table-column align="center" label="资料">
          <template #default="scope">
            <!-- attachLink -->
            <el-button type="text">资料下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 培训计划 -->
    <el-dialog title="培训计划" append-to-body v-model="planOpen" width="450px" v-if="planOpen">
      <el-form
        ref="form"
        :model="formModel"
        label-width="80px"
        :rules="formRules"
        class="vd-form-row"
      >
        <el-form-item label="培训模板" prop="trainingPlanId">
          <el-select v-model="formModel.trainingPlanId" placeholder="请选择培训模板">
            <el-option
              v-for="item in jttpArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="培训师" prop="teacherId">
          <!-- multiple -->
          <el-select
            v-model="formModel.teacherId"
            placeholder="请输入培训师"
            @change="changeTeacher"
          >
            <el-option
              v-for="item in teacherArr"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="planOpen = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  remove,
  add,
  update,
  issued,
  trainingCompleted,
  uploadMaterials,
  configured,
} from '@/api/workLicense/trainingRecordManagement';
import { getPlanList } from '@/api/workLicense/jobTransferManagement';
import { getUserList } from '@/api/workLicense/workLicense';

export default {
  data() {
    return {
      jttpArr: [],
      teacherArr: [],
      formModel: {},
      planOpen: false,
      formRules: {
        trainingPlanId: [{ required: true, message: '请选择培训模板', trigger: 'blur' }],
        teacherId: [{ required: true, trigger: 'blur', message: '请输入培训师' }],
      },
      loading: false,
      data: [],
      form: {},
      detailDialog: false,
      selectionList: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      fileDialog: false,
      fileForm: {},
      fileOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '资料上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '附件上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data',
            },
            tip: '不能上传 附件，且不超过 10M',
            action: '/blade-system/user/import-user',
          },
        ],
      },
      option: {
        columnSort: true,
        tip: false,
        height: 'auto',
        align: 'center',
        calcHeight: 32,
        simplePage: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: false,
        selection: true,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        editBtnText: '修改',
        editBtnIcon: ' ',
        delBtnIcon: ' ',
        addBtn: false,
        labelWidth: 120,
        menu: true,
        menuWidth: 200,
        dialogWidth: 600,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: true,
        gridBtn: false,
        searchShowBtn: false,
        showOverflowTooltip: true,
        searchLabelPosition: 'left',
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: 'left',
        gridBtn: false,
        searchMenuPosition: 'right',
        addBtnIcon: ' ',
        viewBtnIcon: ' ',
        delBtnIcon: ' ',
        editBtnIcon: ' ',

        column: [
          {
            label: '姓名',
            prop: 'name',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: true,
            searchLabelWidth: 50,
          },
          {
            label: '工号',
            prop: 'code',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: true,
            searchLabelWidth: 50,
          },
          {
            label: '用工类型',
            prop: 'staffType',
            type: 'select',
            span: 8,
            labelWidth: 150,
            search: false,
            width: 200,
            editDisplay: false,
            rules: [
              {
                required: true,
                message: '请输入用工类型',
                trigger: 'click',
              },
            ],
            dicUrl: '/blade-system/dict/dictionary?code=staffType',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
          },
          {
            label: '培训类型',
            prop: 'typeName',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: true,
          },
          {
            label: '培训周期(天)',
            prop: 'cycle',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '预警周期(天)',
            prop: 'earlyWarningDay',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '培训计划',
            prop: 'planName',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '培训师',
            prop: 'teacherName',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '培训时间',
            prop: 'distributeTime',
            type: 'date',
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            searchRange: true,
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '状态',
            prop: 'caStatusName',
            type: 'select',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: true,
            dicUrl: '/blade-system/dict/dictionary?code=training_ecord_tatus',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
          },
        ],
      },
      uploadInfo: {},
      rowData: {},
    };
  },
  mounted() {
    this.getPlanList()
    this.getUserList()
  },
  methods: {
    // 修改配置
    handleUpdate(row) {
      this.rowData = row;
      this.planOpen = true;
    },
    getPlanList() {
      getPlanList().then(res => {
        this.jttpArr = res.data.data.records;
      });
    },
    getUserList() {
      getUserList({ size: 999999, current: 1 }).then(res => {
        this.teacherArr = res.data.data.records;
      });
    },
     // 切换培训师
    changeTeacher(val) {
      let select = this.teacherArr.find(e => e.id == val);
      this.formModel.teacherName = select.realName;
    },
    // 转岗/下岗提交
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const obj = {
            id: this.rowData.id, //主键集合
            teacherId: this.formModel.teacherId, //培训师id
            teacherName: this.formModel.teacherName, //培训师姓名
            planId: this.formModel.trainingPlanId, //培训模板
          };
          configured(obj).then(res => {
            this.$message.success('操作成功');
            this.planOpen = false;
            this.onLoad(this.page, this.query);
          });
        }
      });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page, this.query);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    selectionChange(val) {
      this.selectionList = val;
    },
    // 培训详情
    handleDetail(row) {
      this.detailData = [row];
      this.detailDialog = true;
    },
    // 批量下发
    handleIssue(type, row) {
      if (type == 'all') {
        if (this.selectionList.length == 0) {
          this.$message.error('请至少选择一条数据');
        } else {
          let tmp = this.selectionList.find(item => item.jduStatus != 1);
          if (tmp) {
            this.$message.error('请选择状态为待下发的数据');
          } else {
            this.$confirm('确定下发?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }).then(() => {
              issued(this.selectionList).then(res => {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                });
                this.onLoad(this.page, this.query);
              });
            });
          }
        }
      } else {
        this.$confirm('确定下发?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          issued([row]).then(res => {
            this.$message({
              message: '操作成功',
              type: 'success',
            });
            this.onLoad(this.page, this.query);
          });
        });
      }
    },
    // 批量上传
    handleUpload(type, row) {
      if (type == 'all') {
        if (this.selectionList.length == 0) {
          this.$message.error('请至少选择一条数据');
        } else {
          let tmp = this.selectionList.find(item => item.caStatus != 3);
          if (tmp) {
            this.$message.error('请选择状态为培训中的数据');
          } else {
            this.uploadInfo = this.selectionList;
            this.fileDialog = true;
          }
        }
      } else {
        this.uploadInfo = [row];
        this.fileDialog = true;
      }
    },
    // 批量上传数据
    submitUpload() {
      console.log(this.fileForm, 'fileForm');
      if (this.selectionList.length > 0) {
        this.selectionList.forEach(item => {
          item.attachLink = '';
        });
        uploadMaterials(this.selectionList).then(res => {
          this.$message.success('上传成功');
          this.fileDialog = false;

          this.onLoad(this.page, this.query);
        });
      } else {
        this.uploadInfo.forEach(item => {
          this.fileForm.attachLink = '';
        });
        uploadMaterials(this.uploadInfo).then(res => {
          this.$message.success('上传成功');
          this.fileDialog = false;
          this.onLoad(this.page, this.query);
        });
      }
    },

    // 培训完成
    handleFinish(type, row) {
      if (type == 'all') {
        if (this.selectionList.length == 0) {
          this.$message.error('请至少选择一条数据');
        } else {
          let tmp = this.selectionList.find(item => item.caStatus != 5);
          if (tmp) {
            this.$message.error('请选择状态为待确认的数据');
          } else {
            this.$confirm('确定培训完成?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }).then(() => {
              trainingCompleted(this.selectionList).then(res => {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                });
                this.onLoad(this.page, this.query);
              });
            });
          }
        }
      } else {
        this.$confirm('确定培训完成?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          trainingCompleted([row]).then(res => {
            this.$message({
              message: '操作成功',
              type: 'success',
            });
            this.onLoad(this.page, this.query);
          });
        });
      }
    },

    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        this.data = res.data.data.records;
        this.loading = false;
        this.page.total = res.data.data.total;
        // this.selectionClear();
      });
    },
  },
};
</script>

<style></style>
