<template>
  <div class="account-container" v-loading="loading">
    <div class="top" style="margin-bottom: 24px">
      <div class="account-title">{{ this.$t('trainList.trainDetail') }}</div>
      <div class="button-group" style="margin-right: 6px">
        <!--        <el-button v-if="openType !== 'view'" type="primary" icon="el-icon-circle-check" @click="submitForm"-->
        <!--                   :loading="submitLoading">{{ $t('common.confirm') }}-->
        <!--        </el-button>-->
        <el-button @click="cancel" icon="el-icon-remove-outline">
          {{ $t('common.cancel') }}
        </el-button>
      </div>
    </div>
<!--    <div class="content">-->
<!--      <div class="card card-full">-->
        <el-tabs v-model="editableTabsValue" type="border-card">
          <!--    培训方案-->
          <el-tab-pane :label="$t('trainList.trainingProgram')" name="1" :key="1">
            <el-form ref="form" :model="form" label-width="120px" style="margin-top: 20px">
              <el-row :gutter="20">
                <el-col :span="6">
                  <Input disabled prop="trainName" :label="$t('trainList.trainingName')" width="100%"/>
                </el-col>
                <el-col :span="6">
                  <Select disabled prop="trainType" :data="dict.type.training_category"
                          :label="$t('trainList.trainingCategory')"
                          :styleObj=" { width: '100%' }"></Select>
                </el-col>
                <el-col :span="6">
                  <DatePicker disabled prop="startDate" :label="$t('trainList.startTime')" width="100%"/>
                </el-col>
                <el-col :span="6">
                  <DatePicker disabled prop="endDate" :label="$t('trainList.endTime')" width="100%"/>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="6">
                  <Select disabled prop="assessFlag" :data="dict.type.train_whether_to_assess"
                          :label="$t('trainList.whetherToAssess')"
                          :styleObj=" { width: '100%' }"/>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('trainList.trainingTargets')" prop="trainingTargets">
                    <el-button disabled @click="addTrainTargetsDialog" type="primary"
                               size="mini">{{
                        $t('trainList.addObject')
                      }}
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
              <!--            培训对象列表-->
              <card-table :loading="loading" :modalData="trainTargetsList" style="width: 80%;margin: 0 40px 0 98px" :searchParams="targetQueryParams">
                <el-table-column label="No" type="index"></el-table-column>
                <el-table-column :label="$t('user.nick')" prop="nickName"></el-table-column>
                <Column :label="$t('user.role')" prop="roleId">
                  <template #default="{ row }">
                    <span>{{ row.roleNames }}</span>
                  </template>
                </Column>
