<template>
  <div class="app-container">
    <el-card shadow="always">
      <div slot="header" class="header-wrapper">
        <div class="line"></div>
        <span>考试信息</span>
      </div>

      <!-- 表单 -->
      <el-form :model="queryParams" ref="queryForm" size="small" label-width="80px" :rules="rules">
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="queryParams.examName" placeholder="请输入考试名称" clearable style="width: 260px" />
        </el-form-item>
        <el-form-item label="选择试卷" required>
          <el-button type="primary" size="mini" @click="handleQuotePaper">引用试卷</el-button>
          <el-button type="primary" size="mini" @click="handleCreatePaper">创建试卷</el-button>
        </el-form-item>
        <el-form-item label="试卷名称" prop="paperName">
          <el-input
            v-model="queryParams.examPaperList[0].paperName"
            placeholder="请输入试卷名称" v-no-whitespace
            clearable
            style="width: 260px"
            disabled
          />
        </el-form-item>
        <el-form-item label="题目数" prop="questionNum">
          <el-input
            v-model="queryParams.examPaperList[0].questionNum"
            placeholder="请输入题目数" v-no-whitespace
            clearable
            style="width: 260px"
            disabled
          />
        </el-form-item>
        <el-form-item label="总分" prop="totalScore">
          <el-input
            v-model="queryParams.examPaperList[0].totalScore"
            placeholder="请输入总分" v-no-whitespace
            clearable
            style="width: 260px"
            disabled
          />
        </el-form-item>
        <el-form-item label="考试时长" prop="examLduration">
          <el-input v-model="queryParams.examLduration" placeholder="请输入考试时长" v-no-whitespace clearable style="width: 260px" />
          分钟
        </el-form-item>
        <el-form-item label="考试日期" prop="examDate">
          <el-date-picker
            v-model="queryParams.examDate"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
            :picker-options="pickerOptions"
            style="width: 400px"
          />
        </el-form-item>
        <el-form-item label="考试对象" prop="examTarget">
          <el-select
            v-model="queryParams.examTarget"
            placeholder="请选择考试对象"
            clearable
            style="width: 260px"
            @change="changeExamObject"
          >
            <el-option v-for="item in examObjectOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="考前说明" prop="examStatement">
          <el-input
            v-model="queryParams.examStatement"
            type="textarea"
            placeholder="请输入考前说明" v-no-whitespace
            clearable
            :rows="5"
            :maxlength="200"
            show-word-limit
            style="width: 260px"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 20px">
      <div slot="header" class="header-wrapper">
        <div class="line"></div>
        <span>人员信息</span>
      </div>
      <el-row style="margin-bottom: 15px">
        <el-button type="primary" v-if="queryParams.examTarget == '1'" size="mini" @click="openDialog(1)">
          选择内部人员
        </el-button>
        <el-button type="primary" v-if="queryParams.examTarget == '2'" size="mini" @click="openDialog(2)">
          选择外委人员
        </el-button>
        <span style="color: #7915f5; font-size: 12px; margin-left: 10px">人员选择根据考试对象选择</span>
      </el-row>

      <!-- 列表 -->
      <el-table :data="tableData" fit highlight-current-row style="width: 100%">
        <el-table-column
          type="index"
          width="55"
          label="序号"
          align="center"
          :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
        />
        <el-table-column
          v-for="item in queryParams.examTarget == '2' ? tableColumns : tableColumns2"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
          align="center"
        >
          <!-- 状态插槽 -->
          <template v-if="item.prop === 'sex'" v-slot="scope">
            <el-tag v-if="scope.row.sex === '0'" type="success" size="mini">男</el-tag>
            <el-tag v-else-if="scope.row.sex === '1'" type="danger" size="mini">女</el-tag>
          </template>
        </el-table-column>
        <!-- 删除 -->
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope.row)"
              style="color: #e47470"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <!-- <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="personQueryParams.pageNum"
        :limit.sync="personQueryParams.pageSize"
        @pagination="getTaskUsersByChecked"
      /> -->
    </el-card>

    <div class="confirm-btn">
      <el-button size="mini" type="primary" @click="handleConfirm" v-preventReClick="5000">确 定</el-button>
    </div>

    <!-- 通用弹框 -->
    <GeneralDialog
      ref="GeneralDialog"
      title="引用试卷"
      :columns="generalDialogColumns"
      @getDialogData="getDialogData"
    />

    <!-- 创建试卷 -->
    <CreateTestPaperDialog ref="CreateTestPaperDialog" @getDialogData="getDialogData"/>

    <el-dialog title="选择人员" :visible.sync="dialogTransfer" width="35%">
      <!-- <el-transfer
        v-model="transferValue"
        :data="transferData"
        :titles="[' ', ' ']"
        :filterable="true"
        filter-placeholder="请输入搜索内容"
      ></el-transfer> -->
      <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 GeneralDialog from '@/views/educationalTraining/learningManagement/learningTasks/components/GeneralDialog'
