<template>
  <div style="height: 100%; padding-bottom: 20px;">
    <el-card>
      <div slot="header" class="lessonHeader">
        {{ $t('global.lessonSystem') }}
      </div>
    </el-card>
    <el-card v-loading="loading">
      <el-row style="padding: 10px;display: flex;align-items: center;justify-content: flex-end;">
        <div style="font-size: 14px;color: #000;">课程名称：</div>
        <el-input v-model="inputName" size="small" style="width: 200px;margin-right: 50px;margin-left: 10px;" placeholder="请输入筛选的名称" @change="changeInput" />
        <el-button size="small" type="primary" @click="goToFilter">查找</el-button>
      </el-row>
      <el-table :data="filterTableData" border style="width: 100%">
        <el-table-column prop="name" :label="project === 'cgy'?'项目名称':this.$t('teach.courseName')" />
        <el-table-column v-if="isGzbShow" prop="classNames" label="所属班级">
          <template slot-scope="scope">
            <el-tag v-for="(item, index) in scope.row.classNames" :key="index" type="success">{{ item }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" show-overflow-tooltip :label="project === 'cgy'?'项目描述':this.$t('teach.courseDescription')" />
        <el-table-column :label="this.$t('global.operate')">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="goLesson(scope.row)">{{ project === 'cgy'?'进入项目':$t('teach.enterTheCourse') }}</el-button>
            <el-button v-if="isAdmin && !scope.row.systemFault" size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <!--<el-button v-if="((isCompanyAdmin && userId === scope.row.creatorId) || isAdmin) && !scope.row.systemFault" size="mini" type="warning" @click="handleSoldOut(scope.row)">下架</el-button>-->
            <el-button v-if="isAdmin && !scope.row.systemFault" size="mini" type="danger" @click="handleDelete(scope.row)">{{ project === 'cgy'?'删除项目':'删除课程' }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <update-operate ref="updateLesson" :title="$t('publish.updateLesson')" @create="handleUpdate" />
  </div>
</template>

<script>
import { getSubSystemDetail } from '@/api/trainingPlatform';
import { UrlConfig } from '@/scripts/ConstDic';
import { forceDeleteLesson } from '@/api/jmap/lesson';
import { getSessionStorage } from '@/utils/auth';
import { superAdmin, admin } from '@/router/index';
import { putLessonOffLine, updatePublishLesson } from '@/api/jmap/lesson';
import UpdateOperate from '@/views/publish/publishLesson/draft.vue';
import localStore from 'storejs';

export default {
    name: 'TeachHome',
    components:{
        UpdateOperate
    },
    data() {
        return {
            tableData: [],
            loading: false,
            mapId: '',
            prdType: '',
            cityCode: '',
            filterTableData: [],
            inputName: ''
        };
    },
    computed: {
        isGzbShow() {
            return getSessionStorage('project').startsWith('gzb');
        },
        project() {
            return getSessionStorage('project');
        },
        userId() {
            return this.$store.state.user.id;
        },
        isAdmin() {
            return this.$store.state.user.roles.includes(admin) || this.$store.state.user.roles.includes(superAdmin);
        }
    },
    watch: {
        '$route.params.subSystem': function(newVal) {
            this.loadInitPage();
        }
    },
    mounted() {
        this.loadInitPage();
    },
    methods: {
        loadInitPage() {
            if (this.$route.params.subSystem) {
                getSubSystemDetail(this.$route.params.subSystem).then(resp =>{
                    if (resp.data) {
                        this.mapId = resp.data.mapId;
                        this.prdType = resp.data.prdType;
                        this.tableData = resp.data.lessonList;
                        this.cityCode = resp.data.cityCode;
                    } else {
                        this.tableData = [];
                    }
                    this.inputName = localStore.get(this.$route.path) || '';
                    this.goToFilter();
                }).catch((error)=>{
                    if (error.code == 30001) {
                        const url = localStore.get('orignalTrainingPlatformRoute' + this.$store.state.user.id + this.project);
                        if (url) {
                            this.$router.push(url);
                        }
                    } else {
                        this.$messageBox(this.$t('error.obtainCourseInformationFailed'));
                    }
                });
            }
        },
        goLesson(row) {
            this.$router.push({ path: `${UrlConfig.trainingPlatform.teachDetail}/${this.$route.params.subSystem}`, query: {lessonId: row.id, mapId: row.mapId, prdType: row.prdType}});
        },
        handleSoldOut(row) {
            this.$confirm(this.$t('publish.wellSoldOutTraining'), this.$t('global.tips'), {
                confirmButtonText: this.$t('global.confirm'),
                cancelButtonText: this.$t('global.cancel'),
                type: 'warning'
            }).then(() => {
                putLessonOffLine(row.id).then(response => {
                    this.$message.success(this.$t('publish.operationSuccess'));
                    this.reloadTable();
                }).catch(() => {
                    this.reloadTable();
                    this.$messageBox(this.$t('error.operationFailure'));
                });
            }).catch(() => { });
        },
        handleEdit(row) {
            this.$refs.updateLesson.doShow(row);
        },
        handleUpdate(data) {
            updatePublishLesson(data).then(response => {
                this.loadInitPage();
                this.$message.success(this.$t('publish.updateSuccess'));
            }).catch(() => {
                this.$messageBox(this.$t('error.updateFailed'));
            });
        },
        changeInput(val) {
            localStore.set(this.$route.path, val);
        },
        goToFilter() {
            if (!this.inputName) {
                this.filterTableData = [...this.tableData];
            } else {
                this.filterTableData = [];
                this.tableData.forEach(item => {
                    if (item.name.includes(this.inputName)) {
                        this.filterTableData.push(item);
                    }
                });
            }
        },
        handleDelete(row) {
            this.$confirm('此操作将删除课程，且无法恢复，是否继续？', this.$t('global.tips'), {
                confirmButtonText: this.$t('global.confirm'),
                cancelButtonText: this.$t('global.cancel'),
                type: 'warning'
            }).then(() => {
                forceDeleteLesson(row.id).then(response => {
                    this.$message.success(this.$t('publish.deleteSuccess'));
                    this.loadInitPage();
                }).catch((error) => {
                    this.loadInitPage();
                    this.$messageBox(this.$t('error.deleteFailed') + ':' + error.message);
                });
            }).catch(() => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.lessonHeader{
  text-align: center;
  font-weight: bold;
}
</style>
