<template>
  <div>
    <QueryListPage ref="queryListPage" :pager-config="pagerConfig" :query-form="queryForm" :query-list="queryList" />
    <el-dialog v-dialogDrag :title="this.$t('approval.explanation')" :visible.sync="dialogFormVisible" width="500px" center>
      <data-form ref="dataform" :form="form" :form-model="formModel" :rules="rules" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="rejectCancel">{{ $t('global.cancel') }}</el-button>
        <el-button type="primary" @click="rejectConfirm">{{ $t('global.confirm') }}</el-button>
      </div>
    </el-dialog>
    <lesson-detail ref="lessonDetail" />
  </div>
</template>

<script>
import {adminPublishLesson, rejectedLessonRelease, reviewLessonList, reviewScriptList, publishScript, rejectScript, reviewRunPlanList, publishRunPlan, rejectRunPlan, previewRunPlan} from '@/api/designPlatform';
import { getPublishMapListOnline } from '@/api/jmap/map';
import { scriptDraftRecordNotifyNew } from '@/api/simulation';
import LessonDetail from './detail';
import { launchFullscreen } from '@/utils/screen';
import { UrlConfig } from '@/scripts/ConstDic';

export default {
    name: 'Approval',
    components: {
        LessonDetail
    },
    data() {
        return {
            dialogFormVisible: false,
            rejectId: '',
            passId: '',
            formModel: {
                explanation: ''
            },
            approvalType: 'lesson',
            mapList: [],
            pagerConfig: {
                pageSize: 'pageSize',
                pageIndex: 'pageNum'
            },
            queryList: {
                query: this.queryApprovalList,
                selectCheckShow: false,
                indexShow: true,
                columns: [
                    {
                        title: this.$t('lesson.courseName'),
                        prop: 'name'
                    },
                    {
                        title: this.$t('approval.map'),
                        prop: 'mapId ',
                        type: 'tag',
                        columnValue: (row) => { return this.$convertField(row.mapId, this.mapList, ['value', 'label']); },
                        tagType: (row) => { return ''; }
                    },
                    {
                        title: this.$t('approval.courseDescription'),
                        prop: 'remarks'
                    },
                    {
                        title: this.$t('approval.applicant'),
                        prop: 'userName'
                    },
                    {
                        title: this.$t('approval.applyTime'),
                        prop: 'uploadTime',
                        type: 'tag',
                        columnValue: (row) => { return row.uploadTime.replace('T', ' '); },
                        tagType: (row) => { return ''; }
                    },
                    {
                        type: 'button',
                        title: this.$t('global.operate'),
                        width: '400',
                        buttons: [
                            {
                                name: this.$t('approval.lookOver'),
                                handleClick: this.goDetail,
                                type: ''
                            },
                            {
                                name: this.$t('approval.applyPassed'),
                                handleClick: this.pass,
                                type: ''
                            },
                            {
                                name: this.$t('approval.applyReject'),
                                handleClick: this.noPass,
                                type: ''
                            }
                        ]
                    }
                ]
            },
            form: {
                labelWidth: '80px',
                items: [
                    { prop: 'explanation', label: this.$t('approval.explanation'), type: 'textarea', required: true}
                ]
            },
            rules: {
                explanation: [
                    { required: true, message: this.$t('rules.enterRejectReason'), trigger: 'blur' }
                ]
            }
        };
    },
    computed: {
        queryForm() {
            if (this.approvalType === 'script') {
                return {
                    labelWidth: '120px',
                    reset: true,
                    initLoadCallback: this.initLoadCallback,
                    queryObject: {
                        approvalType: {
                            type: 'select',
                            label: '申请类型:',
                            config: {
                                data: [{ label: '课程申请', value: 'lesson' }, { label: '剧本申请', value: 'script'}, { label: '运行图申请', value: 'runPlan' }],
                                noClear: true
                            },
                            default: 'lesson',
                            selectChange: this.approvalTypeChange
                        },
                        mapId: {
                            type: 'select',
                            label: this.$t('approval.map') + this.$t('global.colon'),
                            config: {
                                data: []
                            }
                        },
                        'name':{
                            type: 'text',
                            label: this.$t('approval.scriptName')
                        },
                        'creatorName': {
                            type: 'text',
                            label: this.$t('approval.applicant')
                        }
                    }
                };
            } else if (this.approvalType === 'runPlan') {
                return {
                    labelWidth: '120px',
                    reset: true,
                    queryObject: {
                        approvalType: {
                            type: 'select',
                            label: '申请类型:',
                            config: {
                                data: [{ label: '课程申请', value: 'lesson' }, { label: '剧本申请', value: 'script'}, { label: '运行图申请', value: 'runPlan' }],
                                noClear: true
                            },
                            default: 'lesson',
                            selectChange: this.approvalTypeChange
                        },
                        mapId: {
                            type: 'select',
                            label: this.$t('approval.map'),
                            config: {
                                data: []
                            }
                        },
                        'name':{
                            type: 'text',
                            label: this.$t('approval.runPlanName')
                        },
                        'creatorName': {
                            type: 'text',
                            label: this.$t('approval.applicant')
                        }
                    }
                };
            } else {
                return {
                    labelWidth: '120px',
                    reset: true,
                    initLoadCallback: this.initLoadCallback,
                    queryObject: {
                        approvalType: {
                            type: 'select',
                            label: '申请类型:',
                            config: {
                                data: [{ label: '课程申请', value: 'lesson' }, { label: '剧本申请', value: 'script'}, { label: '运行图申请', value: 'runPlan' }],
                                noClear: true
                            },
                            default: 'lesson',
                            selectChange: this.approvalTypeChange
                        },
                        mapId: {
                            type: 'select',
                            label: this.$t('approval.map') + this.$t('global.colon'),
                            config: {
                                data: []
                            }
                        },
                        lessonName: {
                            type: 'text',
                            label: '课程名称:'
                        },
                        userName: {
                            type: 'text',
                            label: this.$t('approval.applicant') + this.$t('global.colon')
                        }
                    }
                };
            }
        }
    },
    watch: {
        approvalType() {
            if (this.approvalType === 'lesson') {
                this.queryList.columns = [
                    {
                        title: this.$t('lesson.courseName'),
                        prop: 'name'
                    },
                    {
                        title: this.$t('approval.map'),
                        prop: 'mapId ',
                        type: 'tag',
                        columnValue: (row) => { return this.$convertField(row.mapId, this.mapList, ['value', 'label']); },
                        tagType: (row) => { return ''; }
                    },
                    {
                        title: this.$t('approval.courseDescription'),
                        prop: 'remarks'
                    },
                    {
                        title: this.$t('approval.applicant'),
                        prop: 'userName'
                    },
                    {
                        title: this.$t('approval.applyTime'),
                        prop: 'uploadTime',
                        type: 'tag',
                        columnValue: (row) => { return row.uploadTime.replace('T', ' '); },
                        tagType: (row) => { return ''; }
                    },
                    {
                        type: 'button',
                        title: this.$t('global.operate'),
                        width: '400',
                        buttons: [
                            {
                                name: this.$t('approval.lookOver'),
                                handleClick: this.goDetail,
                                type: ''
                            },
                            {
                                name: this.$t('approval.applyPassed'),
                                handleClick: this.pass,
                                type: ''
                            },
                            {
                                name: this.$t('approval.applyReject'),
                                handleClick: this.noPass,
                                type: ''
                            }
                        ]
                    }
                ];
            } else if (this.approvalType === 'script') {
                this.queryList.columns = [
                    {
                        title: this.$t('approval.scriptName'),
                        width:250,
                        prop: 'name'
                    },
                    {
                        title: this.$t('approval.map'),
                        prop: 'mapId ',
                        width:250,
                        type: 'tag',
                        columnValue: (row) => { return this.$convertField(row.mapId, this.mapList, ['value', 'label']); },
                        tagType: (row) => { return ''; }
                    },
                    {
                        title: this.$t('approval.scriptDescription'),
                        prop: 'description'
                    },
                    {
                        title: this.$t('approval.applicant'),
                        prop: 'creatorName'
                    },
                    {
                        title: this.$t('approval.applyTime'),
                        prop: 'uploadTime',
                        type: 'tag',
                        columnValue: (row) => { return row.uploadTime.replace('T', ' '); },
                        tagType: (row) => { return ''; }
                    },
                    {
                        type: 'button',
                        title: this.$t('global.operate'),
                        width: '450',
                        buttons: [
                            {
                                name: this.$t('approval.applyPassed'),
                                handleClick: this.scriptPass,
                                type: ''
                            },
                            {
                                name: this.$t('approval.applyReject'),
                                handleClick: this.noPass,
                                type: ''
                            },
                            {
                                name: this.$t('approval.scriptPreview'),
                                handleClick: this.scriptPreview,
                                type: ''
                            }
                        ]
                    }
                ];
            } else if (this.approvalType === 'runPlan') {
                this.queryList.columns = [
                    {
                        title: this.$t('approval.runPlanName'),
                        width:250,
                        prop: 'name'
                    },
                    {
                        title: this.$t('approval.map'),
                        prop: 'mapId ',
                        width:250,
                        type: 'tag',
                        columnValue: (row) => { return this.$convertField(row.mapId, this.mapList, ['value', 'label']); },
                        tagType: (row) => { return ''; }
                    },
                    {
                        title: this.$t('approval.applicant'),
                        prop: 'creatorName'
                    },
                    {
                        title: this.$t('approval.applyTime'),
                        prop: 'uploadTime',
                        type: 'tag',
                        columnValue: (row) => { return row.uploadTime.replace('T', ' '); },
                        tagType: (row) => { return ''; }
                    },
                    {
                        type: 'button',
                        title: this.$t('global.operate'),
                        width: '450',
                        buttons: [
                            {
                                name: this.$t('approval.applyPassed'),
                                handleClick: this.runPlanPassed,
                                type: ''
                            },
                            {
                                name: this.$t('approval.applyReject'),
                                handleClick: this.noPass,
                                type: ''
                            },
                            {
                                name: this.$t('approval.runPlanPreview'),
                                handleClick: this.runPlanPreview,
                                type: ''
                            }
                        ]
                    }
                ];
            }
        }
    },
    created() {
        getPublishMapListOnline().then(response=>{
            this.mapList = response.data.map(elem => { return { value: elem.id, label: elem.name }; });
            this.queryForm.queryObject.mapId.config.data = this.mapList;
        });
    },
    methods: {
        goDetail(index, row) {
            this.$refs.lessonDetail.show(row.id);
        },
        queryApprovalList(params) {
            if (this.approvalType === 'lesson') {
                return 	reviewLessonList(params);
            } else if (this.approvalType === 'script') {
                return reviewScriptList(params);
            } else if (this.approvalType === 'runPlan') {
                return reviewRunPlanList(params);
            } else { return 	reviewLessonList(params); }
        },
        initLoadCallback(form) {
            form.approvalType = 'lesson';
        },
        pass(index, row) {
            this.$confirm(this.$t('tip.publishTheCourseHint'), this.$t('global.tips'), {
                confirmButtonText: this.$t('global.confirm'),
                cancelButtonText: this.$t('global.cancel'),
                type: 'warning'
            }).then(() => {
                const params = {
                    cityCode: row.cityCode,
                    mapId: row.mapId,
                    name: row.name,
                    prdType: row.prdType
                };
                adminPublishLesson(params, row.id).then(response => {
                    this.$message.success(this.$t('tip.coursePublishSuccessful'));
                    this.doClose();
                }).catch(() => {
                    this.$messageBox(this.$t('tip.coursePublishFailed'));
                });
            });
        },
        noPass(index, row) {
            this.form = {
                labelWidth: '80px',
                items: [
                    { prop: 'explanation', label: this.$t('approval.explanation'), type: 'textarea', required: true}
                ]
            };
            this.dialogFormVisible = true;
            this.rejectId = row.id;
        },
        doClose() {
            this.dialogFormVisible = false;
            this.rejectId = '';
            this.passId = '';
            this.$refs.queryListPage.refresh(true);
            this.$refs.dataform.resetForm();
        },
        rejectConfirm() {
            this.$refs.dataform.validateForm(() => {
                if (this.rejectId && this.approvalType === 'lesson') {
                    rejectedLessonRelease(this.formModel, this.rejectId).then(resp =>{
                        this.$message.success(this.$t('tip.rejectedCourseReleaseApplicationSuccessful'));
                        this.doClose();
                    }).catch(() => {
                        this.$messageBox(this.$t('tip.rejectedCourseReleaseApplicationSuccessful'));
                        this.doClose();
                    });
                } else if (this.rejectId && this.approvalType === 'script') {
                    rejectScript(this.rejectId, this.formModel).then(resp => {
                        this.$message.success(this.$t('approval.rejectScriptSuccess'));
                        this.doClose();
                    }).catch((error) => {
                        this.$messageBox(`${this.$t('approval.rejectScriptFailed')}: ${error.message}`);
                        this.doClose();
                    });
                } else if (this.rejectId && this.approvalType === 'runPlan') {
                    rejectRunPlan(this.rejectId, this.formModel).then(resp => {
                        this.$message.success(this.$t('approval.rejectRunPlanSuccess'));
                        this.doClose();
                    }).catch((error) => {
                        this.$messageBox(`${this.$t('approval.rejectRunPlanFailed')}: ${error.message}`);
                        this.doClose();
                    });
                } else if (this.passId && this.approvalType === 'runPlan') {
                    publishRunPlan(this.passId, this.formModel).then(resp => {
                        if (resp.data.length <= 0) {
                            this.$message.success(this.$t('approval.passedRunPlanSuccess'));
                        } else {
                            this.$messageBox(`${this.$t('approval.passedRunPlanFailed')}: ${resp.data[0]}`);
                        }
                        this.doClose();
                    }).catch(error => {
                        this.$messageBox(`${this.$t('approval.passedRunPlanFailed')}: ${error.message}`);
                        this.doClose();
                    });
                }
            });
        },
        rejectCancel() {
            this.dialogFormVisible = false;
            this.rejectId = '';
            this.textarea = '';
        },
        approvalTypeChange(form) {
            this.approvalType = form.approvalType;
            this.$refs.queryListPage.refresh(true);
        },
        runPlanPreview(index, row) {
            previewRunPlan(row.id).then(resp => {
                const query = {
                    prdType: '01', group: resp.data, mapId: row.mapId, planId: row.id, from:''
                };
                this.$router.push({ path: `${UrlConfig.display}/plan`, query: query });
                launchFullscreen();
            }).catch(error => {
                this.$messageBox(this.$t('tip.createSimulationFaild') + this.$t('global.colon') + error.message);
            });
        },
        runPlanPassed(index, row) {
            this.form = {
                labelWidth: '100px',
                items: [
                    { prop: 'runPlanName', label: this.$t('approval.runPlanName'), type: 'text', required: true}
                ]
            };
            this.dialogFormVisible = true;
            this.passId = row.id;
        },
        scriptPass(index, row) {
            publishScript(row.id).then(resp => {
                this.reloadTable();
                this.$message.success(this.$t('approval.passedScriptSuccess'));
            }).catch(error => {
                this.$messageBox(`${this.$t('approval.passedScriptFailed')}: ${error.message}`);
            });
        },
        scriptPreview(index, row) {
            const mapInfo = this.mapList.find(elem=>{ return elem.id == row.mapId; });
            scriptDraftRecordNotifyNew(row.id).then(resp => {
                const query = { mapId: row.mapId, group: resp.data, scriptId: row.id, try:0, lineCode:mapInfo.lineCode};
                this.$router.push({ path: `${UrlConfig.design.displayNew}/demon`, query });
                launchFullscreen();
            }).catch(error => {
                this.$messageBox(`${this.$t('scriptRecord.createSimulationFail')}: ${error.message}`);
            });
        }
    }
};
</script>
