<template>
  <div class="app-container">
    <el-card shadow="always">
      <!-- 表单 -->
      <el-form :model="queryParams" ref="queryForm" size="small" label-width="120px" :rules="rules">
        <el-form-item label="培训主题名称:" prop="trainingName">
          <el-input v-model="queryParams.trainingName" maxlength="40" show-word-limit placeholder="请输入培训主题名称" clearable
                    style="width: 400px" v-no-whitespace
          />
        </el-form-item>
        <el-form-item label="培训内容:" prop="trainingContent">
          <el-input v-model="queryParams.trainingContent" maxlength="1000" show-word-limit v-no-whitespace placeholder="请输入培训内容" clearable style="width: 400px" />
        </el-form-item>
        <el-form-item label="培训地点:" prop="trainingPlace">
          <el-input v-model="queryParams.trainingPlace" maxlength="500" show-word-limit v-no-whitespace placeholder="请输入培训地点" clearable style="width: 400px" />
        </el-form-item>
        <el-form-item label="培训级别:" prop="trainingLevel">
          <el-select v-model="queryParams.trainingLevel" placeholder="请选择培训级别" clearable style="width: 400px">
            <el-option
              v-for="dict in dict.type.sys_train_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="培训时间:" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            clearable
            style="width: 400px"
            format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="培训时长:" prop="trainingDuration">
          <el-input v-model="queryParams.trainingDuration" placeholder="请输入培训时长" clearable
                    style="width: 400px" v-no-whitespace
          />
          分钟
        </el-form-item>
        <el-form-item label="主讲人:" prop="lecturer">
          <el-input v-model="queryParams.lecturer" maxlength="10" show-word-limit v-no-whitespace placeholder="请输入主讲人" clearable style="width: 400px" />
        </el-form-item>
        <el-form-item label="培训对象:" prop="studyObject">
          <el-select
            v-model="queryParams.studyObject"
            placeholder="请选择学习对象"
            style="width: 200px"
            clearable
            filterable
            @change="changeTaskFor"
          >
            <el-option v-for="item in trainObjOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- 外委: 按钮 -->
        <el-form-item
          label="外委"
          prop="external"
          class="red-label"
          v-if="queryParams.studyObject == '2'"
        >
          <el-button type="primary" size="mini" @click="handleSelectPerson(1)">选择人员</el-button>
          <!-- <span class="mr-lf">已选择{{ externalPerson.length }}</span> -->
          <span class="tip-text">点击选择人员，可添加人员，可对现有学习人员进行编辑；</span>
        </el-form-item>
        <!-- 内部: 按钮 -->
        <el-form-item
          label="内部"
          prop="internal"
          class="red-label"
          v-if="queryParams.studyObject == '1'"
        >
          <el-button type="primary" size="mini" @click="handleSelectPerson(2)">选择人员</el-button>
          <!-- <span class="mr-lf">已选择{{ internalPerson.length }}</span> -->
          <span class="tip-text">点击选择人员，可添加人员，可对现有学习人员进行编辑；</span>
        </el-form-item>
        <el-form-item label="培训人数:" prop="trainingNumber">
          <el-input v-model="queryParams.trainingNumber" placeholder="培训人数" v-no-whitespace disabled style="width: 400px" />
        </el-form-item>
        <el-form-item label="签到二维码:" prop="qrCodeUrl">
          <vue-qr
            ref="qrCode"
            :text="queryParams.qrCodeUuid"
            :logoSrc="logoSrc"
            :color-dark="randomColor"
            width="100"
            height="100"
          ></vue-qr>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" size="mini" @click="handleAddExam" :disabled="examTableData.length > 0">添加考试
          </el-button>
        </el-form-item>
        <el-form-item label="考试信息:">
          <el-card :style="{ marginTop: '20px' }">
            <!-- 考试信息 -->
            <div>
              <el-table :data="examTableData" highlight-current-row style="width: 100%">
                <el-table-column type="index" width="55" label="序号" align="center" />
                <el-table-column prop="examPaperName" label="考试名称" align="center" />
                <el-table-column prop="examTemplateName" label="试卷名称" align="center" />
                <el-table-column prop="questionNum" label="试题数" align="center" />
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="mini"
                      icon="el-icon-delete"
                      style="color: #e47470"
                      @click="handleDelete(scope.row)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- <div class="bottom-btn">
              <el-button type="primary" size="mini">确定</el-button>
              <el-button size="mini">取消</el-button>
            </div> -->
          </el-card>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" style="float:right;" @click="onSubmit" v-preventReClick="5000">确定新建</el-button>
        </el-form-item>
      </el-form>
    </el-card>


    <!-- 弹框 -->
    <ExamDialog ref="ExamDialog" />
    <!-- 创建试卷 -->
    <CreateTestPaperDialog ref="CreateTestPaperDialog" />
    <!-- 添加考试 -->
    <ExamDialog ref="ExamDialog" title="添加考试" @getDialogData="getDialogData" />
    <el-dialog title="选择人员" :visible.sync="dialogTransfer" width="35%">
      <treeTransfer
        :title="['所有人员', '已选人员']"
        :from_data="transferData"
        :to_data="toData"
        :defaultProps="{ label: 'label' }"
        height="60vh"
        filter
        openAll
      ></treeTransfer>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleTransfer" v-preventReClick="5000">确 定</el-button>
        <el-button @click="dialogTransfer = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ExamDialog from '@/views/educationalTraining/learningManagement/learningTasks/components/ExamDialog'
