<style lang="less" scoped>
    @import './AddStudent.less';
</style>
<style lang="less">
    .add-student .ivu-input, .add-student .ivu-input-number {
        background: none;
        border: none;
        border-bottom: 1px solid #505050;
        border-radius: 0px;
        color: white;
        font-size: 16px;
    }

    .add-student .ivu-input-number{
        width: 100%;
    }

    .add-student .ivu-modal-footer {
        border: none;
    }
    .add-student .ivu-form-item-label {
        color: #929292;
    }

    .add-student .ivu-form-item-required .ivu-form-item-label:before {
        color: #6DE2C4;
    }

    .add-student .ivu-form-item-error .ivu-input:focus {
        border: none;
    }

    .add-student .ivu-input-group-prepend {
        border: none;
        background: none;
        color: white;
        font-size: 14px;
    }

    .add-student .ivu-checkbox-wrapper {
        float: right;
        color: #929292;
    }

    .add-student .ivu-checkbox-inner {
        background: none;
        border-color: #6DE2C4;
    }

    .add-student .ivu-checkbox-checked .ivu-checkbox-inner:after {
        border-color: #6DE2C4;
    }

    .account-form .ivu-select-selection {
        border-color: #505050;
    }

        .account-form .ivu-select-selection:hover {
            border-color: #57a3f3;
        }

    .account-form .ivu-select-input {
        color: white;
        font-size: 16px;
    }

