<template>
  <div class="account-container" v-loading="loading">
    <div class="top" style="margin-bottom: 24px">
      <div class="account-title">{{ this.$t('trainList.addTrain') }}</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 v-if="openType !== 'view'" @click="cancel" icon="el-icon-remove-outline">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button v-if="openType === 'view'" icon="el-icon-remove-outline" plain size="mini" @click="cancel">
          {{ $t('common.back') }}
        </el-button>
      </div>
    </div>
<!--    <div class="content">-->
<!--      <div class="card card-full">-->
        <el-tabs type="border-card">
          <!--    培训方案-->
          <el-tab-pane :label="$t('trainList.trainingProgram')">
            <el-form ref="form" :model="form" label-width="120px" :rules="rules" style="margin-top: 20px">
              <el-row :gutter="20">
                <el-col :span="6">
                  <Input prop="trainName" required :label="$t('trainList.trainingName')" width="100%"/>
                </el-col>
                <el-col :span="6">
                  <Select required prop="trainType" :data="dict.type.training_category"
                          :label="$t('trainList.trainingCategory')"
                          :styleObj=" { width: '100%' }"></Select>
                </el-col>
                <el-col :span="6">
                  <DatePicker :pickerBeginOption="sPickerOptions" required prop="startDate"
                              :label="$t('trainList.startTime')" width="100%"/>
                </el-col>
                <el-col :span="6">
                  <DatePicker :pickerBeginOption="ePickerOptions" required prop="endDate"
                              :label="$t('trainList.endTime')" width="100%"/>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="6">
                  <Select required 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 ref="trainingTargetsItem" :label="$t('trainList.trainingTargets')" prop="trainingTargets">
                    <el-button :disabled="openType === 'view'" @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 :label="$t('user.nick')" prop="nickName"/>
                <Column :label="$t('user.role')" prop="roleId">
                  <template #default="{ row }">
                    <span>{{ row.roleNames }}</span>
                  </template>
                </Column>
                <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>

                <el-table-column v-show="openType !== 'view'" :label="$t('common.operate')" align="center">
                  <template #default="{ row }">
                    <el-button v-hasPermi="['train:list:delete']" icon="el-icon-delete" size="mini"
                               type="text" @click="deleteTrainTarget(row)">{{ $t('common.delete') }}
                    </el-button>
                  </template>
                </el-table-column>
              </card-table>
              <el-row :gutter="20">
                <el-col :span="12">
                  <Input prop="remark" type="textarea" :maxlength="500" :label="$t('trainList.remarks')" width="100%"
                         style="margin-top: 20px"/>
                </el-col>
              </el-row>
              <el-form-item :label="$t('trainList.fileList')">
                <el-button :disabled="openType === 'view'" @click="addTrainFileDialog" type="primary" size="mini">{{
                    $t('trainList.addFile')
                  }}
                </el-button>
                <div style="font-size: 12px">
                  <i class="el-icon-warning-outline" style="color: red"></i>
                  {{ $t('trainList.fileLimit', { limit: SUPPORT_FILE_FORMAT }) }}
                </div>
              </el-form-item>
              <!--            附件列表-->
              <card-table :modalData="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>
                <el-table-column v-show="openType !== 'view'" :label="$t('common.operate')" align="center">
                  <template #default="{ row }">
                    <el-button v-hasPermi="['train:list:delete']" icon="el-icon-delete" size="mini"
                               type="text" @click="fileDelete(row)">{{ $t('common.delete') }}
                    </el-button>
                    <el-button v-show="fileList.indexOf(row)>0" v-hasPermi="['train:list:delete']" icon="el-icon-delete"
                               size="mini"
                               type="text" @click="moveItem(row,'moveUp',fileList)">{{ $t('trainList.moveUp') }}
                    </el-button>
                    <el-button v-show="fileList.indexOf(row) < fileList.length -1" v-hasPermi="['train:list:delete']"
                               icon="el-icon-delete" size="mini"
                               type="text" @click="moveItem(row,'moveDown',fileList)">{{ $t('trainList.moveDown') }}
                    </el-button>
                  </template>
                </el-table-column>
              </card-table>

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

          <!--    考核方案-->
          <el-tab-pane v-if="form.assessFlag === '1'" :label="$t('trainList.assessmentPlan')" style="margin-top: 20px">
            <el-form ref="assessmentPlanForm" @validate="assessFormValidate" :rules="assessRules" :model="assessmentPlanForm" label-width="120px">
              <el-row :gutter="20">
                <el-col :span="6">
                  <Input required 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" v-model="assessmentPlanForm.passScore" :min="0" :max="totalScore" :precision="0"/>
                  </el-form-item>