<!--                <Column :label="$t('user.agent')" prop="agentName"/>-->
                <Column :label="$t('user.agent')" prop="agentName">
                  <template #default="{ row }">
                    <span v-if="row.deptId == 0">{{ $t('common.head') }}</span>
                    <span v-else>{{ row.agentName }}</span>
                  </template>
                </Column>
              </card-table>

              <el-row :gutter="20">
                <el-col :span="12">
                  <Input disabled prop="remark" type="textarea" :label="$t('trainList.remarks')" width="100%"
                         style="margin-top: 20px"/>
                </el-col>
              </el-row>

              <el-form-item :label="$t('trainList.fileList')">
                <el-button disabled @click="addTrainFileDialog" type="primary" size="mini">{{
                    $t('trainList.addFile')
                  }}
                </el-button>
              </el-form-item>
              <!--            附件列表-->
              <card-table :modal-data="fileList" style="width: 80%;margin: 0 40px 0 98px" :searchParams="fileQueryParams">
                <el-table-column label="No" type="index"></el-table-column>
                <el-table-column :label="$t('trainList.filename')" prop="fileName">
                  <template #default="{ row }">
                    <el-link :href="`${baseUrl}${row.filePath}`" :underline="false" target="_blank">{{
                        row.fileName
                      }}
                    </el-link>
                  </template>
                </el-table-column>
              </card-table>

            </el-form>
          </el-tab-pane>

          <!--    考核方案-->
          <el-tab-pane v-if="form.assessFlag === '1'" :label="$t('trainList.assessmentPlan')" name="2" :key="2">
            <el-form ref="assessmentPlanForm" :model="assessmentPlanForm" label-width="120px" style="margin-top: 20px">
              <el-row :gutter="20">
                <el-col :span="6">
                  <Input disabled prop="testPaperName" :label="$t('trainList.examName')" width="100%"/>
                </el-col>
                <el-col :span="6">
                  <el-form-item prop="passScore" :label="$t('trainList.passScore')">
                    <el-input-number :controls="false" disabled v-model="assessmentPlanForm.passScore" :min="0"
                                     :max="totalScore" style="width: 100%;"></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <Input disabled prop="testRemark" type="textarea" :label="$t('trainList.examInstructions')"
                         width="100%"/>
                </el-col>
              </el-row>
              <el-form-item :label="$t('trainList.listOfTestQuestions')" prop="listOfTestQuestions">
                <el-button icon="el-icon-view"  size="mini" type="primary" @click="preview">{{ $t('trainList.preview') }}</el-button>
                <el-button icon="el-icon-finished"  disabled size="mini" @click="selectByMyself"> {{ $t('trainList.manualTopicSelection')
                  }}
                </el-button>
                <el-button icon="el-icon-refresh" disabled size="mini" @click="randomSelect">{{
                    $t('trainList.randomSelectionOfTopics')
                  }}
                </el-button>
                <!--              <el-button size="mini" @click="importTestQuestions">{{ $t('trainList.importTestQuestions') }}</el-button>-->
                <ImportModal disabled :title="$t('common.import')" icon="el-icon-upload2" fileName="培训试题导入模板"
                             :table-type="6"
                             style="margin: 0 0 0 10px"></ImportModal>
                <div style="font-size: 12px">
                  <i class="el-icon-warning-outline" style="color: red"></i>
                  {{ $t('trainList.totalNumberOfQuestions') }}（{{
                    totalNumberOfQuestions
                  }}{{ $t('trainList.questionUnit') }}）
                  {{ $t('trainList.totalScore') }}（{{ totalScore }}{{ $t('trainList.scoreUnit') }}）
                  {{ $t('trainList.singleChoiceQuestions') }}（{{ singleChoiceQuestions }}）
                  {{ $t('trainList.multipleChoiceQuestions') }}（{{ multipleChoiceQuestions }}）
                  {{ $t('trainList.trueOrFalseQuestions') }}（{{ trueOrFalseQuestions }}）
                  {{ $t('trainList.fillInTheBlankQuestions') }}（{{ fillInTheBlankQuestions }}）
                </div>
              </el-form-item>

              <card-table :modal-data="questionList" :search-params="questionParams" style="width: 80%;margin: 0 40px 0 98px">
                <el-table-column label="No" type="index"/>
                <el-table-column :label="$t('trainList.questionContext')" align="left" prop="questionContext"
                                 :show-overflow-tooltip="true"/>
                <Column :label="$t('trainList.questionType')" prop="questionType" align="center"
                        :searchDict="dict.type.train_question_type">
                  <template #default="{ row }">
                    <span>{{ row.questionTypeName }}</span>
                  </template>
                </Column>
                <el-table-column :label="$t('trainList.score')" prop="score"
                                 align="center">
                  <template #default="{ row }">
                    <el-input-number :controls="false" disabled v-model="row.score" :min="0" :max="100"></el-input-number>
                  </template>
                </el-table-column>

              </card-table>
            </el-form>
          </el-tab-pane>

          <!--    培训跟踪-->
          <el-tab-pane :label="$t('trainList.trainingTracking')" name="3" :key="3">
            <el-row :gutter="20" style="margin-top: 20px">
              <el-col :span="form.assessFlag === '1' ? 4 : 8" :offset="2" align="center">
                <el-statistic :title="$t('trainList.trainingCompletionRate')">
                  <template slot="formatter">
                    {{getTrainingCompletionRate.rate}}
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="4" align="center">
                <el-statistic v-show="form.assessFlag === '1'" :title="$t('trainList.assessmentCompletionRate')">
                  <template slot="formatter">
                    {{getAssessmentCompletionRate.rate}}
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="form.assessFlag === '1' ? 4 : 8" align="center">
                <el-statistic :title="$t('trainList.trainCompleteNum')" :value="getTrainingCompletionRate.completeNum"/>
              </el-col>
              <el-col :span="4" align="center">
                <el-statistic v-show="form.assessFlag === '1'" :title="$t('trainList.assessCompleteNum')">
                  <template slot="formatter">
                    {{getAssessmentCompletionRate.completeNum}}
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="4" align="center">
                <el-statistic v-show="form.assessFlag === '1'" :title="$t('trainList.complianceRate')">
                  <template slot="formatter">
                    {{getComplianceRate}}
                  </template>
                </el-statistic>
              </el-col>
            </el-row>
            <card-table :modal-data="trackList" :search-params="trainingTrackingParams" style="width: 80%;margin: 20px 40px 0 160px">
              <el-table-column label="No" type="index"/>
              <Column :label="$t('trainList.participants')" prop="nickName" align="center"/>
              <Column :label="$t('user.role')" prop="roleNames" align="center"/>
              <Column :label="$t('user.agent')" prop="agentName">
                <template #default="{ row }">
                  <span v-if="row.deptId == 0">{{ $t('common.head') }}</span>
                  <span v-else>{{ row.agentName }}</span>
                </template>
              </Column>
              <Column :label="$t('trainList.trainResult')" prop="trainCompleteFlag" align="center">
                <template #default="{ row }">
                  <el-tag v-if="row.trainCompleteFlag === '0'" type="danger">{{ row.trainCompleteFlagName }}</el-tag>
                  <el-tag v-else type="success">{{ row.trainCompleteFlagName }}</el-tag>
                </template>
              </Column>
              <Column v-if="form.assessFlag === '1'" :label="$t('trainList.testResult')" prop="assessCompleteFlag" align="center">
                <template #default="{ row }">
                  <span v-if="form.assessFlag === '0'">-</span>
                  <el-tag v-else-if="row.assessCompleteFlag === '0'" type="info">{{ row.assessCompleteFlagName }}</el-tag>
                  <el-tag v-else-if="row.assessCompleteFlag === '1'" type="danger">{{ row.assessCompleteFlagName }}</el-tag>
                  <el-tag v-else type="success">{{ row.assessCompleteFlagName }}</el-tag>
                </template>
              </Column>
              <Column v-if="form.assessFlag === '1'" :label="$t('trainList.assessmentScore')" prop="totalScore" align="center"/>
              <Column :label="$t('common.operate')" :min-width="250" fixed="right" searchType="operate">
                <template #default="{ row }">
                  <el-button v-hasPermi="['train:list:view']" icon="el-icon-delete" size="mini"
                             type="text" @click="handleMove(row)">{{ $t('trainList.moveTarget') }}
                  </el-button>
                </template>
              </Column>
            </card-table>
          </el-tab-pane>
        </el-tabs>