</style>
<template>

    <div class="account-form dark-iview-form dark-iview-select">
        <!--新增学生表单-->
        <Form ref="studentInfoForm" :model="studentInfo" label-position="top" :rules="ruleValidate" :show-message="showError" v-if="bizType == 1">
            <!-- ID -->
            <FormItem :label="$t('stuAccount.accountInfo')" prop="id">
                <Input v-model="studentInfo.id" :placeholder="$t('stuAccount.accountHolder')" @on-change="setPassword(same)">
                <!-- <span slot="prepend">{{schoolCode}}#</span> 前方 -->
                </Input>
                <input type="text" style="position:fixed;z-index:-10000;width:0;border:none"/>
            </FormItem>
            <!-- 密碼 -->
            <FormItem :label="$t('stuAccount.passwordInfo')" prop="pw">
                <input type="password" style="position:fixed;z-index:-10000;width:0;border:none"/>
                <Input v-model="studentInfo.pw" type="password" password :placeholder="$t('stuAccount.passwordHolder')"></Input>
                <Checkbox v-model="same" @on-change="setPassword">{{$t('stuAccount.isSame')}}</Checkbox>
            </FormItem>
            <!-- 姓名 -->
            <FormItem :label="$t('stuAccount.stuName')" prop="name">
                <Input v-model="studentInfo.name" :placeholder="$t('stuAccount.stuNameHolder')"></Input>
            </FormItem>
            <!-- 學制、學級 -->
            <div style="display:flex;justify-content: space-between;">
                <!-- 學制 -->
                <FormItem :label="$t('stuAccount.periodInfo')" style="width:45%">
                    <Select v-model="searchPeriod" style="width: 100%;" :placeholder="$t('stuAccount.periodHolder')" clearable >
                        <Option v-for="(item, index) in periods" :value="item.id" :key="index">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <!-- 學級 -->
                <FormItem :label="$t('stuAccount.gradeInfo')" style="width:45%">
                    <Select v-model="searchGrade" style="width: 100%; margin-left: 5px" :placeholder="$t('stuAccount.gradeHolder')" :not-found-text="$t('stuAccount.sltPdFirst')" clearable>
                        <Option v-for="(item, index) in filterGrades" :value="item.id" :key="index">{{ item.name }}</Option>
                    </Select>
                </FormItem>
            </div>
            <!-- 教室資訊 -- 班级 -->
            <FormItem :label="$t('stuAccount.classroomInfo')" prop="classId">
                <Select filterable style="width:100%" :placeholder="$t('stuAccount.classroomInfoHolder')" v-model="studentInfo.classId" clearable>
                    <Option v-for="(item,index) in filterClasses" :value="item.id" :key="index" @click.native="setCurrentClassDetail(item)">{{ item.name }}</Option>
                </Select>
                <span style="float:right;color:#6DE2C4;cursor:pointer;text-decoration:underline;font-size:12px;" @click="createClassroom">{{$t('stuAccount.newClassroom')}}</span>
            </FormItem>
            <div style="display:flex;justify-content: space-between;">
                <!-- 座位號 -->
                <FormItem :label="$t('stuAccount.stuSeatNo')" prop="no" style="width:45%">
                    <InputNumber v-model="studentInfo.no" :min="1" :placeholder="$t('stuAccount.stuSeatNoHolder')"></InputNumber>
                </FormItem>
                <!-- 學級 -->
                <FormItem :label="$t('stuAccount.gradeInfo')" prop="gradeCode" style="width:45%">
                    <span style="color:white;">{{ gradeName }}</span>
                </FormItem>
            </div>
            <div style="display:flex;justify-content: space-between;">
                <!-- 學年度 -->
                <FormItem :label="$t('stuAccount.academicYear')" prop="year" style="width:45%">
                    <InputNumber v-model="studentInfo.year" :editable="false"></InputNumber>
                </FormItem>
            </div>
        </Form>

        <!--修改信息表单-->
        <Form ref="updateForm" :model="editStudentInfo[0]" label-position="top" :rules="ruleValidate" :show-message="showError" v-if="bizType == 2">
            <FormItem :label="$t('stuAccount.chooseInfo')" v-if="editStudentInfo.length > 1">
                <span class="account-item" :key="index" v-for="(item,index) in editStudentInfo">{{item.id}}{{index < editStudentInfo.length - 1 ? "， ":""}}</span>
            </FormItem>
            <FormItem :label="$t('stuAccount.chooseNum') + editStudentInfo.length + $t('stuAccount.numUnit')" v-if="editStudentInfo.length > 1">
            </FormItem>
            <FormItem :label="$t('stuAccount.accountInfo')" prop="id" v-if="editStudentInfo.length == 1">
                <Input v-model="editStudentInfo[0].id" disabled :placeholder="$t('stuAccount.accountHolder')" @on-change="setPassword(same)"></Input>
            </FormItem>
            <FormItem :label="$t('stuAccount.passwordInfo')" prop="pw" v-if="editStudentInfo.length == 1">
                <Input v-model="editStudentInfo[0].pw" disabled type="text" :placeholder="$t('stuAccount.passwordHolder')">
                <span slot="append" size="small" style="cursor:pointer;" @click="setPassword(true)">{{$t('stuAccount.resetPw')}}</span>
                </Input>
            </FormItem>
            <FormItem :label="$t('stuAccount.stuName')" prop="name" v-if="editStudentInfo.length == 1">
                <Input v-model="editStudentInfo[0].name" :placeholder="$t('stuAccount.stuNameHolder')"></Input>
            </FormItem>
            <FormItem :label="$t('stuAccount.classroomInfo')" prop="classId">
                <Select filterable style="width:100%" v-model="editStudentInfo[0].classId" :placeholder="$t('stuAccount.classroomInfoHolder')" clearable>
                    <Option v-for="(item) in classes" :value="item.id" :key="item.id" @click.native="setCurrentClassDetail(item)">{{ item.name }}</Option>
                </Select>
                <span style="float:right;color:#6DE2C4;cursor:pointer;text-decoration:underline;" @click="createClassroom">{{$t('stuAccount.newClassroom')}}</span>
            </FormItem>
            <div style="display:flex;justify-content: space-between;" v-if="editStudentInfo.length == 1">
                <FormItem :label="$t('stuAccount.stuSeatNo')" prop="no" style="width:45%">
                    <Input type="number" number v-model="editStudentInfo[0].no" :min="1" :placeholder="$t('stuAccount.stuSeatNoHolder')"></Input>
                </FormItem>
                <FormItem :label="$t('stuAccount.gradeInfo')" prop="gradeCode" style="width:45%">
                    <span style="color:white;">{{ gradeName }}</span>
                </FormItem>
            </div>
            <div style="display:flex;justify-content: space-between;" v-if="editStudentInfo.length == 1">
                <!-- 學年度 -->
                <FormItem :label="$t('stuAccount.academicYear')" prop="year" style="width:45%">
                    <Input v-model="editStudentInfo[0].year" disabled></Input>
                </FormItem>
            </div>
        </Form>

        <Button @click="confirm()" :loading="isLoading" type="success" :class="isFull?'confirm-btn confirm-btn-active':'confirm-btn'">{{isFull ? $t('stuAccount.submitActive'): bizType == 1 ? $t('stuAccount.submitAccount'):$t('stuAccount.submitActive')}}</Button>
    </div>
</template>
<script>
    import fn from '@/utils/js-fn.js'
    import { mapGetters } from 'vuex'