<!--                  <input prop="passScore" :label="$t('trainList.passScore')"></input>-->
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <Input prop="testRemark" type="textarea" :maxlength="500" :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"  size="mini" @click="selectByMyself"> {{ $t('trainList.manualTopicSelection') }}</el-button>
                <el-button icon="el-icon-refresh"  size="mini" @click="randomSelect">{{ $t('trainList.randomSelectionOfTopics') }}</el-button>
                <ImportModal :title="$t('common.import')" icon="el-icon-upload2" fileName="培训试题导入模板"
                             :table-type="6" @importSuccess="importSuccess"
                             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" @blur="changeScore(row)" v-model="row.score" :min="0" :max="100" :precision="0"/>
                  </template>
                </el-table-column>
                <el-table-column v-show="openType !== 'view'" :label="$t('common.operate')" align="center">
                  <template #default="{ row }">
                    <el-button v-hasPermi="['train:list:delete']" icon="el-icon-delete" size="mini"
                               type="text" @click="questionDelete(row)">{{ $t('common.delete') }}
                    </el-button>
                    <el-button v-show="questionList.indexOf(row)>0" v-hasPermi="['train:list:delete']"
                               icon="el-icon-top"
                               size="mini"
                               type="text" @click="moveItem(row,'moveUp',questionList)">{{ $t('trainList.moveUp') }}
                    </el-button>
                    <el-button v-show="questionList.indexOf(row) < questionList.length -1"
                               v-hasPermi="['train:list:delete']"
                               icon="el-icon-bottom" size="mini"
                               type="text" @click="moveItem(row,'moveDown',questionList)">{{ $t('trainList.moveDown') }}
                    </el-button>
                  </template>
                </el-table-column>
              </card-table>
            </el-form>
          </el-tab-pane>
        </el-tabs>
