<template>
  <a-modal title="选择课程" ok-text="确认" cancel-text="取消" :width="1100" :visible="auditionVisible" @ok="auditionOk"
    @cancel="auditionCancel" >
    <a-tabs v-model="activeTab" @change="handleChangeTab" :animated="false" :tab-bar-style="{marginTop: '-20px', paddingLeft: '0px'}">
      <a-tab-pane tab="试听课" key="1">
        <!-- 查询条件Audition -->
        <a-range-picker v-model="queryParam.date" format="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']"
          @change="handleQueryTimeChange" :style="{width: '222px'}" />
        <DropDownSearch @child-event='courseReturn' menuName='选择课程' :QueryList='courseList' :QueryReset='reset'></DropDownSearch>
        <DropDownSearch @child-event='lecturerReturn' menuName='选择老师' :QueryList='lecturerList' :QueryReset='reset'></DropDownSearch>
        <DropDownSearch @child-event='weekReturn' menuName='星期' :QueryList='weekList' :QueryReset='reset'></DropDownSearch>
        <a style="margin-left: 10px;" href="javascript:;" @click="handleReset(2)">重置</a>
        <a-button @click="addAuditionClass" style="position: absolute; right: 0px;">安排试听</a-button>
        <AuditionClassAdd  @child-event='auditionClassAddReturn' :auditionClassShow="auditionClass" :cpId="this.dataPara.id" :cpPhone="this.dataPara.cpPhone" ></AuditionClassAdd>
        <!-- 选择区域 -->
        <a-table
          ref="table"
          size="middle"
          style="margin-top: 15px;"
          :scroll="{ y:200,x:800 }"
          rowKey="id"
          :columns="columns"
          :dataSource="table.dataSource"
          :pagination="table.pagination"
          :loading="table.loading"
          :row-selection="rowSelection"
          class="j-table-force-nowrap"
          @change="handleTableChange">
        </a-table>
      </a-tab-pane>
      <a-tab-pane tab="正式课" key="2" >
        <!-- 查询条件Audition -->
        <a-range-picker v-model="queryParam.date" format="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']"
          @change="handleQueryTimeChange" :style="{width: '222px'}" />
        <DropDownSearch @child-event='courseReturn' menuName='选择课程' :QueryList='courseList' :QueryReset='reset'></DropDownSearch>
        <DropDownSearch @child-event='classReturn' menuName='选择班级' :QueryList='classList' :QueryReset='reset'></DropDownSearch>
        <DropDownSearch @child-event='lecturerReturn' menuName='选择老师' :QueryList='lecturerList' :QueryReset='reset'></DropDownSearch>
        <DropDownSearch @child-event='weekReturn' menuName='星期' :QueryList='weekList' :QueryReset='reset'></DropDownSearch>
        <DropDownSearch @child-event='themeReturn' menuName='上课主题' :QueryList='themeList' :QueryReset='reset'></DropDownSearch>
        <a style="margin-left: 10px;" href="javascript:;" @click="handleReset(1)">重置</a>
        <!-- 选择区域 -->
        <a-table
          ref="table"
          size="middle"
          style="margin-top: 15px;"
          :scroll="{y:200,x:800}"
          rowKey="id"
          :columns="formalColumns"
          :dataSource="table.dataSource"
          :pagination="table.pagination"
          :loading="table.loading"
          :row-selection="rowSelection"
          class="j-table-force-nowrap"
          @change="handleTableChange">
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <AuditionConfirm  @confirm-event='confirmReturn' :confirmShow="confirmShow" 
    :addPara="addPara" :addStatus="'old'" ></AuditionConfirm>
  </a-modal>
