<template>
    <div class="mark-setting-wrap dark-iview-form">
        <div v-show="!isSetting" class="publish-status-box">
            <Icon type="ios-information-circle-outline" class="tips-icon" />
            <p class="status-text">
                <span style="font-size:16px;color:white">暂未发布阅卷任务</span>
            </p>
            <span class="setting-btn" @click="isSetting = !isSetting">发布任务</span>
        </div>
        <vuescroll v-show="isSetting">
            <!-- 基础设置 -->
            <div class="setting-block">
                <!-- <p class="block-title">
                    {{$t('learnActivity.mark.baseSetting')}}
                </p> -->
                <div class="setting-content">
                    <Form ref="baseSetting" :model="setting" label-colon :label-width="100" :rules="ruleValidate">
                        <Row>
                            <!-- 开始时间 -->
                            <Col :md="24" :lg="24" :xl="12" :xxl="8">
                            <FormItem label="开始时间" class="setting-item-wrap" prop="startTime">
                                <DatePicker :options="dateOpt" class="attr-value-wrap" type="datetime" format="yyyy/MM/dd HH:mm" v-model="startTime" split-panels :placeholder="$t('learnActivity.createEv.sTimeHolder')" style="width:100%" @on-change="getDate($event,0)"></DatePicker>
                            </FormItem>
                            </Col>
                            <!-- 结束时间 -->
                            <Col :md="24" :lg="24" :xl="12" :xxl="8">
                            <FormItem label="结束时间" class="setting-item-wrap" prop="endTime">
                                <DatePicker :options="dateOpt1" class="attr-value-wrap" type="datetime" format="yyyy/MM/dd HH:mm" v-model="endTime" split-panels :placeholder="$t('learnActivity.createEv.eTimeHolder')" style="width:100%" @on-change="getDate($event,1)"></DatePicker>
                            </FormItem>
                            </Col>
                            <!-- 分配方式 -->
                            <Col :md="24" :lg="24" :xl="12" :xxl="8">
                            <FormItem label="分配方式" class="setting-item-wrap" prop="mode">
                                <RadioGroup v-model="setting.mode" style="color:white">
                                    <Radio label="full">按人分配</Radio>
                                    <Radio disabled label="qu" style="margin-left:20px">按题分配 (开发中)</Radio>
                                </RadioGroup>
                            </FormItem>
                            </Col>
                            <!-- 阅卷次数 -->
                            <Col :md="24" :lg="24" :xl="12" :xxl="8">
                            <FormItem label="阅卷次数" class="setting-item-wrap" prop="num">
                                <!-- <InputNumber :max="2" class="attr-value-wrap" :min="1" v-model="setting.point"></InputNumber> -->
                                <RadioGroup v-model="setting.num" style="color:white">
                                    <Radio :label="1">单评制</Radio>
                                    <Radio disabled :label="2" style="margin-left:0px">双评制 (开发中)</Radio>
                                    <Radio disabled :label="3" style="margin-left:0px">三评制 (开发中)</Radio>
                                </RadioGroup>
                            </FormItem>
                            </Col>
                            <!-- 启用异常处理 -->
                            <Col :md="24" :lg="24" :xl="12" :xxl="8">
                            <FormItem label="异常申报" class="setting-item-wrap" prop="isErr">
                                <RadioGroup v-model="setting.isErr" style="color:white">
                                    <Radio :label="1">是</Radio>
                                    <Radio :label="0" style="margin-left:20px">否</Radio>
                                </RadioGroup>
                            </FormItem>
                            </Col>
                            <!-- 启用仲裁 -->
                            <Col :md="24" :lg="24" :xl="12" :xxl="8" v-show="setting.num > 1">
                            <FormItem label="启用仲裁" class="setting-item-wrap" prop="isArb">
                                <RadioGroup v-model="setting.isArb" style="color:white">
                                    <Radio :label="1">是</Radio>
                                    <Radio :label="0" style="margin-left:20px">否</Radio>
                                </RadioGroup>
                            </FormItem>
                            </Col>

                        </Row>
                    </Form>
                </div>
            </div>
            <div class="subject-wrap">
                <span v-for="(item,index) in subjects" :key="index" :class="index == curSubIndex ? 'filter-tab-item filter-tab-item-active':'filter-tab-item'" @click="curSubIndex = index">
                    {{item.name}}
                </span>
            </div>

            <div class="setting-block" id="teacher-wrap">
                <!-- <p class="block-title">
                    {{$t('learnActivity.mark.markRole')}}
                </p> -->
                <div class="setting-content" id="teacher-wrap-content">
                    <Form ref="teacherSet" :model="subsInfo" label-colon :label-width="100" :rules="ruleValidate" style="margin-top:15px">
                        <Row>
                            <Col :md="24" :lg="24" :xl="24" :xxl="24" v-if="setting.isErr">
                            <!-- 异常处理老师 -->
                            <FormItem :label="$t('learnActivity.mark.errRole')" class="setting-item-wrap" prop="err">
                                <Select v-model="subsInfo.err" style="width:400px" multiple>
                                    <Option v-for="(item,index) in teacherList" :value="item.id" :key="index">{{item.name}}</Option>
                                </Select>
                            </FormItem>
                            </Col>
                            <Col :md="24" :lg="24" :xl="24" :xxl="24" v-if="setting.isArb">
                            <!-- 仲裁老师 -->
                            <FormItem :label="$t('learnActivity.mark.arb')" class="setting-item-wrap" prop="arb">
                                <Select v-model="subsInfo.arb" style="width:400px" multiple>
                                    <Option v-for="(item,index) in teacherList" :value="item.id" :key="index">{{item.name}}</Option>
                                </Select>
                            </FormItem>
                            </Col>
                            <Col :md="24" :lg="24" :xl="24" :xxl="24">
                            <!-- 阅卷老师 -->
                            <FormItem :label="$t('learnActivity.mark.markRole')" class="setting-item-wrap dark-iview-table" prop="markers">
                                <Table :columns="teaCol" :data="markers" border :no-data-text="$t('learnActivity.mark.noTea')">
                                    <template slot-scope="{ row }" slot="header">
                                        <PersonalPhoto :name="row.name" :picture="row.picture" />
                                    </template>
                                    <template slot-scope="{ row,index }" slot="action">
                                        <Button v-show="setting.mode == 'qu'" type="info" size="small" style="margin-right:10px" @click="setQuStatus = true">题号</Button>
                                        <Button type="error" size="small" @click="removeMarker(row,index)">{{$t('learnActivity.mark.remove')}}</Button>
                                    </template>
                                    <template slot-scope="{ row }" slot="count">
                                        <span>{{`${row.count}/${evInfo.stuCount}`}}</span>
                                    </template>
                                    <template slot-scope="{ row }" slot="qu">
                                        <span :style="{color:setting.mode == 'full' ? '#2db7f5' : row.qu.length ? '#FFFFFF' : '#ed4014'}">
                                            {{setting.mode == 'full' ? '所有题目' : row.qu.length ? row.qu.join(',') : '暂未设置'}}
                                        </span>
                                    </template>
                                </Table>
                                <span class="add-tea-btn" @click="addTeaStatus = true">
                                    <Icon type="md-add" />
                                    {{$t('learnActivity.mark.addTea')}}
                                </span>
                            </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </div>
            </div>
        </vuescroll>
        <Modal v-model="addTeaStatus" :title="$t('learnActivity.mark.addTeaTitle')" class-name="dark-iview-modal dark-iview-table" @on-ok="okAddTea" :width="1000">
            <Table ref="sltTea" :columns="teacherCol" :data="teacherList" style="margin-top:10px" @on-selection-change="(selection)=>{sltTeachers = selection}" height="600">
                <template slot-scope="{ row }" slot="picture">
                    <PersonalPhoto :name="row.name" :picture="row.picture" />
                </template>
                <template slot-scope="{ row }" slot="job">
                    <span>{{row.job || '--'}}</span>
                </template>
            </Table>
        </Modal>
        <Modal v-model="setQuStatus" title="题号设置" class-name="dark-iview-modal dark-iview-table" @on-ok="okSetQu" :width="1000">

        </Modal>
    </div>