<!--      </div>-->
<!--    </div>-->

    <!--    添加培训对象弹出层-->、
    <el-dialog :close-on-click-modal="false" :title="addTrainTargetsTitle" :visible.sync="isAddTrainTargets"
               append-to-body class="dialog-style"
               custom-class="edit-dialog" width="50vw">
      <card-table-zy :row-key="getRowKey" ref="userTable" :modalData="userList" labelWidth="120px"
                     :searchParams="userQueryParams"
                     @pagination="getUserList"
                     :loading="targetLoading" :tableSearch="true"
                     :reserve-selection="true" @cancel="handleUserCancel" @select="handleUserSelect"
                     @columnSearch="getUserList" @resetList="resetUserQuery"
                     :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"/>-->
        <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('common.operate')" :min-width="200" :showSearch="true" align="center" fixed="right"
                search-type="operate"/>
      </card-table-zy>
      <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" @close="resetQuestionQuery">
      <card-table-zy ref="tableQuestion" :del-prop="['createTime']"
                     :loading="questionLoading"
                     :modalData="quesList" :searchParams="questionQueryParams" :tableSearch="true"
                     labelWidth="120px" @cancel="handleQuestionCancel"
                     @columnSearch="handleQuestionQuery" @pagination="getQuestList"
                     @resetList="resetQuestionQuery" @select="handleQuestionSelection">
        <template #default="{ list }">
          <el-table-column align="center" type="selection" width="50"/>
          <el-table-column align="center" label="No" type="index" width="50"/>
          <!--题目名称-->
          <Column :label="$t('question.questionContext')" :search-params="questionQueryParams" :show-search="true"
                  prop="questionContext"
                  show-overflow-tooltip/>
          <Column :label="$t('question.questionType')" :search-dict="dict.type.train_question_type"
                  :search-params="questionQueryParams"
                  :show-search="true"
                  prop="questionType" search-type="select" select-prop="questionTypes" selectMore/>

          <Column :label="$t('question.score')" prop="score" show-overflow-tooltip/>
          <!--标准答案-->
          <Column :label="$t('question.correctAnswer')" prop="correctAnswer" show-overflow-tooltip/>

          <Column :label="$t('common.operate')" :min-width="200" :showSearch="true" align="center" fixed="right"
                  search-type="operate"/>
        </template>
      </card-table-zy>

      <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" style="margin-right: 24PX">{{ $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">
      <card-table  style="width: 100%" ref="tableQuestion" :del-prop="['createTime']"
                   :loading="questionLoading"
                   :modalData="questionNumList" :searchParams="randomQuestionQueryParams" :tableSearch="false"
                   labelWidth="120px" @cancel="handleQuestionCancel"
                   @resetList="resetQuestionQuery" @select="handleQuestionSelection">
        <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" @blur="handleQuestionNumBlur(scope.row)" style="width: 90%;" v-model="scope.row.questionTypeNum" :min="0" :max="99"/>
          </template>
        </el-table-column>

      </card-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" style="margin-right: 24PX">{{ $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 CardTableZy from "@/components/element/table/CardTableZy.vue";
import ImportModal from "@/components/ImportModal/index.vue";
import {randomSelect, randomSelectByNum} from '@/api/train/questionDatabase'
import {getUser, listUserWithoutAdmin} from "@/api/system/user";
import {addTrain, getTrain, updateTrain} from "@/api/train/train";
import DictSelect from "@/views/audit/components/form/DictSelect.vue";
import {getFile} from "@/api/train/file";
import {questionPage} from "@/api/train/database";
import DatePickerRange from "@/components/element/form/items/DatePickerRange.vue";
import {SUPPORT_FILE_FORMAT} from '@/utils/fileFormart'