import CreateTestPaperDialog
  from '@/views/educationalTraining/learningManagement/learningTasks/components/CreateTestPaperDialog'
import treeTransfer from 'el-tree-transfer'
import VueQr from 'vue-qr'
import {
  addTrainingTask,
  editTrainingTask,
  getPersonTreeByType, getTrainingTaskDetail
} from '@/api/educationalTraining/resourceAdministration'
import { StrUtil } from '@/utils/StrUtil'
import GeneralDialog from '@/views/educationalTraining/learningManagement/learningTasks/components/GeneralDialog.vue'

export default {
  components: { GeneralDialog, ExamDialog, CreateTestPaperDialog, treeTransfer, VueQr },
  dicts: ['sys_train_level', 'sys_edu_type'],
  data() {
    return {
      dialogTransfer: false,
      isLoading: false,
      showSearch: true,
      logoSrc: '',
      randomColor: 'black',
      trainId: '', //任务id-编辑时传入
      queryParams: {
        qrCodeUuid: '', // 二维码uuid
        trainingName: '', // 培训主题名称
        trainingContent: '', // 培训内容
        trainingPlace: '', // 培训地点
        trainingLevel: '', // 培训级别
        timeRange: [], // 培训时间-范围
        startDate: '', // 培训时间-开始
        endDate: '', // 培训时间-结束
        trainingDuration: '', // 培训时长
        lecturer: '', // 主讲人
        studyObject: '', // 培训对象
        trainingNumber: '', // 培训人数
        qrCodeUrl: '', // 二维码路径
        userIdList: [], // 人员id 多个用逗号隔开
        examId: '', // 试卷id
        examPaperList: [] // 试卷列表
      },
      examTableData: [],
      delExamPaperIds: [], // 删除的考试/练习ids
      // 培训对象-下拉
      trainObjOptions: [
        { label: '内部人员', value: '1' },
        { label: '外委人员', value: '2' }
      ],
      // 穿梭框数据
      transferValue: [],
      // 穿梭框数据
      transferData: [],
      toData: [], // 右侧数据
      // 穿梭框全部数据
      dataList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 外委人员
      externalPerson: [],
      // 内部人员
      internalPerson: [],
      // 已选人员 ids[]
      userIdList: [],
      selectionRows: [], // 选中的行
      // 外委or内部
      personType: 1,
      // 通用弹框-title
      generalDialogTitle: '',
      labelName: '',
      // 通用弹框-columns
      generalDialogColumns: [],
      pickerOptions: {
        disabledDate: this.disabledDate
      },
      // 表单验证
      rules: {
        trainingName: [{ required: true, message: '请输入培训主题名称', trigger: 'blur' }],
        trainingContent: [{ required: true, message: '请输入培训内容', trigger: 'blur' }],
        trainingPlace: [{ required: true, message: '请输入培训地点', trigger: 'blur' }],
        trainingLevel: [{ required: true, message: '请选择培训级别', trigger: 'change' }],
        timeRange: [{ required: true, message: '请选择培训时间', trigger: 'change' }],
        trainingDuration: [{ required: true, message: '请输入培训时长', trigger: 'blur' }, { pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' }, { max: 4, message: '最多输入4位数', trigger: 'blur' }],
        lecturer: [{ required: true, message: '请输入主讲人', trigger: 'blur' }],
        studyObject: [{ required: true, message: '请选择培训对象', trigger: 'change' }]
      },
      currentTreeData: [],
      currentUserList: [],
      qrCodeImage: ''
    }
  },
  created() {
    this.trainId = this.$route.query.trainId || ''
    console.log('🚀 ~ file: Training.vue ~ line 33 ~ Training ~ created ~ this.trainId', this.trainId)
    if (this.trainId) {
      this.getTrainingTaskDetail()
    }
  },
  methods: {
    disabledDate(time) {
      const today = new Date()
      today.setHours(0, 0, 0, 0) // 将时间归零，只比较日期
      return time.getTime() < today.getTime()
    },
    async getTrainingTaskDetail() {
      try {
        const { data } = await getTrainingTaskDetail({ id: this.trainId, taskType: '2' })
        this.queryParams = { ...this.queryParams, ...data }
        this.queryParams.timeRange = [data.startDate, data.endDate]
        console.log('🚀 ~ getDetail ~ this.queryParams:', this.queryParams)
        this.examTableData = data.examPaperList
        this.userIdList = data.userIdList
        this.currentUserList = data.userIdList
        await this.getPersonTreeByType()
      } catch (error) {
      }
    },
    // 查询
    handleQuery() {
      this.$emit('query', this.queryParams)
    },
    // 打开弹框
    async openDialog(type) {
      await (this.dialogTransfer = true)
      this.transferValue = []
      this.getTreeList(this.dataList, [])
      this.getToDataList(this.toData, [])
      if (type === 1) {
      } else {
      }
    },
    // 学习对象
    changeTaskFor(val) {
      // 清除培训人数
      this.queryParams.trainingNumber = ''
      // 清除外委人员
      this.externalPerson = []
      // 清除内部人员
      this.internalPerson = []
      this.transferData = []
      this.toData = []
      this.getPersonTreeByType()
    },
    // 获取人员树
    async getPersonTreeByType() {
      try {
        const params = {
          type: this.queryParams.studyObject == '1' ? '2' : '1',
          proId: ''
        }
        const res = await getPersonTreeByType(params)
        this.transferData = res.data
        this.currentTreeData = res.data
        // this.handleEditToData(this.transferData)
        this.handlePersonTree(this.transferData)
      } catch (error) {
      }
    },
    filterTree(data) {
      return data.reduce((acc, node) => {
        console.log('🚀 ~ filterTree ~ node:', node)
        const { id, parentId, children = [] } = node;
        const pid = parentId == '0' ? 0 : parentId;
        if (this.currentUserList.includes(id)) {
          acc.push({ ...node, pid, children: [] });
        } else {
          const filteredChildren = this.filterTree(children, this.currentUserList);
        //  console.log('🚀 ~ filterTree ~ filteredChildren=============:', JSON.stringify(filteredChildren))
          if (filteredChildren.length > 0) {
            acc.push({ ...node, pid, children: filteredChildren });
          }
        }
        return acc;
      }, []);
    },
    // 编辑时 studyTaskId有值时, 为编辑状态, 根据 userIdList 过滤出已选人员
    handleEditToData(data, parent = null) {
      this.userIdList.forEach(id => {
        data.forEach(item => {
          if (item.id === id) {
            item.selected = true
            this.toData.push(item)
            if (parent && !this.toData.includes(parent)) {
              this.toData.push(parent)
            }
          }
          if (item.children && item.children.length > 0) {
            this.handleEditToData(item.children, item)
          }
        })
      })
      this.toData = _.uniqWith(this.toData, _.isEqual)
    },
    // 递归循环-人员树- pid = parentId
    handlePersonTree(data) {
      data.forEach(item => {
        if (item.parentId == '0') {
          item.pid = Number(item.parentId)
        } else {
          item.pid = item.parentId
        }
        item.label = item.name
        // 如果 item.id 在已选人员ids[]中 则 selected = true
        if (this.userIdList && this.userIdList.includes(item.id)) {
          this.userIdList.find(id => {
            if (id === item.id) {
              item.selected = true
            }
          })
          item.selected = true
        }else{
          item.selected = false
        }

        if (item.children && item.children.length > 0) {
          this.handlePersonTree(item.children)
        }
      })
      console.log('🚀 ~ handlePersonTree ~ data:', data)
    },
    // 选择人员
    handleSelectPerson(val) {
      this.dialogTransfer = true // 打开穿梭框
      this.$nextTick(() => {
        this.getTreeList(this.currentTreeData, [])
        this.toData = this.filterTree(this.currentTreeData);
        // this.getToDataList(this.toData, [])
      })
    },
    // 穿梭框确定
    handleTransfer() {
      this.dataList = this.transferData
      this.userIdList = []
      this.handleTransferData(this.toData)
      this.addUserIds(this.toData)
      this.queryParams.trainingNumber = this.userIdList.length
      this.currentUserList = this.userIdList


      this.dialogTransfer = false
      this.handlePersonTree(this.currentTreeData);

    },
    addUserIds(items) {
      items.forEach(item => {
        console.log('🚀 ~ addUserIds ~ item:', item)
        if (item.userType) {
          this.userIdList.push(item.id)
          console.log('🚀 ~ addUserIds ~ this.userIdList:', this.userIdList)
        }
        if (item.children && item.children.length > 0) {
          this.addUserIds(item.children)
        }
      })
    },
    // 递归循环-toData 给每一项添加 selected = true 然后与 transferData 合并
    handleTransferData(data) {
      data.forEach(item => {
        item.selected = true
        if (item.children && item.children.length > 0) {
          this.handleTransferData(item.children)
        }
      })
    },
    // 添加考试
    handleAddExam() {
      this.$refs.ExamDialog.openDialog(this.examTableData)
    },
    // 从子组件获取添加的课件, 考试, 练习数据
    getDialogData(type, data) {
      this.examTableData = data
    },
    // 删除
    handleDelete(row) {
      // 弹框确认删除
      this.$confirm('是否删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.examTableData = []
          if (row.examPaperId) {
            this.delExamPaperIds.push(row.examPaperId)
          }
        })
        .catch(() => {
          console.log('取消')
        })
    },
    /**
     * 格式化左侧数据
     * @param {array} treeList
     * @param {array} leftFromData
     */
    getTreeList(treeList, leftFromData) {
      treeList.map(item => {
        if (!item.selected) {
          const tempData = {
            ...item
          }

          // 如果有子项
          if (item.children && item.children.length > 0) {
            tempData.children = []
            this.getTreeList(item.children, tempData.children)
          }
          leftFromData.push(tempData)
        }
      })
      this.transferData = leftFromData
    },
    /**
     * 格式化右侧todata
     * @param {array} treeList
     * @param {array} rightToData
     */
    getToDataList(treeList, rightToData) {
      let childrenArr = []

      treeList.forEach(element => {
        // 二级
        element.children.forEach(item => {
          if (element.id === item.pid && item.selected) {
            childrenArr.push(item)
            const tmp = {
              ...element,
              children: childrenArr
            }
            rightToData.push(tmp)
          }
          // 三级
          if (item.children && item.children.length > 0) {
            // 递归
            this.getToDataList(item.children, rightToData)
          }
        })
        childrenArr = []
      })
      // 引用类型数组去重
      this.toData = _.uniqWith(rightToData, _.isEqual)
    },
    onSubmit() {
      this.$refs.queryForm.validate(async valid => {
        if (valid) {
          this.queryParams.qrCodeUuid = StrUtil.generateSimpleUUID()
          const params = {
            ...this.queryParams,
            startDate: this.queryParams.timeRange[0],
            endDate: this.queryParams.timeRange[1],
            userIdList: this.userIdList, // 人员ids
            examPaperList: this.examTableData, // 考试数组
            delExamPaperIds: this.delExamPaperIds, // 删除的考试ids
            trainId: this.trainId || ''
          }
          delete params.timeRange
          console.log('🚀 ~ file: Training.vue ~ line 33 ~ Training ~ onSubmit ~ params', params)
          if (this.trainId) {
            const res = await editTrainingTask(params)
            console.log('🚀 ~ onSubmit ~ res:', res)
          } else {
            const res = await addTrainingTask(params)
            console.log('🚀 ~ onSubmit ~ res:', res)
          }
          this.isLoading = false
          // 关闭当前页
          await this.$tab.closePage()
        }
      })
    }
  }



}
</script>

<style lang="scss" scoped>
.header-wrapper {
  display: flex;
  align-items: center;
  font-weight: 800;

  .line {
    margin-right: 5px;
    width: 3px;
    height: 13px;
    background-color: #409eff;
  }
}

.bottom-btn {
  margin: 30px 0 20px;
  display: flex;
  justify-content: flex-end;
}
::v-deep .wl-transfer .transfer-main {
  height: calc(100% - 81px) !important;
}
</style>