<!--      </div>-->
<!--    </div>-->

    <!--    添加培训对象弹出层-->
    <el-dialog :close-on-click-modal="false" :title="addTrainTargetsTitle" :visible.sync="isAddTrainTargets"
               append-to-body
               custom-class="edit-dialog" width="50vw">
      <card-table :row-key="getRowKey" ref="userTable" :modalData="userList" labelWidth="120px"
                  :searchParams="userQueryParams"
                  @pagination="getUserList"
                  @selection-change="handleUserSelectionChange" :loading="loading" :tableSearch="true"
                  :reserve-selection="true"
                  @columnSearch="handleQuery" @resetList="resetQuery"
                  :delProp="['createTime']">
        <el-table-column type="selection" width="50" align="center"/>
        <!--        <Column :label="$t('user.account')" prop="userName" :searchParams="userQueryParams" :showSearch="true"/>-->
        <Column :label="$t('user.nick')" prop="nickName" :searchParams="userQueryParams" :showSearch="true"/>
        <Column :label="$t('user.role')" prop="roleId" :searchParams="userQueryParams" :showSearch="true"
                searchType="select" :searchDict="allRoleOptions" valueProp="roleId" labelProp="roleName">
          <template #default="{ row }">
            <span>{{ row.roleNames }}</span>
          </template>
        </Column>
        <Column :label="$t('user.agent')" prop="agentName" :searchParams="userQueryParams" :showSearch="true">
          <template #default="{ row }">
            <span v-if="row.deptId == 0">{{ $t('common.head') }}</span>
            <span v-else>{{ row.agentName }}</span>
          </template>
        </Column>
      </card-table>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="submitTrainTargetsForm">{{
            $t('common.confirm')
          }}
        </el-button>
        <el-button icon="el-icon-remove-outline" @click="isAddTrainTargets = false">{{
            $t('common.cancel')
          }}
        </el-button>
      </div>
    </el-dialog>

    <!--    添加附件弹出层-->
    <el-dialog :close-on-click-modal="false" :title="addTrainFileTitle" :visible.sync="isAddTrainFile" append-to-body
               custom-class="edit-dialog" width="80vw">

      <!--      资料库组件-->
      <DatabaseDialog ref="Database"/>

      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="submitFileForm">{{
            $t('common.confirm')
          }}
        </el-button>
        <el-button icon="el-icon-remove-outline" @click="isAddTrainFile = false">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <!--    手动选择题目弹框-->
    <el-dialog :close-on-click-modal="false" :title="selectDialogTitle" :visible.sync="isSelectBySelf" append-to-body
               custom-class="edit-dialog" width="80vw">
      <QuestionDatabaseDialog ref="questionDialog"/>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="submitQuestionList">{{
            $t('common.confirm')
          }}
        </el-button>
        <el-button icon="el-icon-remove-outline" @click="isSelectBySelf = false">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <!--    随机选择题目弹框-->
    <el-dialog :close-on-click-modal="false" :title="$t('trainList.randomSelectionOfTopics')"
               :visible.sync="isRandomSelect" append-to-body
               custom-class="edit-dialog" width="40vw">
      <el-table :data="questionNumList" style="width: 90%">
        <Column :label="$t('trainList.questionType')" prop="questionType" align="center">
          <template #default="{ row }">
            <span>{{ row.questionTypeName }}</span>
          </template>
        </Column>
        <el-table-column prop="questionTypeNum" :label="$t('trainList.questionTypeNum')">
          <template slot-scope="scope">
            <el-input-number  :controls="false" style="width: 90%;" v-model="scope.row.questionTypeNum" :min="0" :max="99"/>
          </template>
        </el-table-column>

      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="getRandomQuestion">{{
            $t('common.confirm')
          }}
        </el-button>
        <el-button icon="el-icon-remove-outline" @click="isRandomSelect = false">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>