export default {
  name: 'AddTrain',
  components: {
    DatePickerRange,
    DictSelect,
    CardTable,
    ImportModal,
    DatePicker,
    Column,
    DatabaseDialog,
    QuestionDatabaseDialog,
    CardTableZy
  },
  dicts: ['train_question_type', 'training_category', 'train_status', 'train_whether_to_assess'],
  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();
      }
    };
    var checkScore = (rule, value, callback) => {
      // if (!value) {
      //   return callback(new Error(`${this.$t('trainList.passScore')}${this.$t('common.requiredMsg')}`));
      // }
      if(this.questionList.length === 0){
        return callback(new Error(`${this.$t('trainList.scoreTimeError')}`));
      }
      if(value < 0 || value > this.totalScore){
        return callback(new Error(`${this.$t('trainList.passScore')}${this.$t('trainList.scoreError')}`));
      }else {
        callback();
      }
    };
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      targetQueryParams: {},
      fileQueryParams: {},
      questionParams: {},

      sPickerOptions: {
        disabledDate: (date) => {
          if (this.form && this.form.endDate) {
            return date > new Date(this.form.endDate);
          }
          return false;
        },
      },
      ePickerOptions: {
        disabledDate: (date) => {
          if (this.form && this.form.startDate && new Date(this.form.startDate) > new Date()) {
            let startDate = new Date(this.form.startDate).setHours(0, 0, 0, 0);
            return date < new Date(startDate);
          }
          return date && date < new Date().setHours(0, 0, 0, 0);
        }
      },
      loading: false,
      questionLoading: false,
      // 弹出层类型
      openType: 'add',
      targetLoading: false,
      submitLoading: false,
      // 表单参数
      form: {
        assessFlag: '1',
        // 日期范围
        dateRange: [],
      },
      // 是否显示 随机选题弹框
      isRandomSelect: false,
      // 手动选题弹框标题
      selectDialogTitle: "",
      // 是否显示 选题弹框
      isSelectBySelf: false,
      // 添加附件弹出层标题
      addTrainFileTitle: "",
      // 是否显示添加附件弹出层
      isAddTrainFile: false,
      // 添加培训对象弹出层
      addTrainTargetsTitle: "",
      // 是否显示添加培训对象弹出层
      isAddTrainTargets: false,
      // 培训类类别
      trainingCategoryList: [],
      // 是否考核： 0:否  1:是
      whetherToAssessList: [],
      // 用户查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      // 所有用户列表
      userList: [],
      // 被选择的用户列表
      userSelectionListNowSet: new Set(),
      selectUserIdSet: new Set(),
      // 培训对象列表
      trainTargetsList: [],
      // 角色列表
      allRoleOptions: [],
      // 附件列表数据
      fileList: [],
      rules: {
        trainingTargets: [
          {required: true, validator: targetsValidate, trigger: 'blur'}
        ]
      },
      assessRules: {
        listOfTestQuestions: [
          {required: true, validator: quesValidate, trigger: 'blur'}
        ],
        passScore: [
          {
            required: true,
            message: `${this.$t('trainList.passScore')}${this.$t('common.requiredMsg')}`,
            trigger: 'blur'
          },
          { validator: checkScore, trigger: 'blur'}
        ]
      },

      // 试题库弹框
      openQuestionDatabaseDialog: false,
      // 考核方案 列表
      assessmentPlanForm: {
        passScore:0
      },


      questionQueryParams: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        questionContext: null,
        questionType: null,
        score: null,
        status: null

      },
      // 随机选题题数列表
      questionNumList: [],
      randomQuestionQueryParams:{
        total: 0,
      },
      // 已选择的问题id
      selectQuestionIdSet: new Set(),
      // 已选择的问题
      questionSelectList: new Set(),
      // 试题列表
      questionList: [],

      // 已选择的数据
      selectionList: [],
      // 分页查询出的问题列表
      quesList: [],


    }

  },
  created() {
    this.getUserList();

    if (this.$route.query.id) {
      this.getDetailInfo()
    }

  },
  computed: {
    SUPPORT_FILE_FORMAT() {
      return Array.from(SUPPORT_FILE_FORMAT).join(',')
    },

    getRowKey(row) {
      return row.id;
    },
    // 总题数
    totalNumberOfQuestions: function () {
      if (!this.questionList) {
        return 0;
      }
      return this.questionList.length;
    },
    // 总分数
    totalScore: function () {
      if (!this.questionList) {
        return 0;
      }
      let totalScore = 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;
    },
  },

  methods: {
    // 控制数字框不会出现空值，如果为空默认为0
    handleQuestionNumBlur(row){
      if(!row.questionTypeNum){
        row.questionTypeNum = 0
      }
    },
    assessFormValidate() {
      setTimeout(item =>{
        this.$refs.assessmentPlanForm && this.$refs.assessmentPlanForm.clearValidate()
      },5000)
    },
    handleQuery() {
    },
    getList() {
    },
    resetQuery() {
    },
    /** 培训新增 提交按钮 */
    async submitForm() {
      let result1 = false;
      let result2 = true;
      await this.$refs.form.validate((valid) => {result1 = valid});
      this.form.assessFlag === '1' ? await this.$refs.assessmentPlanForm.validate(valid => {
        result2 = valid}) : result2 = true
      if (!result1) {
        this.$modal.msgError(this.$t('trainList.trainingProgram') + this.$t('trainList.requiredError'));
      }
      setTimeout(() => {
        if (!result2) {
          this.$modal.msgError(this.$t('trainList.assessmentPlan') + this.$t('trainList.requiredError'));
        }
      }, 50);
      if (!result1 || !result2) {
        return console.log("!valid1:", !result1, ",", "!valid2:", !result2)
      }

      if (this.$route.query.id && this.$route.query.type !== 'addAgain') {
        // 编辑
        try {
          this.pageLoading = true;
          const userIdList = this.trainTargetsList.map(item => {
            return item.userId ? item.userId : item.targetPersonId
          });

          const fileIdList = this.fileList.map(item => {
            return item.fileId ? item.fileId : item.id
          });

          this.questionList.forEach(item => {
            item.questionId ? item.id = item.questionId : ''
          })
          console.log("this.questionList", this.questionList)
          // const questionIdList = this.questionList.map(item => item.id)
          // 参数
          let query = {
            ...this.form,
            userIdList,
            fileIdList,
          };
          if (this.form.assessFlag === '1') {
            query = {
              ...query,
              ...this.assessmentPlanForm,
              questionList: this.questionList,
            };
          }
          await updateTrain(query);

          this.$message.success(this.$t('common.editSuccess'));
          await this.$tab.closePage()
          // this.$store.dispatch('tagsView/delView', this.$route)
          // this.$router.replace("/train/trainlist/")
        } catch (error) {
          console.error(error);
        } finally {
          this.pageLoading = false;
        }
      } else {
        // 新增
        try {
          // 判断是否所有题目都是激活的，如果不是则提示
          let bool = this.questionList.every(item => item.status === '0')
          // let isDelFlag = this.questionList.every(item => item.delFlag === '0')
          if(!bool){
            return this.$message.error(this.$t('trainList.questionStatusError'))
          }
          // if(isDelFlag){
          //   return this.$message.error(this.$t('trainList.questionDelFlagError'))
          // }
          // 培训方案新增
          this.pageLoading = true;
          const userIdList = this.trainTargetsList.map(item => {
            if (item.targetPersonId) {
              return item.targetPersonId
            } else {
              return item.userId
            }
          });
          const fileIdList = this.fileList.map(item => {
            if (item.fileId) {
              return item.fileId
            } else return item.id
          });
          this.questionList.forEach(item => {
            if (item.questionId) {
              item.id = item.questionId
            }
          })

          // 参数
          let query = {
            ...this.form,
            userIdList,
            fileIdList,
          };
          if (this.form.assessFlag === '1') {
            query = {
              ...query,
              ...this.assessmentPlanForm,
              questionList: this.questionList,
            };
          }
          await addTrain(query);

          this.$message.success(this.$t('common.addSuccess'));
          await this.$tab.closePage()
          // this.$store.dispatch('tagsView/delView', this.$route)
          // this.$router.replace("/train/trainlist/")
        } catch (error) {
          console.error(error);
        } finally {
          this.pageLoading = false;
        }
      }
    },
    getDetailInfo() {
      let id = this.$route.query.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.id = res.data.id;
        this.form.trainName = res.data.trainName;
        this.form.trainType = res.data.trainType;
        if (this.$route.query.id && this.$route.query.type === 'addAgain'){
          this.$set(this.form, 'startDate', null);
          this.$set(this.form, 'endDate', null);
        }else{
          this.form.startDate = res.data.startDate + " 00:00:00";
          this.form.endDate = res.data.endDate + " 23:59:59";
        }
        this.form.assessFlag = res.data.assessFlag;
        this.form.updateTime = res.data.updateTime;
        this.form.remark = res.data.remark;
        console.log("this.form", this.form)
        this.trainTargetsList = res.data.ttTrainTargetList
        // 已存在培训对象数据放入回显
        this.trainTargetsList.forEach(item => {
          this.selectUserIdSet.add(item.targetPersonId)
        })

        this.fileList = res.data.ttTrainFileList
        // 有考核才有相关数据
        if (this.form.assessFlag === '1') {
          this.assessmentPlanForm.testPaperName = res.data.ttTestPaperList[0].testPaperName
          this.$set(this.assessmentPlanForm, 'passScore', parseInt(res.data.ttTestPaperList[0].passScore))

          this.assessmentPlanForm.testRemark = res.data.ttTestPaperList[0].remark
          this.questionList = res.data.ttTestPaperDetailList
          // 已存在问题数据放入回显
          this.questionList.forEach(item => {
            this.selectQuestionIdSet.add(item.questionId)
          })
        }


      })

    },
    /** 搜索按钮操作 */
    handleQuestionQuery() {
      this.questionQueryParams.pageNum = 1
      this.getQuestList()
    },

    /** 获取问题列表*/
    async getQuestList() {
      this.questionLoading = true
      try {
        const {createTime, updateTime, questionType, ...p} = this.questionQueryParams
        p.status = '0'
        const response = await questionPage(p)
        this.quesList = response.rows
        this.quesList.forEach(item => {
          item.questionTypeName = this.dict.label.train_question_type[item.questionType];
        })
        this.questionQueryParams.total = response.total
        // 跨页回显
        this.quesList.forEach((row) => {
          const bool = this.selectQuestionIdSet.has(row.id)
          if (bool) {
            this.$nextTick(() => {
              this.$refs['tableQuestion'].$refs['table'].toggleRowSelection(row, true)
              const myArray = Array.from(this.questionSelectList)
              const hasItem = myArray.some(item => item.id === row.id)
              if (!hasItem) {
                this.questionSelectList.add(row)
              }
            })
          }
        })
        this.$forceUpdate()
      } finally {
        this.questionLoading = false
      }
    },

    /** 重置按钮操作 */
    resetQuestionQuery() {
      this.questionQueryParams = {}
      this.handleQuestionQuery()
    },

    handleQuestionSelection(rows) {
      rows.forEach(row => {
        if (!this.selectQuestionIdSet.has(row.id)) {
          this.selectQuestionIdSet.add(row.id)
          this.questionSelectList.add(row)
        }
      })
    },

    handleQuestionCancel(rows) {
      rows.forEach(row => {
        this.questionSelectList.forEach(item => {
          if (item.id === row.id) {
            this.selectQuestionIdSet.delete(item.id);
            this.questionSelectList.delete(item);
          }
        });
      })

    },
    // 打开 手动选题弹窗
    selectByMyself() {
      this.selectDialogTitle = this.$t('trainList.manualTopicSelection')
      this.isSelectBySelf = true
      this.$nextTick(() => {
        this.getQuestList()
      })
    },
    // 获取 选择的题目到列表当中
    submitQuestionList() {
      const myArray = Array.from(this.questionSelectList)
      if (myArray.length === 0) {
        this.$message.error(this.$t('trainList.choiceQuestionIsNullError'))
        return console.log("myArray.length === 0")
      }
      if (this.questionList.length > 0) {
        // 判断选择的试题是否都已存在于已选择的列表中
        const allSelectedAlready = myArray.every(item => this.questionList.some(question => {
          if (question.questionId) {
            return item.id === question.questionId
          } else {
            return item.id === question.id
          }
        }));
        if (allSelectedAlready) {
          this.$message.error(this.$t('trainList.choiceAgain'));
        } else {
          this.questionSelectList.forEach(item => {
            if (!this.questionList.find(ques => {
              if (ques.questionId) {
                return ques.questionId === item.id
              } else {
                return ques.id === item.id
              }
            })) {
              this.questionList.unshift(item);
            }
          });
        }
      } else {
        this.questionList = [...this.questionSelectList]
      }
      this.isSelectBySelf = false;
    },
    // 获取随机选题
    getRandomQuestion() {
      // 获取对相同类型题目已选择的题目id，以免随机选题重复获取
      this.questionList.forEach(item => {
        const sameTypeQues = this.questionNumList.find(ques => {
          return item.questionType === ques.questionType;
        });

        if (sameTypeQues) {
          if (!sameTypeQues.existIds) {
            sameTypeQues.existIds = [];
          }

          const id = item.questionId ? item.questionId : item.id;
          sameTypeQues.existIds.push(id);
        }
      });
      randomSelectByNum(this.questionNumList).then(response => {
        if (response && response.rows) {
          this.questionList = response.rows.concat(this.questionList)
          this.questionList.forEach(item => {
            item.questionTypeName = this.dict.label.train_question_type[item.questionType];
          })

          response.rows.forEach(row => {
            this.selectQuestionIdSet.add(row.id)
            this.questionSelectList.add(row)
          })

          this.$message.success(this.$t('common.addSuccess'))
        } else {
          this.$message.error(this.$t("trainList.randomSelectError"));
        }
      }).finally(() => {
        this.isRandomSelect = false
      })
    },
    // 导入试题
    importSuccess(successData) {
      const importList = successData.data.successList
      this.questionList = importList.concat(this.questionList)
      this.questionList.forEach(item => {
        item.questionTypeName = this.dict.label.train_question_type[item.questionType];
      })
      importList.forEach(item => {
        this.selectQuestionIdSet.add(item.id)
      })


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

    },
    changeScore(row){
      if(!row.score){
        row.score = 0
      }
    },
    // 试题删除
    questionDelete(row) {
      this.questionList.splice(this.questionList.indexOf(row), 1);

      const ids = this.questionList.map(item => {
        if (item.questionId) {
          return item.questionId
        } else {
          return item.id
        }
      })
      this.selectQuestionIdSet = new Set(ids)
      this.questionSelectList.forEach(item => {
        if (row.questionId && item.id === row.questionId) {
          this.questionSelectList.delete(item)
        } else if (!row.questionId && item.id === row.id) {
          this.questionSelectList.delete(item)
        }
      })
    },