</template>
<script>
import MarkProgress from '../echarts/MarkProgress.vue'
import ScanProgress from '../echarts/ScanProgress.vue'
import CptCount from '../echarts/CptCount.vue'
import PersonalPhoto from "@/components/public/personalPhoto/Index.vue"
export default {
    model: {
        prop: 'isShow',
        event: 'statusChange'
    },
    props: {
        evInfo: {
            type: Object,
            default: () => {
                return {
                    id: '',
                    name: ''
                }
            }
        },
        isShow: Boolean //父组件是否显示保存按钮 对应isSetting的值
    },
    data() {
        let _this = this
        return {
            isSetting: false,
            ruleValidate: {
                startTime: [
                    { required: true, type: 'number', message: '请设置阅卷开始时间', trigger: 'blur' }
                ],
                endTime: [
                    { required: true, type: 'number', message: '请设置阅卷结束时间', trigger: 'blur' }
                ],
                mode: [
                    { required: true, message: '请设置分配方式', trigger: 'change' }
                ],
                num: [
                    { required: true, type: 'number', message: '请设置阅卷次数', trigger: 'change' }
                ],
                isErr: [
                    { required: true, type: 'number', message: '请设置是否有异常申报功能', trigger: 'change' }
                ],
                isArb: [
                    { required: true, type: 'number', message: '请设置分差超过1/6的题目是否需要仲裁', trigger: 'change' }
                ],
                arb: [
                    { required: true, type: 'array', message: '请设置仲裁老师', trigger: 'change' }
                ],
                err: [
                    { required: true, type: 'array', message: '请设置异常处理老师', trigger: 'change' }
                ],
                markers: [
                    { required: true, type: 'array', message: '请设置阅卷老师', trigger: 'change' }
                ],
            },
            setQuStatus: false,
            curSubIndex: 0,
            setting: {
                id: '',
                code: '',
                name: '',
                owner: 'school',
                school: '',
                creatorId: '',
                scope: 'school',
                startTime: '',
                createTime: '',
                endTime: '',
                scode: '',//评测的分区键
                mode: 'full',//阅卷模式 按人 full  按题 qu
                num: 1,//阅卷次数
                isErr: 0, //是否有异常处理流程 0/1
                isArb: 0, //是否有仲裁处理流程 0/1
                subs: [
                    {
                        id: '',//科目id,
                        name: '',//科目名称
                        markers: [ //阅卷老师
                            // {
                            //     id: '',
                            //     name:'',
                            //     count: 0, //阅卷量 （学生人数*阅卷次数/阅卷老师人数）
                            //     qu:[]    //如果是按题分配，这里保存批阅的题号。按人分配默认为空数组
                            // }
                        ],
                        err: [],//处理异常卷人员
                        arb: [],//处理冲裁卷人员
                        // point: '',//（仲裁条件）固定条件，只需要设置是否启用仲裁
                    }
                ],

            },
            addTeaStatus: false,
            teacherList: [],
            sltTeachers: [],
            teacherCol: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: ' ',
                    slot: 'picture',
                    align: 'center ',
                    width: '120'
                },
                {
                    title: this.$t('cusMgt.teaName'),
                    key: 'name',
                    align: 'center '
                },
                {
                    title: 'id',
                    key: 'id',
                    align: 'center '
                },
                {
                    title: this.$t('cusMgt.job'),
                    slot: 'job',
                    align: 'center '
                }
            ],
            teaCol: [
                {
                    title: ' ',
                    slot: 'header',
                    align: 'center'
                },
                {
                    title: 'id',
                    key: 'id',
                    align: 'center'
                },
                {
                    title: this.$t('learnActivity.mark.name'),
                    key: 'name',
                    align: 'center'
                },
                {
                    title: this.$t('learnActivity.mark.markNum'),
                    slot: 'count',
                    align: 'center'
                },
                {
                    title: '批阅题号',
                    slot: 'qu',
                    align: 'center'
                },
                {
                    title: '',
                    slot: 'action',
                    align: 'center'
                },
            ],
            dateOpt: {
                disabledDate(date) {
                    return date && date.valueOf() < Date.now() - 86400000
                }
            },
            dateOpt1: {
                disabledDate(date) {
                    let d = _this.setting.startTime ? _this.setting.startTime : Date.now()
                    return d && d > date.valueOf() + 86400000
                }
            },
            startTime: '',
            endTime: ''
        }
    },
    components: {
        MarkProgress, CptCount, ScanProgress, PersonalPhoto
    },
    methods: {
        //移除阅卷老师
        removeMarker(row, index) {
            this.$Modal.confirm({
                title: '移除老师',
                content: `是否确认移除${row.name}?`,
                okText: '是',
                cancelText: '否',
                onOk: () => {
                    this.markers.splice(index, 1)
                }
            })

        },
        //确认设置阅卷题号
        okSetQu() {

        },
        /**
         * 将日期控件时间格式转成时间戳
         * @param value
         * @param flag 0:开始时间 1：结束时间
         */
        getDate(value, flag) {
            if (value.indexOf('00:00') > 0) {
                value = value.replace('00:00', '23:59:59')
            }
            if (flag == 0) {
                this.startTime = value
                this.setting.startTime = new Date(value).getTime()
                if (this.setting.startTime >= this.setting.endTime) {
                    this.endTime = undefined
                    this.setting.endTime = undefined
                }
            } else if (flag == 1) {
                this.endTime = value
                this.setting.endTime = new Date(value).getTime()
            }
        },
        saveSetting() {
            let full = true
            //验证基础信息设置
            this.$refs['baseSetting'].validate((valid) => {
                if (!valid) {
                    full = false
                    this.$Message.error('请完成阅卷基础设置')
                }
            })
            if (!full) return
            // 验证学科阅卷相关老师设置 待完善，目前验证了当前学科
            this.$refs['teacherSet'].validate((valid) => {
                if (!valid) {
                    full = false
                    this.$Message.error('阅卷和相关老师设置')
                }
            })
            if (!full) return

            // 通过验证，保存设置
            this.setting.code = this.$store.state.userInfo.schoolCode
            console.log(this.setting)
            this.$api.mark.UpsertMarkSet(this.setting).then(
                res => {
                    this.$Message.success('保存成功！')
                },
                err => {
                    this.$Message.error('保存失败！')
                }
            )
        },
        //确认添加老师
        okAddTea() {
            let subject = this.setting.subs.find(item => {
                return this.subjects[this.curSubIndex].id == item.id
            })
            console.log('点前学科', subject)
            if (subject) {
                let ids = subject.markers.map(item => {
                    return item.id
                })
                this.sltTeachers.forEach(item => {
                    if (ids.indexOf(item.id) == -1) {
                        subject.markers.push({
                            id: item.id,
                            name: item.name,
                            qu: []
                        })
                    }
                })
                let more = this.evInfo.stuCount % subject.markers.length
                subject.markers.map((item, index) => {
                    if (index < more) {
                        item.count = Math.ceil(this.evInfo.stuCount / subject.markers.length)
                    } else {
                        item.count = Math.floor(this.evInfo.stuCount / subject.markers.length)
                    }

                })
            }
            console.log(this.setting)
            this.cancel()
        },
        cancel() {
            this.sltTeachers = []
            this.$refs.sltTea.selectAll(false)
        },
        //查询评测阅卷配置信息
        findSettingInfo() {
            let requestData = {
                id: this.evInfo.id,
                code: this.$store.state.userInfo.schoolCode
            }
            this.$api.mark.FindById(requestData).then(
                res => {
                    if (res.correct) {
                        this.setting = res.correct
                        this.isSetting = true
                    } else {
                        this.isSetting = false
                        if (this.evInfo.subjects) {
                            this.setting.id = this.evInfo.id
                            this.setting.name = this.evInfo.name
                            this.setting.school = this.$store.state.userInfo.schoolCode
                            this.setting.code = this.$store.state.userInfo.schoolCode
                            this.setting.scode = this.evInfo.code
                            this.setting.creatorId = this.$store.state.userInfo.TEAMModelId
                            this.setting.createTime = new Date().getTime()
                            this.setting.startTime = new Date().getTime()
                            this.setting.endTime = new Date().getTime() + 86400000 * 2
                            this.setting.subs = []
                            this.evInfo.subjects.forEach((item) => {
                                this.setting.subs.push({
                                    id: item.id,
                                    name: item.name,
                                    markers: []
                                })
                            })
                        }
                    }
                },
                err => {

                }
            ).finally(() => {

            })

        }
    },
    created() {
        this.$store.dispatch('teachers/getTeacherList').then(res => {
            this.teacherList = this.$store.state.teachers.teacherList.filter(item => {
                return item.status == 'join'
            })
        })
        //初始化起止时间
        this.startTime = new Date()
        this.setting.startTime = new Date().getTime()
        this.endTime = new Date(new Date(new Date().toLocaleDateString()).getTime() + 3 * 24 * 60 * 60 * 1000 - 1)
        this.setting.endTime = new Date().getTime() + 3 * 24 * 60 * 60 * 1000 - 1
    },
    watch: {
        'evInfo.id': {
            handler(n, o) {
                console.log(this.evInfo)
                if (this.evInfo.id) {
                    this.findSettingInfo()
                } else {
                    this.$Message.warning('暂无评测id')
                }

            },
            deep: true
        },
        isSetting: {
            handler(n, o) {
                console.log('watch', n, o)
                this.$emit('statusChange', this.isSetting)
            },
            immediate: true
        }
    },
    computed: {
        //当前科目的配置信息
        subsInfo() {
            let info = {
                arb: [],
                err: [],
                markers: []
            }
            if (this.setting.subs && this.subjects && this.subjects[this.curSubIndex]) {
                let subject = this.setting.subs.find(item => {
                    return item.id == this.subjects[this.curSubIndex].id
                })
                if (subject) {
                    info = subject
                }
            }
            return info
        },
        //从基础信息获取当前学科阅卷老师
        markers() {
            let arr = []
            if (this.setting.subs && this.subjects && this.subjects[this.curSubIndex]) {
                let subject = this.setting.subs.find(item => {
                    return item.id == this.subjects[this.curSubIndex].id
                })
                if (subject) {
                    arr = subject.markers
                }
            }
            return arr
        },
        //当前评测科目
        subjects() {
            if (this.evInfo && this.evInfo.subjects) {
                return this.evInfo.subjects
            } else {
                return []
            }
        }
    }
}
</script>
<style scoped lang="less">
.publish-status-box {
    width: 360px;
    height: 315px;
    background: #37363a;
    margin: 60px auto;
    padding: 20px;
    border-radius: 20px;
    position: relative;
    box-shadow: 0 0px 10px 0px rgb(0 0 0);

    &:hover {
        // background: #3c3c41;
    }
    .tips-icon {
        display: block;
        margin: auto;
        margin-top: 6%;
        font-size: 80px;
        margin-right: 5px;
        color: #eeeeee;
    }
    .status-text {
        color: #ccc;
        text-align: center;
        margin-top: 40px;
        font-size: 14px;
    }
    .setting-btn {
        display: block;
        color: white;
        background: #2db7f5;
        width: 120px;
        padding: 4px 0px;
        border-radius: 4px;
        position: absolute;
        text-align: center;
        bottom: 50px;
        left: 50%;
        font-size: 16px;
        margin-left: -60px;
        cursor: pointer;
    }
}
.subject-wrap {
    margin-top: 30px;
    color: #a5a5a5;
}
#teacher-wrap {
    margin-top: 0px;
}
#teacher-wrap-content {
    margin-top: 0px;
    border-top-left-radius: 0px;
}
.filter-tab-item {
    display: inline-block;
    width: 80px;
    text-align: center;
    background: #1a191c;
    color: #a5a5a5;
    margin-right: 1px;
    border-top-right-radius: 15px;
    padding: 2px 0px;
    font-size: 12px;
    cursor: pointer;
}
.filter-tab-item-active {
    background: #2b2a2f;
    color: white;
}
.mark-setting-wrap {
    height: calc(100% - 45px);
    padding-bottom: 5px;
}
.setting-block:first-child {
    margin-top: 15px;
}