import CreateTestPaperDialog from '@/views/educationalTraining/learningManagement/learningTasks/components/CreateTestPaperDialog'
import treeTransfer from 'el-tree-transfer'
import {
  addExamTask,
  addTrainingTask,
  editExamTask,
  editTrainingTask,
  getExamTaskById,
  getPersonTreeByType,
  getTaskUsersByChecked,
} from '@/api/educationalTraining/resourceAdministration'
import ExamDialog from '@/views/educationalTraining/learningManagement/learningTasks/components/ExamDialog.vue'
import { addDateRange, indexContinuous, parseTime } from '@/utils/bonus'

export default {
  components: { ExamDialog, GeneralDialog, CreateTestPaperDialog, treeTransfer },
  data() {
    return {
      dialogTransfer: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 考试名称
        examName: '',
        examPaperList: [
          {
            examPaperId: '',
            examPaperName: '',
            examTemplateId: '',
            examTemplateType: '1',
            totalScore: '',
            passScore: '',
            esamTime: '',
            statement: '',
            papeType: '3',
          },
        ],
        // 考试时长
        examLduration: '',
        examDate: '',
        startTime: undefined,
        endTime: undefined,
        // 考试对象
        examTarget: '',
        // 考前说明
        examStatement: '',
        userIdList: [],
      },
      pickerOptions: {
        disabledDate: this.disabledDate,
      },
      // 考试对象-下拉
      examObjectOptions: [
        { label: '内部人员', value: '1' },
        { label: '外委人员', value: '2' },
      ],
      // 表头
      tableColumns: [
        { label: '姓名', prop: 'userName' },
        { label: '性别', prop: 'sex' },
        { label: '身份证号码', prop: 'idCard' },
        { label: '联系方式', prop: 'phone' },
        { label: '工程名称', prop: 'proName' },
        { label: '承包商名称', prop: 'subName' },
        { label: '岗位', prop: 'postName' },
        { label: '工种', prop: 'workTypeName' },
      ],
      tableColumns2: [
        { label: '姓名', prop: 'userName' },
        { label: '性别', prop: 'sex' },
        { label: '身份证号码', prop: 'idCard' },
        { label: '联系方式', prop: 'phone' },
      ],
      personQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表格数据
      tableData: [],
      examTableData: [],
      delExamPaperIds: [], // 删除的考试/练习ids
      total: 0,
      // 穿梭框数据
      transferValue: [],
      transferData: [], // 左侧数据
      toData: [], // 右侧数据
      // 外委人员
      externalPerson: [],
      // 内部人员
      internalPerson: [],
      // 已选人员 ids[]
      userIdList: [],
      selectionRows: [], // 选中的行
      // 外委or内部
      personType: 1,
      // 穿梭框全部数据
      dataList: [],
      // 表单验证
      rules: {
        examName: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
        examLduration: [
          { required: true, message: '请输入考试时间', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' },
        ],
        examDate: [{ required: true, message: '请选择考试时间范围', trigger: 'change' }],
        examTarget: [{ required: true, message: '请选择考试对象', trigger: 'change' }],
      },
      // 通用弹框-表格头
      generalDialogColumns: [
        { label: '试卷名称', prop: 'examTemplateName' },
        { label: '试题数', prop: 'questionNum' },
      ],
      examTaskId: '',
      currentTreeData: [],
      currentUserList: [],
    }
  },
  created() {
    this.examTaskId = this.$route.query.examTaskId || ''
    console.log('🚀 ~ created ~ this.examTaskId:', this.examTaskId)
    if (this.examTaskId) {
      this.getExamTaskById()
    }
  },
  methods: {
    indexContinuous,
    disabledDate(time) {
      const today = new Date()
      today.setHours(0, 0, 0, 0) // 将时间归零，只比较日期
      return time.getTime() < today.getTime()
    },
    // 打开弹框
    async openDialog(type) {
      this.dialogTransfer = true // 打开穿梭框
      console.log('🚀 ~ handleSelectPerson ~ val:', this.transferData)
      this.$nextTick(() => {
        this.getTreeList(this.currentTreeData, [])
        this.toData = this.filterTree(this.currentTreeData)
      })
    },
    // 从子组件获取添加的课件, 考试, 练习数据
    getDialogData(type, data) {
      console.log('🚀 ~ getDialogData ~ type:', type)
      console.log('🚀 ~ getDialogData ~ data:', data)
      this.examTableData = data
      this.queryParams.examPaperList[0].examPaperName = data[0].examTemplateName
      this.queryParams.examPaperList[0].paperName = data[0].examTemplateName
      this.queryParams.examPaperList[0].questionNum = data[0].questionNum
      this.queryParams.examPaperList[0].totalScore = data[0].totalScore
      this.queryParams.examPaperList[0].passScore = data[0].passScore
      this.queryParams.examPaperList[0].examTemplateId = data[0].examTemplateId
      this.queryParams.examPaperList[0].examTemplateType = 1
      if (this.queryParams.examPaperList[0].examPaperId) {
        this.delExamPaperIds.push(this.queryParams.examPaperList[0].examPaperId)
      }
    },
    getExamTaskById() {
      getExamTaskById({ examTaskId: this.examTaskId, taskType: 3 }).then(async res => {
        console.log('🚀 ~ getExamTaskById ~ res:', res)
        this.queryParams.examName = res.data.examName
        this.queryParams.examLduration = res.data.examLduration
        this.queryParams.examDate = [res.data.startTime, res.data.endTime]
        this.queryParams.examTarget = res.data.examTarget
        this.queryParams.examStatement = res.data.examStatement
        this.queryParams.examPaperList[0].examPaperName = res.data.examPaperList[0].examPaperName
        this.queryParams.examPaperList[0].paperName = res.data.examPaperList[0].examPaperName
        this.queryParams.examPaperList[0].questionNum = res.data.examPaperList[0].questionNum
        this.queryParams.examPaperList[0].totalScore = res.data.examPaperList[0].totalScore
        this.queryParams.examPaperList[0].passScore = res.data.examPaperList[0].passScore
        this.queryParams.examPaperList[0].examPaperId = res.data.examPaperList[0].examPaperId
        this.queryParams.examPaperList[0].examTemplateId = res.data.examPaperList[0].examTemplateId
        this.queryParams.examPaperList[0].examTemplateType = 1

        this.userIdList = res.data.userIdList
        this.currentUserList = res.data.userIdList
        await this.getTaskUsersByChecked()
        await this.getPersonTreeByType()
      })
    },
    changeExamObject(val) {
      console.log('🚀 ~ changeExamObject ~ val:', val)
      // 清除外委人员
      this.externalPerson = []
      // 清除内部人员
      this.internalPerson = []
      this.transferData = []
      this.toData = []
      this.tableData = []
      this.userIdList = []
      this.currentUserList = []
      this.getPersonTreeByType()
    },
    // 获取人员树
    async getPersonTreeByType() {
      try {
        const params = {
          type: this.queryParams.examTarget == '1' ? '2' : '1',
          proId: this.queryParams.proId || '',
        }
        const res = await getPersonTreeByType(params)
        this.transferData = res.data
        this.currentTreeData = res.data
        this.handlePersonTree(this.transferData)
      } catch (error) {}
    },
    // 编辑时 studyTaskId有值时, 为编辑状态, 根据 userIdList 过滤出已选人员
    handleEditToData(data, parent = null) {
      data.forEach(item => {
        // 如果 item.id 在已选人员ids[]中 则 selected = true
        if (this.userIdList && this.userIdList.includes(item.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)
        }
      })
      console.log('🚀 ~ 编辑to ~ this.toData:', this.toData)
    },
    // 递归循环-人员树- 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)
    },
    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)
          if (filteredChildren.length > 0) {
            acc.push({ ...node, pid, children: filteredChildren })
          }
        }
        return acc
      }, [])
    },
    // 穿梭框确定
    handleTransfer() {
      console.log('🚀 ~ 左侧数据 ~ this.toData:', this.toData)
      this.dataList = this.transferData
      this.userIdList = []
      this.handleTransferData(this.toData)
      this.addUserIds(this.toData)
      this.queryParams.trainNum = this.userIdList.length
      this.currentUserList = this.userIdList
      this.getTaskUsersByChecked()

      this.dialogTransfer = false
    },
    getTaskUsersByChecked() {
      getTaskUsersByChecked({
        examTarget: this.queryParams.examTarget,
        checkUserIds: this.userIdList,
      }).then(res => {
        this.tableData = res.data
        this.total = res.data.length
      })
    },
    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)
        }
      })
    },
    /**
     * 格式化左侧数据
     * @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)
    },
    addDateRange,
    // 确定添加
    handleConfirm() {
      // 关闭当前标签页
      this.$refs.queryForm.validate(async valid => {
        if (valid) {
          this.queryParams.examPaperList[0].esamTime = this.queryParams.examLduration
          this.queryParams.examPaperList[0].statement = this.queryParams.examStatement
          this.queryParams.userIdList = this.userIdList
          this.queryParams.startTime = parseTime(this.queryParams.examDate[0], '{y}-{m}-{d} {h}:{i}')
          this.queryParams.endTime = parseTime(this.queryParams.examDate[1], '{y}-{m}-{d} {h}:{i}')
          this.queryParams.examTaskId = this.examTaskId
          if (this.examTaskId) {
            const res = await editExamTask(this.queryParams)
            console.log('🚀 ~ onSubmit ~ res:', res)
          } else {
            const res = await addExamTask(this.queryParams)
          }
          // // 关闭当前页
          await this.$tab.closePage().then(() => {
            this.$router.push({ path: '/educationalTraining/learningManagement/examination/index' })
          })
        }
      })
    },
    // 引用试卷
    handleQuotePaper() {
      this.$refs.GeneralDialog.openDialog('1')
    },
    // 创建试卷
    handleCreatePaper() {
      this.$refs.CreateTestPaperDialog.show()
      // this.$refs.CreateTestPaperDialog.openDialog()
    },
    // 删除
    handleDelete(row) {
      console.log('🚀 ~ handleDelete ~ row:', row)
      this.tableData = this.tableData.filter(item => item.id !== row.id)
      this.userIdList = this.userIdList.filter(item => item !== row.id)
      this.currentUserList = this.userIdList
    },
  },
}
</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;
  }
}

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