// 获取人员列表
    getUserList() {
      this.targetLoading = true;
      const {createTime, ...params} = this.userQueryParams;
      listUserWithoutAdmin(params).then((response) => {
        this.userList = response.rows;
        this.userQueryParams.total = response.total
        // this.userSelectionList = this.userSelectionListNowSet
        // 跨页回显
        this.userList.forEach((row) => {
          const bool = this.selectUserIdSet.has(row.userId)
          if (bool) {
            this.$nextTick(() => {
              this.$refs['userTable'].$refs['table'].toggleRowSelection(row, true)
              const userSelectionArray = Array.from(this.userSelectionListNowSet);
              const hasItem = userSelectionArray.some(item => item.userId === row.userId);
              if (!hasItem) {
                this.userSelectionListNowSet.add(row)
              }
            })
          }
        })
        this.getAllRoleOptions()
        this.$forceUpdate()
      }).finally(() => {
        this.targetLoading = false;
      })
    },
    // 权限下拉框
    getAllRoleOptions() {
      getUser().then(response => {
        this.allRoleOptions = response.roles;
      });
    },
    resetUserQuery(){
      this.$set(this.userQueryParams, 'nickName', null)
      this.$set(this.userQueryParams, 'roleId', null)
      this.$set(this.userQueryParams, 'roleName', null)
      this.$set(this.userQueryParams, 'agent', null)
      this.$set(this.userQueryParams, 'agentName', null)
      this.$set(this.userQueryParams, 'nickName', null)
      this.$set(this.userQueryParams, 'nickName', null)
      this.$set(this.userQueryParams, 'nickName', null)
      this.$set(this.userQueryParams, 'pageNum', 1)
      this.getUserList()
    },

    handleUserSelect(rows) {
      console.log("row1231231232113123s", rows)
      rows.forEach(row => {
        if (!this.selectUserIdSet.has(row.userId)) {
          this.selectUserIdSet.add(row.userId)
          this.userSelectionListNowSet.add(row)
        }
      })
    },
    handleUserCancel(rows) {
      rows.forEach(row => {
        this.userSelectionListNowSet.forEach(item => {
          if (item.userId === row.userId) {
            this.selectUserIdSet.delete(row.userId)
            this.userSelectionListNowSet.delete(item);
          }
        });
      })
    },
