<template>
    <div class="ability-container">
        <div v-if="!isShowDetail && !isShowReview">
            <div class="table-filter">
                <Select v-model="curAbility" style="width:250px" @on-change="onAbilityFilter">
                    <Option v-for="(item,index) in abilityList" :value="index" :key="index">{{ item.no }} {{ item.name }}</Option>
                </Select>
                <Select v-model="curGroup" style="width:200px" @on-change="onGroupFilter">
                    <Option v-for="(item,index) in groupList" :value="item.groupName" :key="index">{{ item.groupName }}</Option>
                </Select>
                <Input v-model="searchVal" suffix="ios-search" placeholder="搜索姓名..." style="width: auto" @on-change="onSearch" />
                <span class="btn-export" @click="exportData()">
                    <Icon type="md-download" /> 测评结果下载
                </span>
            </div>
            <Table :columns="ablitiesColumn" :data="origin" border :span-method="handleSpan" :loading="tableLoading" ref="table">
                <template slot-scope="{ row, index }" slot="schoolAppraise">
                    <span v-show="row.schoolAppraise === 2" style="color: #007700;">优秀</span>
                    <span v-show="row.schoolAppraise === 1" style="color: orangered;">合格</span>
                    <span v-show="row.schoolAppraise === 0" style="color: red;">不合格</span>
                    <span v-show="row.schoolAppraise === '-'">-</span>
                </template>
                <template slot-scope="{ row, index }" slot="action">
                    <Button type="info" size="small" style="margin-right: 5px;font-size: 12px;" @click="goAppraiseDetail(row)">评价详情</Button>
                    <Button type="primary" size="small" style="margin-right: 5px;font-size: 12px;" @click="goReview(row)">评审</Button>
                </template>
            </Table>
        </div>
        <div class="animated appraise-detail" v-if="isShowDetail">
            <div class="detail-title">
                <Icon type="md-arrow-back" @click="isShowDetail = false" />
                <span>{{ curData.tmdname }} 【 {{ curData.ability }} 】</span>
            </div>
            <Table :columns="appraiseColumns" :data="appraiseArr" border>
                <template slot-scope="{ row, index }" slot="result">
                    <span v-show="row.result === '优秀'" style="color: #007700;">优秀</span>
                    <span v-show="row.result === '合格'" style="color: orangered;">合格</span>
                    <span v-show="row.result === '不合格'" style="color: red;">不合格</span>
                </template>
            </Table>
        </div>
        <Review v-if="isShowReview" :mode="curReviewMode" :reviewData="curData" @goBack="goBack"></Review>

    </div>
