<template>
  <a-card class="coures" :bordered="false" title="项目课程信息">
    <a-space direction="vertical" style="width: 100%">
      <a-space direction="horizontal">
        <span>总课时：{{ form.totalCourseHours }}H , 总学时要求：{{ form.totalLearnHours }}H , 总题目数量：{{ form.totalTopicNumber }} </span>
        课程名:
        <a-input v-model="queryParam.courseName" style="width: 100%" />
        <a-button type="primary" icon="search" @click="$refs.table.refresh(true)">查询</a-button>
        <a-button icon="select" @click="$refs.CourseSelect.edit({})">添加课程</a-button>
      </a-space>

      <s-table ref="table" size="default" rowKey="id" :columns="columns" :data="loadData" :showPagination="false">
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-dropdown>
              <a class="ant-dropdown-link">操作
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a href="javascript:;" @click="openVisible('course',record)">课程预览</a>
                </a-menu-item>
                <a-menu-item>
                  <a href="javascript:;" @click="openVisible('question',record)">题库预览</a>
                </a-menu-item>
                <a-menu-item v-if="form.id" >
                  <a href="javascript:;" @click="openVisible('topic',record)">必选题设置</a>
                </a-menu-item>
                <a-menu-item>
                  <a-popconfirm title="是否删除?" @confirm="() => handleDelete(record)">
                    <a href="javascript:;" @click="$refs.table.refresh(true)">删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </span>
      </s-table>
    </a-space>
    <project-course-select ref="CourseSelect" @selectKeyDataSubmit="selectKeyDataChange" :selectRows="selData"></project-course-select>
    <a-col :span="24" style="text-align: center;">
      <a-button type="primary" size="default" @click="toPrep" style="margin-right: 8px;">上一步</a-button>
      <a-button type="primary" size="default" @click="toNext">下一步</a-button>
    </a-col>
    <a-drawer title="课程预览" :destroyOnClose="true" placement="right" width="1200" :closable="true" :visible="courseVisible" @close="drawerClose">
      <courseware-list :courseId="selectCourseId"></courseware-list>
    </a-drawer>
    <a-drawer title="题库预览" :destroyOnClose="true" placement="right" width="1200" :closable="true" :visible="questionVisible" @close="drawerClose">
      <question-list :courseId="selectCourseId"></question-list>
    </a-drawer>
    <a-drawer title="必选题设置" :destroyOnClose="true" placement="right" width="1200" :closable="true" :visible="requiredTopicVisible" @close="drawerClose">
      <p>必选题设置</p>
    </a-drawer>
  </a-card>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《s组件路径》'