// 添加培训对象弹窗
    addTrainTargetsDialog() {
      this.addTrainTargetsTitle = this.$t('trainList.addObject');
      this.isAddTrainTargets = true;
      this.$nextTick(() => {
        this.getUserList()
      })
    },
// 111111
// 人员添加表单
    submitTrainTargetsForm() {
      console.log("this.userSelectionListNowSet", this.userSelectionListNowSet)
      const myArray = Array.from(this.userSelectionListNowSet);
      if (myArray.length <= 0) {
        return this.$message.error(this.$t('trainList.choiceTargetIsNullError'))
      }
      if (this.trainTargetsList.length > 0) {
        // 判断选择的用户列表是否都已存在于已选择的列表中
        const allSelectedAlready = myArray.every(item => this.trainTargetsList.some(target => {
          if (target.targetPersonId) {
            return item.userId === target.targetPersonId
          } else {
            return target.userId === item.userId
          }
        }));
        if (allSelectedAlready) {
          this.$message.error(this.$t('trainList.choiceAgain'));
        } else {
          this.userSelectionListNowSet.forEach(item => {
            if (!this.trainTargetsList.find(target => {
              if (target.targetPersonId) {
                return target.targetPersonId === item.userId
              } else {
                return target.userId === item.userId
              }
            })) {
              this.trainTargetsList.unshift(item);
            }
          });
        }
      } else {
        this.trainTargetsList = JSON.parse(JSON.stringify(myArray));
      }
      if(this.trainTargetsList.length > 0) {
        this.$refs.trainingTargetsItem.clearValidate()
      }
      this.isAddTrainTargets = false;
    },