</template>
<script>
import excel from '@/utils/excel.js'
import Review from './Review.vue'
import { mapGetters } from 'vuex'
export default {
    components: { Review },
    data() {
        return {
            tableLoading: false,
            spanb: [],
            searchVal: '',
            abilityList: [],
            groupList: [],
            origin: [],
            ablitiesColumn: [
                {
                    title: '教师姓名',
                    key: 'tmdname',
                    width: 140
                },
                {
                    title: '能力点名称',
                    key: 'ability'
                },
                {
                    title: '维度',
                    key: 'dimension',
                    width: 140
                },
                {
                    title: '所属环境',
                    key: 'env',
                    width: 180
                },
                {
                    title: '教研组',
                    key: 'groupName',
                    width: 140
                },
                {
                    title: '校评结果',
                    slot: 'schoolAppraise',
                    key: 'schoolAppraise',
                    width: 140
                },
                {
                    title: '专家抽查',
                    key: 'teacherAppraise',
                    width: 140
                },
                {
                    title: '操作',
                    slot: 'action',
                    key: 'action'
                }
            ],
            appraiseColumns: [
                {
                    title: '评价人',
                    key: 'name'
                },
                {
                    title: '评价类型',
                    key: 'type'
                },
                {
                    title: '评价结果',
                    slot: 'result',
                },
                {
                    title: '评价内容',
                    key: 'content'
                },
                {
                    title: '评价时间',
                    key: 'time'
                },
            ],
            appraiseArr: [],
            curAbility: 0,
            curGroup: '全部教研组',
            isShowDetail: false,
            isShowReview: false,
            curData: false,
            groupData: [],
            curReviewMode: '',
            originList: []
        }
    },
    created() {
        //由DB取得該校所有使用者並放入state.schoolUserList
        this.$store.dispatch('user/getSchoolTeacher').then(
            res => {
                this.handelGroup()
                if (res.code == 0) {
                    this.$Message.error('無法取得使用者資料')
                }
            },
            err => {
                this.$Message.error('user/setSchoolTeacher API error!')
            }
        )

        this.getAllSubs()
    },
    methods: {
        goBack() {
            this.isShowReview = false
            this.searchVal = ''
            this.getAllSubs()
        },
        exportData(type) {
            let downloadData = JSON.parse(JSON.stringify(this.origin))
            downloadData.forEach(i => {
                if (i.schoolAppraise !== '-') {
                    i.schoolAppraise = ['不合格', '合格', '优秀'][i.schoolAppraise]
                }
            })
            const params = {
                title: this.ablitiesColumn.map(i => i.title).slice(0, this.ablitiesColumn.length - 1),
                key: this.ablitiesColumn.map(i => i.key).slice(0, this.ablitiesColumn.length - 1),
                data: downloadData,
                autoWidth: true,
                filename: '评审结果统计'
            }
            excel.export_array_to_excel(params)
        },
        getAllSubs() {
            this.origin = []
            this.tableLoading = true
            this.$api.jyzx.getOtherSubs({
                "tmdid": this.$store.state.userInfo.TEAMModelId,
                "school": this.$store.state.userInfo.schoolCode,
                "all": "1"
            }).then(res => {
                res.groupMembers.forEach(i => {
                    if (i.sub.uploads.length) {
                        let ability = res.abilities.find(j => j.id === i.sub.abilityId)
                        i.dimension = this.$GLOBAL.DIMENSIONS().find(j => j.code === res.abilities.find(k => k.id === i.sub.abilityId).dimension).val
                        i.ability = ability.no + ' ' + ability.name
                        i.time = i.sub.uploads.length ? this.$tools.formatTime(i.sub.uploads[0].time) : '-'
                        i.env = ability.env
                        i.name = i.tmdname
                        i.id = ability.id
                        i.teacherAppraise = '未抽查'
                        i.schoolAppraise = i.sub.otherScore.find(i => i.roleType === 'school') ? i.sub.otherScore.find(i => i.roleType === 'school').score : '-'
                        this.origin.push(i)
                    }
                })
                this.tableLoading = false
                this.originList = JSON.parse(JSON.stringify(this.origin))
                console.log(res.groupMembers);
                console.log(this.origin)
                console.log(res.groupMembers.map(i => i.sub.uploads))
                this.doGroup()
            })
        },
        //转分组模式数据结构
        handelGroup() {
            this.teachers.forEach(item => {
                item.groupName = item.groupName || '默认组别'
            })
            let groupRes = this.$jsFn.groupBy(this.teachers, 'groupName')
            this.groupData.length = 0
            for (let index in groupRes) {
                this.groupData.push({
                    groupName: groupRes[index][0].groupName || '默认组别',
                    groupId: groupRes[index][0].groupId,
                    teachers: groupRes[index]
                })
            }
            this.groupData.sort((a, b) => {
                return parseInt(a.groupId) - parseInt(b.groupId)
            })
            this.groupData.unshift({
                groupName: '全部教研组',
                groupId: '-1',
                teachers: []
            })
            this.groupList = this.groupData
            console.log('处理分组数据', this.groupData)
        },
        goAppraiseDetail(data) {
            this.appraiseArr = data.sub.otherScore.map(i => {
                return {
                    name: i.tmdname,
                    result: ['不合格', '合格', '优秀'][i.score],
                    content: i.replyIds[0],
                    type: '互评',
                    time: this.$tools.formatTime(i.time)
                }
            })
            this.appraiseArr.unshift({
                name: data.tmdname,
                result: ['不合格', '合格', '优秀'][data.sub.self],
                content: '-',
                type: '自评',
                time: this.$tools.formatTime(data.sub.uploads[0].time)
            })
            this.curData = data
            this.isShowDetail = true
        },
        goReview(data) {
            if (data.tmdid === this.$store.state.userInfo.TEAMModelId) {
                this.$Message.warning('您自己的材料只能由其它管理员进行校评！')
                return
            }
            // this.curData = data
            let reviewData = {
                id: data.sub.abilityId,
                uploads: data.sub.uploads,
                targetId: data.tmdid,
                targetName: data.tmdname
            }
            this.curData = reviewData
            this.isShowReview = true
            this.curReviewMode = 'school'
        },
        getAllAbilities() {
            return new Promise((r, j) => {
                let findParams = {
                    "scope": "school",
                    "code": this.$store.state.userInfo.schoolCode,
                    "dimension": "",
                    "status": 1
                }
                this.$api.ability.FindVolumes(findParams).then(res => {
                    if (!res.error) {
                        res.abilities.unshift({
                            name: '全部能力点',
                            no: '',
                            id: ''
                        })
                        this.abilityList = res.abilities.sort(function(s, t) {
							var a = s.no.toLowerCase();
							var b = t.no.toLowerCase();
							if (a.length === 2) {
								a = a.slice(0, a.length - 1) + '0' + a.slice(-1)
							}
							if (b.length === 2) {
								b = b.slice(0, b.length - 1) + '0' + b.slice(-1)
							}

							if (a < b) return -1;
							if (a > b) return 1;
							return 0;
						});
                    } else {
                        this.$Message.warning(res.error);
                    }
                }).catch(err => {
                    this.$Message.error(err);
                })
            })
        },
        handleSpan({
            row,
            column,
            rowIndex,
            columnIndex
        }) {
            if (columnIndex === 0) {
                if (this.spanb[rowIndex]) {
                    return {
                        rowspan: this.spanb[rowIndex],
                        colspan: 1
                    }
                } else {
                    return {
                        rowspan: 0,
                        colspan: 1
                    }
                }
            }

        },
        doGroup() {
            let contactDotb = 0;
            let spanb = [];
            this.origin.forEach((item, index) => {
                if (index === 0) {
                    console.log(spanb)
                    spanb.push(1)
                } else {
                    if (item.name === this.origin[index - 1].name) {
                        spanb[contactDotb] += 1;
                        spanb.push(0)
                    } else {
                        contactDotb = index
                        spanb.push(1)
                    }
                }
            })
            this.spanb = spanb;
        },

        onAbilityFilter(val) {
            if (val === 0) {
                if (this.curGroup === '全部教研组') {
                    this.origin = this.originList
                } else {
                    this.origin = this.originList.filter(i => i.groupName === this.curGroup)
                }
            } else {
                let curAbilityId = this.abilityList[val].id
                if (this.curGroup === '全部教研组') {
                    this.origin = this.originList.filter(i => i.id === curAbilityId)
                } else {
                    this.origin = this.originList.filter(i => i.id === curAbilityId && i.groupName === this.curGroup)
                }
            }
            this.doGroup()
        },

        onGroupFilter(val) {
            if (val === '全部教研组') {
                if (this.curAbility === 0) {
                    this.origin = this.originList
                } else {
                    let curAbilityId = this.abilityList[this.curAbility].id
                    this.origin = this.originList.filter(i.id === curAbilityId)
                }
            } else {
                if (this.curAbility === 0) {
                    this.origin = this.originList.filter(i => i.groupName === val)
                } else {
                    let curAbilityId = this.abilityList[this.curAbility].id
                    this.origin = this.originList.filter(i => i.groupName === val && i.id === curAbilityId)
                }
            }
            this.doGroup()
        },

        onSearch(val) {
            this.origin = this.originList.filter(i => i.name.indexOf(this.searchVal) > -1)
        },
    },
    mounted() {


        this.getAllAbilities()
    },
    computed: {
        ...mapGetters({
            teachers: 'user/getSchoolUserJoined', // 取得已加入此學校的使用者
        })
    },
}
</script>
<style lang="less" src="./Ability.less" scoped></style>