</template>
<!-- 重写分页 -->
<script>
import { getAction, postAction } from '@/api/manage'
import { httpGroupRequest } from '@/api/GroupRequest.js'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import DropDownSearch from '../components/DropDownSearch'
import {filterObj} from '@/utils/util'
import moment from 'moment'
import AuditionClassAdd from '../education/modules/AuditionClassAdd.vue'
import AuditionConfirm from './AuditionConfirm.vue'
export default {
  name: 'CustomerAuditionAdd',
  components: {
    DropDownSearch,AuditionClassAdd,AuditionConfirm
  },
  computed: {
    rowSelection() {
      return {
        type: "radio", //单选按钮定义
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
          this.selectedRows = selectedRows;
         }
      };
    }
  },
  data() {
    return {
    table: { 
        loading: true,
        // 表头
        columns: [],
        //数据集
        dataSource: [],
        // 选择器
        selectedRowKeys: [],
        selectionRows: [],
        // 分页参数
        pagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        }
      },
      selectedRowKeys: undefined, 
      selectedRows:{},
      auditionVisible: false,
      queryParam: {
        type: 2,
        status: 2
      },
      activeTab: "1",
      courseList: undefined,
      lecturerList: undefined,
      weekList: undefined,
      classList: undefined,
      themeList: undefined,
      auditionClass: false,
      dateStr: "",
      confirmShow: false,
      addPara : {},
      reset: "",
      dataSource: [],
      columns: [
        {
          title:'上课日期',
          width:210,
          align:"center",
          dataIndex: 'curriculaDate',
          customRender: (text, row ) => {
            var date;
            var dateArray = text.split("-");
            date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
            return text + "【星期" + "日一二三四五六".charAt(date.getDay()) +"】" + row.curriculaTime;
          }
        },
        {
          title:'课程',
          align:"center",
          dataIndex: 'courseId_dictText'
        },
        {
          title:'教室',
          align:"center",
          dataIndex: 'classRoomId_dictText'
        },
        {
          title:'老师',
          align:"center",
          dataIndex: 'lecturerId_dictText',
          customRender: function(t) {
            if(t !== null && t !== undefined && t.length > 7) {
              return (t.slice(0, 7) + '...');
            } else {
              return t;
            }
          }
        },
        {
          title:'学员人数',
          align:"center",
          dataIndex: 'maximum'
        }
      ],
      formalColumns:[
        {
          title:'上课日期',
          align:"center",
          width:230,
          dataIndex: 'curriculaDate',
          customRender: (text, row ) => {
            var date;
            var dateArray = text.split("-");
            date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
            return text + "【星期" + "日一二三四五六".charAt(date.getDay()) +"】" + row.curriculaTime;
          }
        },
        {
          title:'课程',
          align:"center",
          dataIndex: 'courseId_dictText'
        },
        {
          title:'教室',
          align:"center",
          dataIndex: 'classRoomId_dictText',
          customRender: function(t) {
            if(t !== null && t !== undefined && t.length > 7) {
              return (t.slice(0, 7) + '...');
            } else {
              return t;
            }
          }
        },
        {
          title:'班级',
          align:"center",
          dataIndex: 'classId_dictText',
          customRender: function(t) {
            if(t !== null && t !== undefined && t.length > 7) {
              return (t.slice(0, 7) + '...');
            } else {
              return t;
            }
          }
        },
        {
          title:'老师',
          align:"center",
          dataIndex: 'lecturerId_dictText',
          customRender: function(t) {
            if(t !== null && t !== undefined && t.length > 7) {
              return (t.slice(0, 7) + '...');
            } else {
              return t;
            }
          }
        },
        {
          title:'主题',
          align:"center",
          dataIndex: 'themeId_dictText',
          customRender: function(t) {
            if(t !== null && t !== undefined && t.length > 7) {
              return (t.slice(0, 7) + '...');
            } else {
              return t;
            }
          }
        },
        {
          title:'学员人数',
          align:"center",
          dataIndex: 'maximum'
        },
        {
          title:'适龄',
          align:"center",
          dataIndex: 'age_range'
        }
      ],
      rules: {
        date: [
          { required: true, message: '请输入预约日期!', trigger: 'blur'},
        ],
      },
    }
  },
  props: ['auditionShow', 'dataPara'],
  watch: {
    auditionShow: {
        handler() {
          this.activeTab = "1"; //触发激活第一个页签
          this.auditionVisible = this.auditionShow
          initDictOptions('customer_follow_type').then((res) => {
              if (res.success) {
                  this.followTypeList = res.result;
              }
          });
          this.followDate = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
          if(this.auditionShow) {
            this.loadData();
          }
        }
      }
  },
  created () {
    //给子组件传递数据 课程信息
    getAction("/education/educationCourse/queryList").then((res) => {
      this.courseList = res;
    });
    //给子组件传递数据 老师信息
    getAction("/sys/user/getMultiUser").then((res) => {
      let listTemp = [];
      for(let item of res) {
        let temp = {
          "id": item.id,
          "name":item.realname
        }
        listTemp.push(temp)
      }
      this.lecturerList = listTemp;
    });
    //给子组件传递数据 星期
    this.weekList = [ {"id": 1 , "name": "星期一"}, {"id": 2 , "name": "星期二"}, 
    {"id": 3 , "name": "星期三"}, {"id": 4 , "name": "星期四"}, {"id": 5 , "name": "星期五"}, 
    {"id": 6 , "name": "星期六"}, {"id": 7 , "name": "星期日"} ];
    //给子组件传递数据 班级
    getAction("/education/educationClass/queryList").then((res) => {
      this.classList = res;
    });
    //给子组件传递数据 主题 themeList
    getAction("/education/educationTheme/queryList").then((res) => {
      this.themeList = res;
    });
  },
  methods: {
      handleChangeTab(key) {
        this.queryParam = {};
        if (key == 1) {
          this.queryParam.type = 2;
        } else if (key == 2) {
          this.queryParam.type = 1;
        }
        //页面切换 重置组件 上面有点儿乱↑ 后面调整……
        this.handleReset(this.queryParam.type);
        this.loadData();
      },
      disabledDate(current) {
        return current < moment().endOf("day"); // 当前时间之前的所有日期都禁用
      },
      disabledFollowDate(current) {
        return current > moment().endOf("day"); // 当前时间之后的所有日期都禁用
      },
      auditionOk(){
        if(this.selectedRows !== undefined) {
          //显示提交
          this.addPara = {
            curriculaDate:this.selectedRows[0].curriculaDate,
            cpId:this.dataPara.id,
            schedule_id:this.selectedRows[0].id,
            scheduleId_old: this.dataPara.scheduleId_old,
            curriculaTime:this.selectedRows[0].curriculaTime,
            schoolDistrictId:this.selectedRows[0].schoolDistrictId,
            courseId:this.selectedRows[0].courseId,
            lecturerId:this.selectedRows[0].lecturerId,
            assistantId:this.selectedRows[0].assistantId,
            themeId:this.selectedRows[0].themeId,
            remark:this.selectedRows[0].remark,
            type:this.selectedRows[0].type,
            createBy:this.selectedRows[0].createBy,
            createTime:this.selectedRows[0].createTime,
            status:this.selectedRows[0].status,
            classRoomId:this.selectedRows[0].classRoomId,
            period:this.selectedRows[0].period,
            courseText:this.selectedRows[0].courseId_dictText,
            classRoomText:this.selectedRows[0].classRoomId_dictText,
            lecturerText:this.selectedRows[0].lecturerId_dictText,
            assistantText:this.selectedRows[0].assistantId_dictText,
            themeText:this.selectedRows[0].themeId_dictText,
            sqlType:this.dataPara.sqlType
          }
          this.confirmShow = true;
        }
      },
      auditionCancel(){
        this.dateStr = "";
        this.dataVisit = "";
        this.queryParam = {};
        this.queryParam.type = 2;
        this.reset = true;
        this.selectedRows = undefined;
        this.selectedRowKeys = {};
        this.addPara = {};
        this.$emit('audition-event', 'audition');
      },
      handleQueryTimeChange: function (value, dateString) {
        this.queryParam.beginTime=dateString[0];
        this.queryParam.endTime=dateString[1];
        this.loadData();
      },
      handleReset(key) {
        this.queryParam = {};
        this.reset = new Date().getTime();
        this.queryParam.type = key;
        this.loadData();
      },
      courseReturn(data) {
        if(this.queryParamClean(data)) {
          this.queryParam.courseId = data
        }
        this.loadData();
      },
      lecturerReturn(data) {
        if(this.queryParamClean(data)) {
          this.queryParam.lecturerId = data
        }
        this.loadData();
      },
      weekReturn(data) {
        if(this.queryParamClean(data)) {
          this.queryParam.week = data
        }
        this.loadData();
      },
      classReturn(data) {
        if(this.queryParamClean(data)) {
          this.queryParam.classRoomId = data
        }
        this.loadData();
      },
      themeReturn(data) {
        if(this.queryParamClean(data)) {
          this.queryParam.themeId = data
        }
        this.loadData();
      },
      auditionClassAddReturn(data) {
        this.auditionClass = false;
        this.loadData();
        this.$emit('audition-event', 'audition');
      },
      queryParamClean(data) {
        if(data === "ALL") {
          let temp = this.queryParam.type;
          this.queryParam = {};
          this.queryParam.type = temp;
          return false;
        } else {
          return true;
        }
      },
      loadData(arg) {
        if (arg == 1) {
          this.table.pagination.current = 1
        }
        this.queryParam.status = 2;
        let params = this.getQueryParams();//查询条件
        this.table.loading = true
        let url = '/education/educationSchedule/list'
        //缓存key
        let groupIdKey
        if (this.groupId) {
          groupIdKey = this.groupId + url + JSON.stringify(params)
        }
        httpGroupRequest(() => getAction(url, params), groupIdKey).then(res => {
          this.table.loading = false;
          let data = res.result;
          if (data) {
            this.table.pagination.total = Number(data.total);
            this.table.dataSource = data.records;
          } else {
            this.table.pagination.total = 0;
            this.table.dataSource = [];
          }
        })
      },
      getQueryParams() {
        let paramTarget = {}
        if(this.dynamicParam){
          //处理自定义参数
         Object.keys(this.dynamicParam).map(key=>{
           paramTarget['self_'+key] = this.dynamicParam[key]
         })
        }
        let param = Object.assign(paramTarget, this.queryParam, this.iSorter);
        param.pageNo = this.table.pagination.current;
        param.pageSize = this.table.pagination.pageSize;
        return filterObj(param);
      },
      handleTableChange(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        if (Object.keys(sorter).length > 0) {
          this.iSorter = {
            column: sorter.field,
            order: 'ascend' === sorter.order ? 'asc' : 'desc'
          }
          // 排序字段受控
          this.table.columns.forEach(col => {
            if (col.dataIndex === sorter.field) {
              this.$set(col, 'sortOrder',sorter.order)
            } else {
              this.$set(col, 'sortOrder', false)
            }
          })
        }
        this.table.pagination = pagination
        this.loadData()
      },
      addAuditionClass() {
        this.auditionClass = true;
      },
      confirmReturn(message) {
        this.$emit('audition-event', message);
        this.confirmShow = false;
      }
  }
}
</script>