import DatePicker from "@/components/element/form/items/DatePicker.vue";
import Column from "@/components/element/table/Column.vue";
import DatabaseDialog from "@/views/train/trainlist/detail/databaseDialog.vue";
import QuestionDatabaseDialog from "@/views/train/trainlist/detail/questionDatabaseDialog.vue";
import CardTable from "@/components/element/table/CardTable.vue";
import ImportModal from "@/components/ImportModal/index.vue";
import {randomSelectByNum} from '@/api/train/questionDatabase'
import {listUserWithoutAdmin} from "@/api/system/user";
import {addTrain, getTrain, getTrainResult} from "@/api/train/train";
import {delTarget} from "@/api/train/target";
import DictSelect from "@/views/audit/components/form/DictSelect.vue";


export default {
  name: 'TrainDetail',
  components: {DictSelect, CardTable, ImportModal, DatePicker, Column, DatabaseDialog, QuestionDatabaseDialog},
  dicts: ['train_question_type', 'training_category', 'train_status', 'train_whether_to_assess', 'train_target_train_complete_flag','train_exam_status'],
  data() {
    // 培训对象校验规则
    var targetsValidate = (rule, value, callback) => {
      if (this.trainTargetsList.length === 0) {
        callback(new Error(`${this.$t('trainList.trainingTargets')}${this.$t('common.requiredMsg')}`));
      } else {
        callback();
      }
    };
    // 培训试题校验规则
    var quesValidate = (rule, value, callback) => {
      if (this.questionList.length === 0) {
        callback(new Error(`${this.$t('trainList.listOfTestQuestions')}${this.$t('common.requiredMsg')}`));
      } else {
        callback();
      }
    };

    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      targetQueryParams:{},
      fileQueryParams: {},
      questionParams:{},
      trainingTrackingParams:{},

      editableTabsValue: '1',
      loading: false,
      // 弹出层类型
      openType: 'add',
      targetLoading: false,
      submitLoading: false,
      // 表单参数
      form: {},
      // 是否显示 随机选题弹框
      isRandomSelect: false,
      // 手动选题弹框标题
      selectDialogTitle: "",
      // 是否显示 选题弹框
      isSelectBySelf: false,
      // 添加附件弹出层标题
      addTrainFileTitle: "",
      // 是否显示添加附件弹出层
      isAddTrainFile: false,
      // 添加培训对象弹出层
      addTrainTargetsTitle: "",
      // 是否显示添加培训对象弹出层
      isAddTrainTargets: false,
      // 培训类类别
      trainingCategoryList: [],
      // 是否考核： 0:否  1:是
      whetherToAssessList: [],
      // 用户查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      // 所有用户列表
      userList: [],
      // 被选择的用户列表
      userSelectionList: [],
      userSelectionListNow: new Set(),
      // 培训对象列表
      trainTargetsList: [],
      // 角色列表
      allRoleOptions: [],
      // 附件列表数据
      fileList: [],
      // 试题列表
      questionList: [],
      // 试题库弹框
      openQuestionDatabaseDialog: false,
      // 考核方案 列表
      assessmentPlanForm: {},
      // 各题型数量
      questionNumForm: {},
      // 已存在的试题列表
      questionNumList: [],
      checkedRows: [],
      selectUserIdSet: new Set(),
      // 追踪列表
      trackList: [],
    }

  },
  created() {
    this.getDetailInfo()
    this.getTrainTrackInfo()
    this.getUserList();
  },
  computed: {
    // 培训完成率/和完成人数
    getTrainingCompletionRate() {
      // 培训完成人数
      let completeNum = 0
      this.trackList.forEach(item => {
        if (item.trainCompleteFlag === '1') {
          completeNum++
        }
      })
      // 培训完成率
      let rate = this.trackList.length === 0? 0 : (completeNum / this.trackList.length * 100).toFixed(2) + "%";
      return {
        completeNum:completeNum,
        rate: rate
      }
    },
    // 考核完成率/完成人数
    getAssessmentCompletionRate() {
      if(this.form.assessFlag === '0'){
        return {
          completeNum:'-',
          rate: '-'
        }
      }
      // 考核完成人数
      let completeNum = 0
      this.trackList.forEach(item => {
        if (item.assessCompleteFlag !== '0') {
          completeNum++
        }
      })
      // 培训完成率
      let rate = this.trackList.length === 0? 0 : (completeNum / this.trackList.length * 100).toFixed(2) + "%";
      return {
        completeNum:completeNum,
        rate: rate
      }
    },
    // 达标率
    getComplianceRate() {
      if(this.form.assessFlag === '0'){
        return '-'
      }
      let completeNum = 0
      this.trackList.forEach(item => {
        if (item.assessCompleteFlag === '2') {
          completeNum++
        }
      })
      return this.trackList.length === 0 ? 0 : (completeNum / this.trackList.length * 100).toFixed(2) + "%"
    },


    // 总题数
    totalNumberOfQuestions: function () {
      if (this.questionList) {
        return this.questionList.length;
      }
      return 0;
    },
    // 总分数
    totalScore() {
      let totalScore = 0
      if (this.questionList) {
        if (this.questionList.length > 0) {
          this.questionList.forEach(item => {
            totalScore = totalScore + item.score
          })
        }
      }

      return totalScore;
    },
    // 单选题数
    singleChoiceQuestions: function () {
      // 过滤出 单选题
      if (!this.questionList) {
        return 0
      }
      let List = this.questionList.filter(item => item.questionType === '01')
      return List.length;
    },
    // 多选题数
    multipleChoiceQuestions: function () {
      if (!this.questionList) {
        return 0
      }
      // 过滤出 多选题
      let List = this.questionList.filter(item => item.questionType === '02')
      return List.length;
    },
    // 判断题
    trueOrFalseQuestions: function () {
      if (!this.questionList) {
        return 0
      }
      // 过滤出 判断题
      let List = this.questionList.filter(item => item.questionType === '03')
      return List.length;
    },
    // 填空题
    fillInTheBlankQuestions: function () {
      if (!this.questionList) {
        return 0
      }
      // 过滤出 填空题
      let List = this.questionList.filter(item => item.questionType === '04')
      return List.length;
    },
    getRowKey(row) {
      return row.id;
    },

  },

  methods: {

    // 获取培训详细信息
    getDetailInfo() {
      let id = this.$route.params.id;
      getTrain(id).then((res) => {
        console.log("res----------------", res)
        // 考核方案内容
        if (res.data.ttTestPaperDetailList) {
          res.data.ttTestPaperDetailList.forEach(item => {
            item.questionTypeName = this.dict.label.train_question_type[item.questionType];
            item.score = parseInt(item.questionScore)
          })
        }

        this.form.trainName = res.data.trainName;
        this.form.trainType = res.data.trainType;
        this.form.startDate = res.data.startDate;
        this.form.endDate = res.data.endDate;
        this.form.assessFlag = res.data.assessFlag;
        this.form.remark = res.data.remark;

        this.trainTargetsList = res.data.ttTrainTargetList
        this.fileList = res.data.ttTrainFileList

        if(this.form.assessFlag === '1'){
          this.assessmentPlanForm.testPaperName = res.data.ttTestPaperList[0].testPaperName
          // this.assessmentPlanForm.passScore = res.data.ttTestPaperList[0].passScore
          this.$set(this.assessmentPlanForm, 'passScore', parseInt(res.data.ttTestPaperList[0].passScore))
          console.log("passScore", typeof this.assessmentPlanForm.passScore, ":", this.assessmentPlanForm.passScore)

          this.assessmentPlanForm.testRemark = res.data.ttTestPaperList[0].remark
          this.questionList = res.data.ttTestPaperDetailList
        }



      })

    },
    // 获取追踪详细信息
    getTrainTrackInfo() {
      let query = {
        id: this.$route.params.id
      }
      getTrainResult(query).then(res => {
        this.trackList = res.data
        this.trackList.forEach(item => {
          item.assessCompleteFlagName = this.dict.label.train_exam_status[item.assessCompleteFlag];
          item.trainCompleteFlagName = this.dict.label.train_target_train_complete_flag[item.trainCompleteFlag];
        });
      })
    },
    handleMove(row) {
      // 如果已经参加过考核，则不能移除
      if(row.assessCompleteFlag !== '0'){
        return this.$modal.msgError(this.$t('trainList.cannotRemove'))
      }
      this.$modal.confirm(this.$t('common.isDelete')).then(()=>{
        delTarget(row.id).then(()=>{
          this.$modal.msgSuccess(this.$t("common.deleteSuccess"))
          this.getTrainTrackInfo()
        })
      }).catch()

    },
    // 打开 手动选题弹窗
    selectByMyself() {
      this.selectDialogTitle = this.$t('trainList.manualTopicSelection')
      this.isSelectBySelf = true
      // console.log("this.$refs['questionDialog']",this.$refs['questionDialog'])
      this.$nextTick(() => {
        this.$refs['questionDialog'].getQuestList()
      })
    },
    // 获取 选择的题目到列表当中
    submitQuestionList() {
      const selectionList = this.$refs['questionDialog'].selectionList
      if (this.questionList.length > 0) {
        // 判断选择的试题是否都已存在于已选择的列表中
        const allSelectedAlready = selectionList.every(item => this.questionList.some(question => question.id === item.id));
        if (allSelectedAlready) {
          this.$message.error(this.$t('trainList.choiceAgain'));
        } else {
          selectionList.forEach(item => {
            if (!this.questionList.find(ques => ques.id === item.id)) {
              this.questionList.unshift(item);
            }
          });
        }
      } else {
        this.questionList = JSON.parse(JSON.stringify(selectionList));
      }
      this.isSelectBySelf = false;
    },
    // 获取随机选题
    getRandomQuestion() {
      randomSelectByNum(this.questionNumList).then(response => {
        if (response && response.rows) {
          this.questionList = this.questionList.concat(response.rows)
          this.questionList.forEach(item => {
            item.questionTypeName = this.dict.label.train_question_type[item.questionType];
          })
          this.$message.success(this.$t('common.addSuccess'))
        } else {
          this.$message.error(this.$t("trainList.randomSelectError"));
        }
      }).finally(() => {
        this.isRandomSelect = false
      })

    },

    // 随机选题
    randomSelect() {
      this.isRandomSelect = true
      this.questionNumList = this.dict.type.train_question_type.map(item => {
        return {
          questionType: item.value,
          questionTypeName: item.label,
          questionTypeNum: 5
        }
      })

    },
    // 试题删除
    questionDelete(row) {
      this.questionList.splice(this.questionList.indexOf(row), 1);
    },
    // 文件删除
    fileDelete(row) {
      this.fileList.splice(this.fileList.indexOf(row), 1);
    },
    moveItem(row, direction, list) {
      const index = list.indexOf(row);
      if (index !== -1) {
        const newIndex = direction === 'moveUp' ? index - 1 : index + 1;
        if (newIndex >= 0 && newIndex < list.length) {
          // 将元素从当前位置移除 并获取这个元素
          const item = list.splice(index, 1)[0];
          // 在新位置插入元素
          list.splice(newIndex, 0, item);
        }
      } else {
        // 不应走到此处
        console.info("文件列表中没有该条数据")
      }
    },
    // 获取人员列表
    getUserList() {
      // console.log("2",bool)
      const {createTime, ...params} = this.userQueryParams;
      listUserWithoutAdmin(params).then((response) => {
        this.userList = response.rows;
        this.userQueryParams.total = response.total
        this.userSelectionList = this.userSelectionListNow
        // 跨页回显
        this.userList.forEach((row) => {
          const bool = this.selectUserIdSet.has(row.userId)
          if (bool) {
            this.$nextTick(() => {
              this.$refs['userTable'].$refs['table'].toggleRowSelection(row, true)
            })
          }
        })
        this.$forceUpdate()
      })
    },
    // 被选择的用户列表
    handleUserSelectionChange(selection) {
      selection.forEach(item => {
        this.selectUserIdSet.add(item.userId)
        this.userSelectionListNow.add(item)
      })
    },
    // 添加培训对象弹窗
    addTrainTargetsDialog() {
      this.addTrainTargetsTitle = this.$t('trainList.addObject');
      this.isAddTrainTargets = true;
    },
    // 人员添加表单
    submitTrainTargetsForm() {
      const myArray = Array.from(this.userSelectionListNow);
      if (this.trainTargetsList.length > 0) {
        // 判断选择的用户列表是否都已存在于已选择的列表中
        const allSelectedAlready = myArray.every(item => this.trainTargetsList.some(target => target.userId === item.userId));
        if (allSelectedAlready) {
          this.$message.error(this.$t('trainList.choiceAgain'));
        } else {
          this.userSelectionList.forEach(item => {
            if (!this.trainTargetsList.find(target => target.userId === item.userId)) {
              this.trainTargetsList.unshift(item);
            }
          });
        }
      } else {
        this.trainTargetsList = JSON.parse(JSON.stringify(myArray));
      }
      this.isAddTrainTargets = false;
    },
    // 删除培训对象
    deleteTrainTarget(row) {
      this.selectUserIdSet.delete(item => item.userId === row.id);
      this.trainTargetsList.splice(this.trainTargetsList.indexOf(row), 1);
    },
    // 添加附件弹窗
    addTrainFileDialog() {
      this.addTrainFileTitle = this.$t('trainList.addFile');
      this.isAddTrainFile = true;
    },

    // 试卷预览
    preview() {
      // 试题参数
      if (!this.questionList) {
        return this.$modal.msgError(this.$t("trainList.previewError"));
      }
      if (this.questionList.length > 0) {
        let query = {
          data: this.questionList,// 将数组转换为字符串
          assessmentPlanForm: this.assessmentPlanForm
        };
        this.$router.push({
          path: "/train/trainlist/detail/PreviewTest",
          query: query
        });
      } else {
        this.$modal.msgError(this.$t("trainList.previewError"));
      }


    },
    /** 培训新增 提交按钮 */
    async submitForm() {
      let valid1 = false;
      let valid2 = false;

      try {
        const [result1, result2] = await Promise.all([
          this.$refs.form.validate(),
          this.$refs.assessmentPlanForm.validate(),
        ])
        valid1 = result1
        valid2 = result2
      } catch (e) {
        return
      }
      if (!valid1 || !valid2) {
        return
      }
      try {
        // 培训方案新增
        this.pageLoading = true;
        const userIdList = this.trainTargetsList.map(item => item.userId);
        const fileIdList = this.fileList.map(item => item.id);
        // const questionIdList = this.questionList.map(item => item.id)
        // 参数
        const query = {
          ...this.form,
          userIdList,
          fileIdList,
          ...this.assessmentPlanForm,
          questionList: this.questionList,
        };
        await addTrain(query);


        this.$message.success(this.$t('common.addSuccess'));
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.replace("/train/trainlist/")
      } catch (error) {
        console.error(error);
      } finally {

        this.pageLoading = false;
      }
    },

    // 文件选择提交
    submitFileForm() {
      const fileSelectionList = this.$refs.Database.selectionList
      this.fileList = JSON.parse(JSON.stringify(fileSelectionList))
      this.isAddTrainFile = false;
    },
    assessCancel() {
      this.assessOpen = false;
    },
    handleQuery() {

    },
    resetQuery() {

    },
    // 返回培训列表页面
    cancel() {
      this.$tab.closePage()
      // this.$store.dispatch('tagsView/delView', this.$route)
      // this.$router.replace("/train/trainlist/")
    }
  }
}

</script>
<style scoped>
.card-Table {
  box-shadow: none;
}
.account-container {
  padding: 16px 1vw;

  .account-title {
    font-family: Arial, Arial;
    font-weight: bold;
    font-size: 18px;
    line-height: 21px;
  }

  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .button-group {
    display: flex;
  }

  .content {
    width: 100%;
    display: flex;

    & > div {
      align-self: stretch;
    }

    .card {
      background: #FFFFFF;
      box-shadow: 0px 2px 10px 0px #CED6DD;
      border-radius: 6px;
      padding: 20px;
    }

    .card-full {
      width: 97.6vw;
    }

  }

}


</style>