.setting-content {
    background: #2b2a2f;
    box-shadow: 1px 1px 13px #141414;
    // border: 1px solid rgba(98, 97, 101, 0.4);
    padding: 10px;
    border-radius: 5px;
    margin-right: 12px;
    margin-top: 5px;
}
.setting-item-wrap {
    padding-right: 15px;
}
.attr-value-wrap {
    width: 90%;
    max-width: 180px;
}
.block-title {
    color: white;
    border-left: 2px solid #1cc0f3;
    line-height: 14px;
    padding-left: 5px;
    user-select: none;
}
.setting-block {
    margin-top: 30px;
}
.count-wrap {
    flex: 1;
    text-align: center;
    color: white;
    width: 200px;
    position: relative;
    .count-icon {
        color: #a5a5a5;
    }
    .count-num {
        font-size: 40px;
    }
    .count-label {
        color: #a5a5a5;
    }
}
.count-wrap::after {
    content: "";
    width: 2px;
    height: 30px;
    background: #a5a5a5;
    position: absolute;
    right: 0px;
    top: 50%;
    margin-top: -15px;
}
.count-wrap:last-child::after {
    display: none;
}
.count-content {
    display: flex;
}
.chart-wrap {
    flex: 1;
    color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
.role-item-wrap {
    margin: 5px 0px;
    .role-label {
        color: #a5a5a5;
        display: inline-block;
        // width: 120px;
        text-align: right;
        padding-right: 10px;
    }
}
.scan-tea-table {
    width: calc(100% - 120px);
    display: inline-block;
}
.add-tea-btn {
    color: white;
    margin-top: 8px;
    display: inline-block;
    cursor: pointer;
    user-select: none;
}
</style>