import { STable } from '@/components'
import ProjectCourseSelect from './ProjectCourseSelect.vue'
import { getCourseList, getCourseListByCourseIds } from '@/api/project/projectCourse'
import QuestionList from '@/views/course/question/QuestionList.vue'
import CoursewareList from '@/views/course/CoursewareList.vue'

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    STable,
    QuestionList,
    CoursewareList,
    ProjectCourseSelect,
    QuestionList,
  },
  props: {
    projectForm: {
      type: Object,
    },
    courseChange: {
      type: Boolean,
    }
  },
  data() {
    //这里存放数据
    return {
      form: this.projectForm,
      selData: [],
      labelCol: {},
      wrapperCol: {},
      vertical: 'vertical',
      beChange: this.courseChange || false,  //被编辑过标识
      totalCourseHours: 0, //总课时
      totalLearnHours: 0, //总学时
      totalTopicNumber: 0, //题目数量
      selectCourseId: '', //课程id

      courseVisible: false, //课程预览页面显示控制
      questionVisible: false, //题库预览页面显示控制
      requiredTopicVisible:false, //必选题设置显示控制

      queryParam: {
        ids: '',
      }, //查询数据
      columns: [
        { title: '序号', key: 'id', dataIndex: 'id', width: 60, scopedSlots: { customRender: 'serial' } },
        { title: '课程编号', dataIndex: 'courseCode', key: 'courseCode' },
        { title: '课程名称', dataIndex: 'courseName', key: 'courseName' },
        { title: '课时', dataIndex: 'courseHours', key: 'courseHours', customRender: (text) => text + 'H' },
        { title: '学时要求', dataIndex: 'learnHours', key: 'learnHours', customRender: (text) => text + 'H' },
        { title: '题量', dataIndex: 'topicNumber', key: 'topicNumber' },
        { title: '操作', width: 200, align: 'center', scopedSlots: { customRender: 'action' } },
      ], // 表头
      loadData: (parameter) => {
        if (this.$route.query.projectId && !this.beChange) {
          /** 编辑进来的有项目id 并且没有被编辑过*/
          return getCourseList({id:this.$route.query.projectId}).then((res) => {
            this.selData = res.data;
            this.calc(res.data)
            return res.data
          })
        } else {
          /** 新建的没有项目id，传当前的所选的课程id */
          return getCourseListByCourseIds(Object.assign(parameter, this.queryParam)).then((res) => {
            this.selData = res.data;
            this.calc(res.data)
            return res.data
          })
        }
      },
    }
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //关闭抽屉
    drawerClose(){
      this.courseVisible = false;
      this.requiredTopicVisible = false;
      this.questionVisible = false;
    },

    //打开抽屉
    openVisible(type,record) {
      this.selectCourseId = record.id;
      if(type === 'course') this.courseVisible = true;
      else if(type === 'topic') this.requiredTopicVisible = true;
      else if(type === 'question') this.questionVisible = true;
    },
    //计算总学时，总分数，总课时
    calc(data) {
      this.form.totalCourseHours = 0
      this.form.totalLearnHours = 0
      this.form.totalTopicNumber = 0
      data.forEach((item) => {
        this.form.totalCourseHours = this.form.totalCourseHours + parseInt(item.courseHours)
        this.form.totalLearnHours = this.form.totalLearnHours + parseInt(item.learnHours)
        this.form.totalTopicNumber = this.form.totalTopicNumber + parseInt(item.topicNumber)
      })
    },
    //下一步
    toNext() {
      this.form.lessonIds = []
      let ids = this.queryParam.ids.split(',')
      ids.forEach((id, index, arr) => {
        // console.log('id-----------------------', id)
        this.form.lessonIds.push({ ids: id, sort: index })
      })
      if (this.form.lessonIds.length > 0) {
        this.$emit('nextStep', this.form,this.beChange)
      } else {
        this.$message.warning('培训课程不能为空')
      }
    },
    //上一步
    toPrep() {
      this.form.lessonIds = []
      let ids = this.queryParam.ids.split(',')
      ids.forEach((id, index, arr) => {
        this.form.lessonIds.push({ ids: id, sort: index })
      })

      // console.log('toPrep', this.form)
      this.$emit('prevStep', this.form,this.beChange)
    },
    //初始化ids
    initIds() {
      // console.log('this.projectForm.lessonIds',this.projectForm.lessonIds)
      let str = [];
      if (this.projectForm.lessonIds) str = this.projectForm.lessonIds
      // let str = this.projectForm.lessonIds.join(',') || []
      // console.log('initIds', str)
      if (str && str.length > 0) {
        let arr = [];
        str.forEach((item) => {
          arr.push(item.ids)
        })
        this.queryParam.ids = arr.join(',')
      }
    },
    //选择课程完毕，提交到list页面
    selectKeyDataChange(childValue) {
      console.log('list page - selectKeyDataSubmit', childValue)
      this.queryParam.ids = childValue
      this.beChange = true
      this.$refs.table.refresh(true)
    }
  },

  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.initIds()
  },
  mounted() { }, //生命周期 - 挂载完成（可以访问DOM元素）
  beforeCreate() { }, //生命周期 - 创建之前
  beforeMount() { }, //生命周期 - 挂载之前
  beforeUpdate() { }, //生命周期 - 更新之前
  updated() { }, //生命周期 - 更新之后
  beforeDestroy() { }, //生命周期 - 销毁之前
  destroyed() { }, //生命周期 - 销毁完成
  activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>
</style>