// import { delete } from 'vuedraggable'

    export default {
        props: {
            isShow: {
                type: Boolean,
                default: false
            },
            schoolCode: {
                type: String,
                default: ''
            },
            editStudentInfo: {
                type: Array,
                default: () => {
                    return [
                        {
                            classId: ''
                        }
                    ]
                }
            },
            bizType: {
                type: Number,
                default: 0 //1新增 2编辑
            }
        },
        data() {
            const validateSeatNo = (rule, value, callback) => {
                let flag = (value == null || typeof value == 'undefined' || value === '')
                if (flag && (this.studentInfo.classId != null && typeof this.studentInfo.classId != 'undefined' && this.studentInfo.classId !=='')) {
                    callback(new Error('学生座位号不能为空'));                    
                } else {
                    callback();
                }
            };
            const validateclassId = (rule, value, callback) => {
                if (value === '' &&  (this.studentInfo.no != null && typeof this.studentInfo.no != 'undefined' && this.studentInfo.no !=='')) {
                    callback(new Error('班级资讯不能为空'));
                } else {
                    callback()
                }
            };
            const validatePw = (rule, value, callback) => {
                if(this.bizType == 1 && value === ''){
                    callback(new Error('密码不能为空'));
                } else {
                    callback()
                }
            };            
            return {
                fn,
                isLoading: false,
                test: true,
                showError: false,
                isFull: false,
                classroomList: [],
                same: '',
                list: [],
                studentInfo: {
                    name: '',
                    id: '',
                    no: null,
                    classId:'',
                    className:'',
                    // periodCode:'',
                    // gradeCode:'',
                    pw: '',
                    year: new Date().getFullYear()
                },
                gradeName:'',
                ruleValidate: {
                    id: [
                        { required: true, message: '账号不能为空', trigger: 'blur' }
                    ],
                    pw: [
                        // { required: true, message: '密码不能为空', trigger: 'blur' }
                        { validator: validatePw, trigger: 'blur' }
                    ],
                    name: [
                        { required: true, message: '学生姓名不能为空', trigger: 'blur' }
                    ],
                    no: [
                        { validator: validateSeatNo, type: 'number', trigger: 'blur' }
                    ],
                    classId: [
                        { validator: validateclassId, trigger: 'blur' },
                    ]
                },
                modal_loading: false,
                searchPeriod: '',
                searchGrade: ''
            }
        },
        computed: {
            ...mapGetters({
                periods: 'user/getPeriods', // 學制s
                grades: 'user/getGrades', // 年級
                classes: 'user/getClasses', // 教室ID,
                students: 'schoolBaseInfo/getStudent', // 學生List
            }),
            filterGrades: function() {
                var data = this.grades
                if (this.searchPeriod) {
                    let periodId = this.searchPeriod
                    data = data.filter(function(item) {
                        return item.periodId == periodId
                    })
                    return data
                } else {
                    return []
                }
            },
            filterClasses: function() {
                var data = this.classes
                if (this.searchGrade) {
                    let gradeId = this.searchGrade
                    data = data.filter(function(item) {
                        return item.gradeId == gradeId && item.openType == '1'
                    })
                    return data
                } else {
                    return []
                }
            },
            show: {
                get() {
                    // if (this.bizType == 2 && this.isShow == true) {
                    //  if (this.editStudentInfo.length == 1) {
                    //    let arr = this.editStudentInfo[0].id.split("#");
                    //    if (arr.length > 1) {
                    //      this.editStudentInfo[0].id = arr[1];
                    //    } else {
                    //      alert("学生账号格式错误！");
                    //    }
                    //  }
                    // }
                    return this.isShow
                },
                set(value) {
                }
            }
        },
        methods: {
            
            cancel() {
                this.same = false
                this.$parent.addStudentStatus = false
                this.$emit('saveStudentInfo', {
                    action: 0
                })
            },
            setPassword(data) {
                //bizType 编辑
                if (this.bizType == 2) {
                    this.$set(this.editStudentInfo[0], 'pw', data ? this.editStudentInfo[0].id : '')
                } else {
                    this.studentInfo.pw = data ? this.studentInfo.id : ''
                }
            },
            setCurrentClassDetail(item){
                this.$store.dispatch('user/getGradeById', item.gradeId).then(res=>{
                    if(res.length == 0){
                        this.gradeName = '暫無資訊'
                    } else {
                        this.gradeName = res.name
                    }
                })   
            },
            getClassroom() {
                this.classroomList = this.$store.state.schoolBaseInfo.classroomList
                if (this.classroomList.length == 0) {
                    this.$api.schoolSetting.findClassInfo({
                        SchoolCode: this.schoolCode
                    }).then(res => {
                        if (res.error == null) {
                            if (res.result.data.length > 0) {
                                this.classroomList = res.result.data
                            }
                        }
                    })
                }
            },
            confirm() {
                this.showError = true
                if (this.isFull) {
                    this.same = false
                    if (this.bizType == 2) {

                        this.isLoading = true
                        let stringify = JSON.stringify( this.editStudentInfo)
                        let parse = JSON.parse(stringify)
                        let apiData = []
                        if(parse.length == 1){
                            let temp = parse.map(function(item){
                                let data = {
                                    id: item.id,
                                    year: item.year ? item.year.toString() : '',
                                    no: item.no ? item.no.toString() : '',
                                    name: item.name,
                                    classId: item.classId ? item.classId : ''
                                }
                                if(data.classId == '') data.no = ''
                                return data
                            })
                            if(this.isRepeat(temp[0])){
                                this.$Message.error('請檢查 帳號資訊 或 座號重複 了。')
                                this.isLoading = false
                            } else {
                                apiData = temp
                            }
                        } else {
                            let classId = parse[0].classId
                            let temp = parse.map(function(item){
                                return {
                                    no : "",
                                    id: item.id,
                                    classId: classId,
                                    name: item.name,
                                    year: item.year ? item.year.toString() : ''
                                }
                            })
                            apiData = temp
                        }
                        if(apiData.length > 0){                 
                            // 新增 如果密碼沒被改變就拿掉此Key           
                            apiData.forEach( (item) =>{
                                if(item.pw == '******') {
                                    delete item.pw
                                }
                            })

                            this.$api.stuAccount.saveAllStudent(this.schoolCode, apiData).then(
                                (res) => {
                                    if (!res.errorId) {
                                        this.show = false
                                        this.$emit('saveStudentInfo', {
                                            action: 2, // 批量修改数据
                                            studentInfos: res.students
                                        })
                                        this.$refs.updateForm.resetFields()
                                        this.uploadLoading = false
                                    } else {
                                        this.$Message.error('API error!')
                                    }
                                    this.isLoading = false
                                },
                                (err) => {
                                    this.$Message.error('API error!')
                                    this.isLoading = false
                                }
                            )
                        }
                    } else {
                        this.isLoading = true

                        let apiData = 
                        [
                            {
                            "id": this.studentInfo.id,
                            "no": this.studentInfo.no ? this.studentInfo.no.toString() : '',
                            "name": this.studentInfo.name,
                            "year": this.studentInfo.year ? this.studentInfo.year.toString() : '',
                            "pw": this.studentInfo.pw,
                            "classId": this.studentInfo.classId,
                            // Excel 匯入才需要給classname
                            // "className":this.studentInfo.classroomName ? this.studentInfo.classroomName : ''
                            }
                        ]
                        if(this.isRepeat(apiData[0])){
                            this.$Message.error('請檢查 帳號資訊 或 座號重複 了。')
                            this.isLoading = false
                        } else {
                            this.$api.stuAccount.saveStudent(this.schoolCode, apiData).then(
                                (res) => {
                                    if (!res.errorId) {
                                        this.show = false
                                        res.gradeId = this.searchGrade
                                        res.periodId = this.searchPeriod
                                        this.$emit('saveStudentInfo', {
                                            action: 1, // 新增学生
                                            studentInfos: res
                                        })
                                        this.$refs.studentInfoForm.resetFields()
                                    }
                                    this.isLoading = false
                                },
                                (err) => {
                                    this.$Message.error('API error!')
                                    this.isLoading = false
                                }
                            )
                        }
                    }
                } else {
                    this.$Message.error('请完善信息!')
                }
            },
            createClassroom() {
                this.$router.push({
                    path: '/home/classroom'
                })
            },
            isRepeat(data){
                if(this.bizType == 1){
                    return this.students.some(function(item){
                        return (item.id === data.id || (data.classId !='' && data.classId === item.classId && data.no === item.no))
                    })
                } else if(this.bizType == 2){
                    let temp = this.students.filter(function(item){
                        return (data.classId !='' && data.classId === item.classId && data.no === item.no)
                    })
                    if(temp.length > 0){
                        return !(temp[0].id == data.id)
                    } else {
                        return false
                    }
                }                
            }
        },
        created() {
            // this.getClassroom()
        },
        mounted() {
            if (this.bizType == 2 && this.isShow == true) {
                if (this.editStudentInfo.length == 1) {
                    this.setCurrentClassDetail(this.editStudentInfo[0])
                    // let arr = this.editStudentInfo[0].id.split('#')
                    // if (arr.length > 1) {
                    //     this.editStudentInfo[0].id = arr[1]
                    // } else {
                    //     alert('学生账号格式错误！')
                    // }
                }
            }
        },
        watch: {
            studentInfo: {
                handler(newValue, oldValue) {
                    if (this.bizType == 1) {
                        this.showError = false
                        this.$refs.studentInfoForm.validate((valid) => {
                            if (valid) {
                                this.isFull = true
                            } else {
                                this.isFull = false
                            }
                        })
                    }
                },
                deep: true
            },
            editStudentInfo: {
                handler(newValue, oldValue) {
                    this.$nextTick(() => {
                        this.showError = false
                        if (this.bizType == 2) {
                            this.$refs.updateForm.validate((valid) => {
                                if (valid) {
                                    this.isFull = true
                                } else {
                                    this.isFull = false
                                }
                            })
                        }
                    })
                },
                deep: true,
                immediate: true
            }
        }
    }
</script>
<style>
    .account-form .ivu-btn {
        border:none;
    }
</style>