// 删除培训对象
    deleteTrainTarget(row) {
      this.trainTargetsList.splice(this.trainTargetsList.indexOf(row), 1);

      const ids = this.trainTargetsList.map(item => {
        if (item.targetPersonId) {
          return item.targetPersonId
        } else {
          return item.userId
        }
      })
      // 删除列表数据后 选中数据就是列表数据
      this.selectUserIdSet = new Set(ids)
      // 删除列表数据时，也删除选中数据
      this.userSelectionListNowSet.forEach(item => {
        if (row.targetPersonId && item.userId === row.targetPersonId) {
          this.userSelectionListNowSet.delete(item);
        } else if (!row.targetPersonId && item.userId === row.userId) {
          this.userSelectionListNowSet.delete(item);
        }
      });

    },
// 添加附件弹窗
    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) {
        console.log("this.questionList,", this.questionList)
        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"));
      }

    },
// 文件删除
    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("文件列表中没有该条数据")
      }
    },
// 文件选择提交
    submitFileForm() {
      // 对选择的文件格式做限制
      let formatList = Array.from(SUPPORT_FILE_FORMAT).join("|")
      const fileList = this.$refs.Database.selectionList.filter(item => {
        const regexString = `.*\\.(${formatList})$`;
        const reg = new RegExp(regexString, 'i')
        return reg.test(item.fileName)
      })
      if (fileList.length <= 0) {
        console.log(this.$t("trainList.submitFileForm"),SUPPORT_FILE_FORMAT);
        console.log("111",this.$t("trainList.fileTypeError",{ limit: JSON.stringify(Array.from(SUPPORT_FILE_FORMAT).join("、")) }))
        return this.$modal.msgError(this.$t("trainList.fileTypeError",{ limit: Array.from(SUPPORT_FILE_FORMAT).join("、") }).toString());
      }
      this.fileList = JSON.parse(JSON.stringify(fileList))
      this.isAddTrainFile = false;
    },

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

  }
}

</script>
<style scoped>
 ::v-deep .el-dialog__body {
  padding: 0 20px !important;
}
.card-Table {
  box-shadow: none;
  padding: 10px 24px;
}
.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>
