<template>
    <div class="sm-system dark-iview-input" @click="initStatus">
        <Loading v-if="isLoading"></Loading>
        <div class="sm-school-name dark-iview-select common-save-btn">
            <span class="setting-title">{{$t('schoolBaseInfo.schoolNameLabel')}}</span>
            <div class="editable school-name dark-iview-input disabled-iview-select text-cursor-disabled" @click.stop>
                <Input v-model="schoolSetting.name" :disabled="!editSchNmStatus" :placeholder="$t('schoolBaseInfo.pdHolder')" :style="{width: snWitdh+'px'}" />
                <Icon type="md-create" class="edit-btn" :title="$t('schoolBaseInfo.editLabel')" @click.stop="editSchNmStatus = !editSchNmStatus" />
            </div>
            <div class="editable time-zone-select" style="margin-left:100px;" @click.stop>
                <span class="setting-title">{{$t('schoolBaseInfo.tmzLabel')}}</span>
                <Select filterable v-model="schoolSetting.timeZone.value" label-in-value :style="{width: tzWidth+'px', verticalAlign:'baseline'}" :placeholder="$t('schoolBaseInfo.tmzHolder')">
                    <Option v-for="(item,index) in timeZoneList" :value="item.value" :key="index" @click.native="setTimeZone(item)">{{ item.label }}</Option>
                </Select>
            </div>
            <Button v-if="$access.ability('admin','schoolSetting-upd').validateAll" class="school-tools" :loading="isLoading" :disabled="!updated" icon="ios-albums-outline" @click="saveData()">{{$t('schoolBaseInfo.saveInfo')}}</Button>

        </div>
        <div class="sm-system-body dark-iview-split disabled-iview-select text-cursor-disabled">
            <Split v-model="split1">
                <div slot="left" class="split-left">
                    <Split v-model="split2">
                        <!--学段列表-->
                        <div slot="left" class="period-wrap">
                            <div class="col-title">
                                <span>{{$t('schoolBaseInfo.periodSettingLabel')}}</span>
                                <Icon v-if="$access.ability('admin','schoolSetting-upd').validateAll" type="md-add" @click="addPeriod()" class="action-btn-icon" />
                                <Icon v-if="$access.ability('admin','schoolSetting-upd').validateAll" type="md-trash" @click="showComfirmDelPeriod()" :title="$t('schoolBaseInfo.delete')" :class="editIconStatus ? 'action-btn-icon':'custom-label-disabeld action-btn-icon'" />
                                <Icon v-if="$access.ability('admin','schoolSetting-upd').validateAll" type="md-create" @click.stop="editPrdIndex = curPriodIndex" :title="$t('schoolBaseInfo.editLabel')" :class="editIconStatus ? 'action-btn-icon':'custom-label-disabeld action-btn-icon'" />
                            </div>
                            <Draggable ghost-class="ghost" class="period-list list-group" :list="schoolSetting.period" :animation='200'>
                                <div class="period-item list-group-item" v-for="(item,index) in schoolSetting.period" :key="index" @click.capture="choosePeriod(index)" :class="index == curPriodIndex ? 'block-bg-active block-bg':'block-bg'">
                                    <p class="period-item-name semester-name-label dark-iview-input" @click.stop>
                                        <Input v-model="item.name" :disabled="editPrdIndex !== index" :placeholder="$t('schoolBaseInfo.pdHolder')" style="width: 180px" />
                                        <span class="campus-label" @click="setCampus">
                                            {{item.campusId === null ? $t('schoolBaseInfo.campusHolder'): $JSONPath.query(schoolSetting, "$..campuses[?(@.id=='" + item.campusId + "')]").length > 0 ? $JSONPath.query(schoolSetting, "$..campuses[?(@.id=='" + item.campusId + "')]")[0].name : $t('schoolBaseInfo.campusHolder') }}
                                        </span>
                                    </p>
                                    <p class="period-item-num"><span></span>{{ $t('schoolBaseInfo.semesterNum') + item.semesters.length}}</p>
                                    <p class="period-item-num"><span></span>{{ $t('schoolBaseInfo.gradeNum') + item.grades.length}}</p>
                                    <p class="period-item-num"><span></span>{{ $t('schoolBaseInfo.periodNum') + item.subjects.length}}</p>
                                </div>
                            </Draggable>
                        </div>
                        <!--学期列表-->
                        <div slot="right" class="semester-wrap">
                            <div class="col-title">
                                <span>{{$t('schoolBaseInfo.semesterSetting')}}</span>
                                <Icon v-if="$access.ability('admin','schoolSetting-upd').validateAll" type="md-add" @click.stop="addSemester()" class="action-btn-icon" />
                                <Icon v-if="$access.ability('admin','schoolSetting-upd').validateAll" type="md-trash" @click.stop="showComfirmDelSemester()" :title="$t('schoolBaseInfo.delete')" :class="editIconStatus ? 'action-btn-icon':'custom-label-disabeld action-btn-icon'" />
                                <Icon v-if="$access.ability('admin','schoolSetting-upd').validateAll" type="md-create" @click.stop="editSemIndex = curSemIndex" :title="$t('schoolBaseInfo.editLabel')" :class="editIconStatus ? 'action-btn-icon':'custom-label-disabeld action-btn-icon'" />
                            </div>
                            <div class="col-body">
                                <div class="no-data-text" v-if="!schoolSetting.period[curPriodIndex].semesters.length">{{$t('schoolBaseInfo.noSemester')}}</div>
                                <div class="term-list dark-iview-input disabled-iview-input dark-iview-select disabled-iview-select" v-if="schoolSetting.period[curPriodIndex].semesters.length">
                                    <vuescroll>
                                        <div v-for="(item,index) in schoolSetting.period[curPriodIndex].semesters" :key="index" :class="index == curSemIndex ? 'term-item block-bg block-bg-active':'term-item block-bg'" @click.capture="chooseSemester(index)">
                                            <span class="term-item-name-line" :style="{backgroundColor: colorList[index]}"></span>
                                            <p class="semester-name-label" @click.stop>
                                                <Input v-model="item.name" :disabled="editSemIndex !== index" :placeholder="$t('schoolBaseInfo.smHolder')" style="width: 180px" />
                                            </p>
                                            <div class="term-item-start" @click.stop>
                                                <span>{{$t('schoolBaseInfo.startDate')}}</span>
                                                <Select v-model="item.month" style="width:50px" :placeholder="$t('schoolBaseInfo.monthHolder')" :disabled="editSemIndex !== index">
                                                    <Option v-for="(item,index) in monthList" :value="(index + 1)" :key="index" @click.native="countSemDays">{{ item }}</Option>
                                                </Select>
                                                <span> / </span>
                                                <Select v-model="item.day" style="width:50px" :placeholder="$t('schoolBaseInfo.dayHolder')" :disabled="editSemIndex !== index">
                                                    <Option v-for="(item,index) in dayList" :value="(index + 1)" :key="index" @click.native="countSemDays">{{ item }}</Option>
                                                </Select>
                                            </div>
                                            <p class="term-item-students-num">{{$t('schoolBaseInfo.semesterDuration')+ semDays[index] + $t('schoolBaseInfo.dayUnit')  }}</p>
                                        </div>
                                    </vuescroll>
                                </div>
                                <div class="term-item-time-line" v-if="schoolSetting.period[curPriodIndex].semesters.length">
                                    <vuescroll>
                                        <ul style="">
                                            <li v-for="(item,index) in monthList" :key="index" :title="timeLineColor(index).text">
                                                <span class="time-label">{{item}}</span>
                                                <span class="time-dot" :style="{borderColor: timeLineColor(index).color}">
                                                    <span class="time-inner-dot" :style="{backgroundColor: timeLineColor(index).color}"></span>
                                                    <span class="time-line-tail"></span>
                                                </span>
                                                <div v-show="timeLineColor(index).showArrow">
                                                    <Icon class="first-arrow" size="20" :style="{color: timeLineColor(index).color}" type="ios-arrow-back" />
                                                    <Icon class="second-arrow" size="20" :style="{color: timeLineColor(index).color}" type="ios-arrow-back" />
                                                </div>
                                            </li>
                                        </ul>
                                    </vuescroll>
                                </div>
                            </div>
                        </div>
                    </Split>
                </div>
                <div slot="right" class="split-right">
                    <Split v-model="split3">
                        <!--年级区域-->
                        <div slot="left" class="grade-wrap dark-iview-table disabled-iview-input dark-iview-input">
                            <div class="col-title">
                                <span>{{$t('schoolBaseInfo.gradeSetting')}}</span>
                                <Icon type="md-add" @click.stop="addGrade" class="action-btn-icon" v-if="$access.ability('admin','schoolSetting-upd').validateAll" />
                                <Icon type="md-trash" @click.stop="delGraStatus = true" class="action-btn-icon" v-if="$access.ability('admin','schoolSetting-upd').validateAll" />
                                <Icon type="md-create" @click.stop="editGraStatus = true" class="action-btn-icon" v-if="$access.ability('admin','schoolSetting-upd').validateAll" />
                            </div>
                            <div class="grade-body">
                                <Draggable ghost-class="ghost" class="grade-list list-group" :list="schoolSetting.period[curPriodIndex].grades" :animation='200'>
                                    <div class="grade-item list-group-item" v-for="(item,index) in schoolSetting.period[curPriodIndex].grades" :key="index" @click.stop>
                                        <span class="grade-order">{{index + 1}}</span>
                                        <Input class="grade-name" v-model="item.name" :disabled="!editGraStatus" placeholder="设置年级..." :style="{width: getWidth(index,item.name)+'px'}" />
                                        <Icon type="md-close" @click.stop="showDelGrade(index)" style="cursor:pointer;flex:0.1" v-show="delGraStatus" />
                                    </div>
                                </Draggable>
                            </div>
                        </div>
                        <!--学科显示区域-->
                        <div slot="right" class="subject-wrap">
                            <div class="col-title">
                                <span>{{$t('schoolBaseInfo.subjectSetting')}}</span>
                                <Icon type="md-add" @click.stop="addSubject()" class="action-btn-icon" v-if="$access.ability('admin','schoolSetting-upd').validateAll" />
                                <Icon type="md-trash" @click.stop="delSubStatus = true" class="action-btn-icon" v-if="$access.ability('admin','schoolSetting-upd').validateAll" />
                                <Icon type="md-create" @click.stop="editSubStatus = true" class="action-btn-icon" v-if="$access.ability('admin','schoolSetting-upd').validateAll" />
                            </div>
                            <div class="subject-body dark-iview-input disabled-iview-input" style="height:40%;">
                                <div class="tag-item item-active" @click.stop v-for="(item,index) in schoolSetting.period[curPriodIndex].subjects" :key="index">
                                    <!--<span class="tag-item-icon"></span>-->
                                    <Input v-model="item.name" :disabled="!editSubStatus" :placeholder="$t('schoolBaseInfo.subjectHolder')" :style="{width: getWidth(index,item.name)+'px'}" />
                                    <Icon type="md-close" @click="delSubject(index)" v-show="delSubStatus" />
                                </div>
                                <EmptyData v-if="schoolSetting.period[curPriodIndex].subjects.length == 0" :textContent="$t('schoolBaseInfo.noSubject')"></EmptyData>
                            </div>
                            <!--学情设置-->
                            <div style="height:50%;position:relative;" class="dark-iview-inputnumber disabled-iview-inputnumber">
                                <div class="col-title">
                                    <span>{{$t('schoolBaseInfo.anaLabel')}}</span>
                                    <Icon type="md-add" class="action-btn-icon" @click.stop="addExamType" v-if="$access.ability('admin','schoolSetting-upd').validateAll" />
                                    <Icon type="md-trash" class="action-btn-icon" @click.stop="delAnaStatus = !delAnaStatus" v-if="$access.ability('admin','schoolSetting-upd').validateAll" />
                                    <Icon type="md-create" class="action-btn-icon" @click.stop="editAnaStatus = !editAnaStatus" v-if="$access.ability('admin','schoolSetting-upd').validateAll" />
                                </div>
                                <div class="attr-box-item" style="margin-top:15px;">
                                    <p>
                                        <span>{{$t('schoolBaseInfo.exTypeLabel')}}</span>
                                    </p>
                                    <div class="attr-content">
                                        <div class="tag-item item-active" @click.stop v-for="(item,index) in schoolSetting.period[curPriodIndex].analysis.type" :key="index">
                                            <Input v-model="item.name" :disabled="!editAnaStatus" :placeholder="$t('schoolBaseInfo.examHolder')" :style="{width: getWidth(index,item.name)+'px'}" />
                                            <Icon type="md-close" @click="confirmDelAna(index)" v-show="delAnaStatus" />
                                        </div>
                                        <span v-if="!schoolSetting.period[curPriodIndex].analysis.type" style="line-height:32px;">{{$t('schoolBaseInfo.noExam')}}</span>
                                    </div>
                                </div>
                                <div class="attr-box-item">
                                    <p>
                                        <Tooltip :content="$t('schoolBaseInfo.eugenicsTips')" placement="right">
                                            <Icon type="ios-information-circle-outline" color="aqua" size="16" style="margin-right: 5px;cursor: pointer;" />
                                        </Tooltip>
                                        <span>{{$t('schoolBaseInfo.eugenicsLabel')}}</span>
                                    </p>
                                    <div class="attr-content" @click.stop>
                                        <InputNumber :max="100" :min="0" :disabled="!editAnaStatus" v-model="schoolSetting.period[curPriodIndex].analysis.eugenics" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')"></InputNumber>
                                    </div>
                                </div>
                                <div class="attr-box-item">
                                    <p>
                                        <Tooltip :content="$t('schoolBaseInfo.incomeTips')" placement="right">
                                            <Icon type="ios-information-circle-outline" color="aqua" size="16" style="margin-right:5px;cursor:pointer;" />
                                        </Tooltip>
                                        <span>{{$t('schoolBaseInfo.incomeLable')}}</span>
                                    </p>
                                    <div class="attr-content" @click.stop>
                                        <InputNumber :max="100" :min="0" :disabled="!editAnaStatus" v-model="schoolSetting.period[curPriodIndex].analysis.income" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')"></InputNumber>
                                    </div>
                                </div>
                                <div class="attr-box-item">
                                    <p>
                                        <Tooltip :content="$t('schoolBaseInfo.touchTips')" placement="right">
                                            <Icon type="ios-information-circle-outline" color="aqua" size="16" style="margin-right: 5px;cursor: pointer;" />
                                        </Tooltip>
                                        <span>{{$t('schoolBaseInfo.touchLabel')}}</span>
                                    </p>
                                    <div class="attr-content" @click.stop>
                                        <InputNumber :max="100" :min="0" :disabled="!editAnaStatus" v-model="schoolSetting.period[curPriodIndex].analysis.touch" :formatter="value => `${value}${$t('schoolBaseInfo.scoreUnit')}`" :parser="value => value.replace($t('schoolBaseInfo.scoreUnit'), '')"></InputNumber>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </Split>
                </div>
            </Split>
        </div>
        <Modal v-model="campusStatus" class="campus-modal dark-iview-modal" @on-cancel="selectedCampusIndex = -1" @on-ok="confirmCampus" @click.native="initStatus">
            <p slot="header" style="color:#DDDDDD;letter-spacing:2px;font-weight:400;">{{$t('schoolBaseInfo.setCampus')}}</p>
            <p v-for="(item,index) in schoolSetting.campuses" class="campus-name-item dark-iview-input disabled-iview-select text-cursor-disabled" :key="index" @click.stop="selectedCampusIndex = index">
                <Icon type="md-checkmark" size="20" style="margin-right:10px;position:absolute;left:15px;" v-if="index == selectedCampusIndex" />
                <Input v-model="item.name" :disabled="editCamIndex !== index" :placeholder="$t('schoolBaseInfo.campusHolder')" :style="{width: getWidth(0, item.name)+'px'}" />
                <Icon type="md-create" class="campus-btn-edit" :title="$t('schoolBaseInfo.editLabel')" size="20" @click.stop="editCamIndex = index" />
                <Icon type="md-trash" class="campus-btn-edit" :title="$t('schoolBaseInfo.delete')" size="20" style="margin-right:40px;" @click.stop="delCampus(index)" />
            </p>
            <Icon type="md-add-circle" size="40" style="margin:auto;cursor:pointer;margin-top:30px;" @click="addCampus" />
        </Modal>
    </div>
</template>

<script>
import Draggable from 'vuedraggable'
import '@/utils/Math.uuid'
export default {
    components: {
        Draggable
    },
    data() {
        return {
            addTypeStatus: false,
            typeItem: {
                base: '',
                name: '',
                id: ''
            },
            delSubStatus: false,
            delAnaStatus: false,
            delGraStatus: false,

            editCamIndex: -1,
            editSchNmStatus: false,
            editPrdIndex: -1,
            editTZStatsu: true,
            editGraStatus: false,
            editSubStatus: false,
            editAnaStatus: false,
            editSemIndex: -1,

            split1: 0.5,
            split2: 0.38,
            split3: 0.38,
            monthList: [],
            timeZoneList: [],
            isLoading: false,
            dataDefault: {},
            updated: false,
            curPriodIndex: 0,
            curSemIndex: 0,
            isInit: true,
            schoolSetting: {
                schoolCode: '',
                name: '',
                period: [],
                campuses: [],
                timeZone: {
                    "label": "",
                    "value": ""
                }
            },

            colorList: [],
            TERM_MAX_LENGTH: 6, // 学期数上限
            campusStatus: false,
            semDays: [],
            selectedCampusIndex: -1
        }
    },
    methods: {
        /**
         * 初始化状态
         */
        initStatus() {
            this.delGraStatus = false
            this.delSubStatus = false
            this.delAnaStatus = false
            this.editSubStatus = false
            this.editGraStatus = false
            this.editAnaStatus = false
            this.editPrdIndex = -1
            this.editSemIndex = -1
            this.editCamIndex = -1
            this.editTZStatsu = true
            this.editSchNmStatus = false
        },
        //初始化数据
        initData() {
            this.schoolSetting.schoolCode = this.$store.state.userInfo.schoolCode
            this.schoolSetting.id = this.$store.state.userInfo.schoolCode
            this.schoolSetting.code = this.$store.state.userInfo.schoolCode
            this.schoolSetting.name = this.$store.state.userInfo.school

            this.schoolSetting.period.push({
                name: this.$t('schoolBaseInfo.presetPeriod') + '1',
                id: this.guid(),
                gradeCount: 0,
                semesterCount: 0,
                subjectCount: 0,
                semesters: [],
                grades: [],
                subjects: [],
                campusId: ""
            })
            this.schoolSetting.period[0].semesters.push({
                name: this.$t('schoolBaseInfo.persetSemester'),
                id: this.guid(),
                month: 1,
                day: 1
            })
            this.schoolSetting.period[0].grades.push({
                name: this.$t('schoolBaseInfo.presetGrade1'),
                id: this.guid()
            })
            this.schoolSetting.period[0].grades.push({
                name: this.$t('schoolBaseInfo.presetGrade2'),
                id: this.guid()
            })
            this.schoolSetting.period[0].grades.push({
                name: this.$t('schoolBaseInfo.presetGrade3'),
                id: this.guid()
            })
            this.schoolSetting.period[0].subjects.push({
                name: this.$t('schoolBaseInfo.presetSubject1'),
                id: this.guid()
            })
            this.schoolSetting.period[0].subjects.push({
                name: this.$t('schoolBaseInfo.presetSubject2'),
                id: this.guid()
            })
            this.schoolSetting.period[0].subjects.push({
                name: this.$t('schoolBaseInfo.presetSubject3'),
                id: this.guid()
            })
            this.schoolSetting.period[0].analysis = {
                income: 10,
                touch: 10,
                type: this.$GLOBAL.EXAM_TYPE()
            }
            this.updated = false
            this.countSemDays()
        },
        //计算时间轴选中颜色
        timeLineColor(index) {
            let len = this.schoolSetting.period[this.curPriodIndex].semesters.length
            let curIndex = -1
            if (this.schoolSetting.period[this.curPriodIndex].semesters[this.curSemIndex].month <= (index + 1)) {
                if (this.curSemIndex < len - 1) {
                    if (this.schoolSetting.period[this.curPriodIndex].semesters[this.curSemIndex + 1].month > (index + 1)) {
                        curIndex = this.curSemIndex
                    }
                }
            }
            let curMonth = this.schoolSetting.period[this.curPriodIndex].semesters[this.curSemIndex].month
            let nextMonth = -1
            if (this.curSemIndex == len - 1) {
                nextMonth = this.schoolSetting.period[this.curPriodIndex].semesters[0].month
            } else {
                nextMonth = this.schoolSetting.period[this.curPriodIndex].semesters[this.curSemIndex + 1].month
            }
            if (curIndex != -1) {
                return {
                    color: this.colorList[curIndex],
                    text: this.schoolSetting.period[this.curPriodIndex].semesters[curIndex].name,
                    showArrow: (index + 1) == curMonth || (index + 2) == nextMonth
                }
            } else if (this.curSemIndex == len - 1) {
                if (this.schoolSetting.period[this.curPriodIndex].semesters[0].month > (index + 1) || this.schoolSetting.period[this.curPriodIndex].semesters[this.curSemIndex].month <= (index + 1)) {
                    curIndex = this.curSemIndex
                    return {
                        color: this.colorList[curIndex],
                        text: this.schoolSetting.period[this.curPriodIndex].semesters[curIndex].name,
                        showArrow: (index + 1) == curMonth || (index + 2) == nextMonth
                    }
                } else {
                    return {
                        color: '#606060',
                        text: '',
                        showArrow: (index + 1) == curMonth || (index + 2) == nextMonth
                    }
                }
            } else {
                return {
                    color: '#606060',
                    text: '',
                    showArrow: (index + 1) == curMonth || (index + 2) == nextMonth
                }
            }

        },
        //获取月份列表
        getMonthList() {
            let lang = window.localStorage.getItem('local')
            if (lang.indexOf('CN') != -1 || lang.indexOf('cn') != -1) {
                this.monthList = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
            } else if (lang.indexOf('TW') != -1 || lang.indexOf('tw') != -1) {
                this.monthList = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
            } else {
                this.monthList = ['JAN.', 'FEB.', 'MAR.', 'APR.', 'MAY.', 'JUN.', 'JUL.', 'AUG.', 'SEP.', 'OCT.', 'NOV.', 'DEC.']
            }
        },
        //设置学校时区
        setTimeZone(item) {
            this.schoolSetting.timeZone.label = item.label
            this.editTZStatsu = true
        },

        //删除考试类型
        confirmDelAna(index) {
            this.$Modal.confirm({
                title: this.$t('schoolBaseInfo.delExamTitle'),
                content: this.$t('schoolBaseInfo.delete') + this.schoolSetting.period[this.curPriodIndex].analysis.type[index].name + this.$t('schoolBaseInfo.delContent'),
                onOk: () => {
                    this.schoolSetting.period[this.curPriodIndex].analysis.type.splice(index, 1)
                }
            })
        },
        //显示删除年级
        showDelGrade(index) {
            this.$Modal.confirm({
                title: this.$t('schoolBaseInfo.delGradeTitle'),
                content: this.$t('schoolBaseInfo.delete') + this.schoolSetting.period[this.curPriodIndex].grades[index].name + this.$t('schoolBaseInfo.delContent'),
                onOk: () => {
                    this.schoolSetting.period[this.curPriodIndex].grades.splice(index, 1)
                }
            })
        },
        //删除学科
        delSubject(index) {
            this.$Modal.confirm({
                title: this.$t('schoolBaseInfo.delSubjectTitle'),
                content: this.$t('schoolBaseInfo.delete') + this.schoolSetting.period[this.curPriodIndex].subjects[index].name + this.$t('schoolBaseInfo.delContent'),
                onOk: () => {
                    this.schoolSetting.period[this.curPriodIndex].subjects.splice(index, 1)
                }
            })
        },
        /**确认删除学段提示框 */
        showComfirmDelPeriod() {
            this.$Modal.confirm({
                title: this.$t('schoolBaseInfo.delPdTitle'),
                content: this.$t('schoolBaseInfo.delete') + this.schoolSetting.period[this.curPriodIndex].name + this.$t('schoolBaseInfo.delContent'),
                onOk: () => {
                    let index = this.curPriodIndex
                    this.curSemIndex = 0
                    this.curPriodIndex = 0
                    if (this.schoolSetting.period.length > 1) {
                        this.schoolSetting.period.splice(index, 1)
                    } else {
                        this.$Message.warning(this.$t('schoolBaseInfo.ssTips2'))
                    }
                }
            })
        },
        //删除校区
        delCampus(index) {
            this.$Modal.confirm({
                title: this.$t('schoolBaseInfo.delCampusTitle'),
                content: this.$t('schoolBaseInfo.delete') + this.schoolSetting.campuses[index].name + this.$t('schoolBaseInfo.delContent'),
                onOk: () => {
                    this.schoolSetting.campuses.splice(index, 1)
                }
            })
        },
        /**确认删除学期提示框 */
        showComfirmDelSemester() {
            this.$Modal.confirm({
                title: this.$t('schoolBaseInfo.delSmTitle'),
                content: this.$t('schoolBaseInfo.delete') + this.schoolSetting.period[this.curPriodIndex].semesters[this.curSemIndex].name + this.$t('schoolBaseInfo.delContent'),
                onOk: () => {
                    let semIndex = this.curSemIndex
                    let prdIndex = this.curPriodIndex
                    if (this.schoolSetting.period[this.curPriodIndex].semesters.length > 1) {
                        //this.curPriodIndex = 0
                        this.curSemIndex = 0
                        this.schoolSetting.period[prdIndex].semesters.splice(semIndex, 1)
                        this.countSemDays()
                    } else {
                        this.$Message.warning(this.$t('schoolBaseInfo.ssTips2'))
                    }
                }
            })
        },
        /**
         * 动态设置input宽度
         * */
        getWidth(index, text) {
            let width = 100
            if (text) {
                width = 18.25
                for (var i = 0; i < text.length; i++) {
                    var c = text.charCodeAt(i);
                    //单字节宽度
                    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
                        width += 9
                    }
                    else {
                        //汉字宽度
                        width += 15.97
                    }
                }
            }
            return width
        },

        /**
         * 计算学期天数
         * @param date1
         * @param date2
        */
        countSemDays() {
            this.semDays = []
            if (this.schoolSetting.period[this.curPriodIndex].semesters.length > 0) {
                let count = 365
                let index = 0
                let year = new Date().getFullYear()
                for (let i = 0; i < this.schoolSetting.period[this.curPriodIndex].semesters.length; i++) {
                    if (i == (this.schoolSetting.period[this.curPriodIndex].semesters.length - 1)) {
                        index = i
                        break
                    } else {
                        let sDate = year + '-' + this.schoolSetting.period[this.curPriodIndex].semesters[i].month + '-' + this.schoolSetting.period[this.curPriodIndex].semesters[i].day
                        let eDate = year + '-' + this.schoolSetting.period[this.curPriodIndex].semesters[i + 1].month + '-' + this.schoolSetting.period[this.curPriodIndex].semesters[i + 1].day
                        let d = this.getDays(sDate, eDate)
                        count -= d
                        //this.$set(this.schoolSetting.period[this.curPriodIndex].semesters[i], 'days', d ? d : 365)
                        this.semDays.push(d ? d : 365)
                    }
                }
                //this.$set(this.schoolSetting.period[this.curPriodIndex].semesters[index], 'days', count ? count : 365)
                this.semDays.push(count ? count : 365)
            }
        },
        /**
         * 计算两个日期的天数
         * @param date1
         * @param date2
         */
        getDays(date1, date2) {
            var date1Str = date1.split("-");//将日期字符串分隔为数组,数组元素分别为年.月.日
            //根据年 . 月 . 日的值创建Date对象
            var date1Obj = new Date(date1Str[0], (date1Str[1] - 1), date1Str[2]);
            var date2Str = date2.split("-");
            var date2Obj = new Date(date2Str[0], (date2Str[1] - 1), date2Str[2]);
            var t1 = date1Obj.getTime();
            var t2 = date2Obj.getTime();
            var dateTime = 1000 * 60 * 60 * 24; //每一天的毫秒数
            var minusDays = Math.floor(((t2 - t1) / dateTime));//计算出两个日期的天数差
            var days = Math.abs(minusDays);//取绝对值
            return days;
        },
        confirmCampus() {
            if (this.selectedCampusIndex !== -1) {
                this.$set(this.schoolSetting.period[this.curPriodIndex], 'campusId', this.schoolSetting.campuses[this.selectedCampusIndex].id)
                //this.schoolSetting.period[this.curPriodIndex].campusId = this.schoolSetting.campuses[this.selectedCampusIndex].id
                this.selectedCampusIndex = -1
            }
        },
        //添加校区
        addCampus() {
            if (this.schoolSetting.campuses.length >= 2) {
                this.$Message.error({
                    background: true,
                    content: this.$t('schoolBaseInfo.campusWarning')
                })
            } else {
                this.schoolSetting.campuses.push({
                    name: this.$t('schoolBaseInfo.setCampus'),
                    id: Math.uuid()
                })
                this.$nextTick(() => {
                    setTimeout(() => {
                        this.editCamIndex = this.schoolSetting.campuses.length - 1
                    }, 200)
                })

            }
        },
        setCampus() {
            this.editPrdIndex = -1
            if (this.$access.ability('admin', 'schoolSetting-upd').validateAll) {
                this.campusStatus = true
            } else {
                this.$Message.warning(this.$t('schoolBaseInfo.authWarning'))
            }
        },

        //选择学期
        chooseSemester(index) {
            if (index != this.curSemIndex) {
                this.editSemIndex = -1
                this.curSemIndex = index
            }
        },
        //选择学段
        choosePeriod(index) {
            this.curSemIndex = 0
            this.curPriodIndex = index
            for (let item in this.schoolSetting.campuses) {
                if (this.schoolSetting.campuses[item].campusId == this.schoolSetting.period[this.curPriodIndex].campusId) {
                    this.selectedCampusIndex = item
                    break
                }
            }
            //计算天数
            if (this.schoolSetting.period[this.curPriodIndex].semesters.length > 0) {
                this.semDays = []
                if (!this.schoolSetting.period[this.curPriodIndex].semesters[0].days) {
                    let count = 365
                    let index = 0
                    let year = new Date().getFullYear()
                    for (let i = 0; i < this.schoolSetting.period[this.curPriodIndex].semesters.length; i++) {
                        if (i == (this.schoolSetting.period[this.curPriodIndex].semesters.length - 1)) {
                            index = i
                            break
                        } else {
                            let sDate = year + '-' + this.schoolSetting.period[this.curPriodIndex].semesters[i].month + '-' + this.schoolSetting.period[this.curPriodIndex].semesters[i].day
                            let eDate = year + '-' + this.schoolSetting.period[this.curPriodIndex].semesters[i + 1].month + '-' + this.schoolSetting.period[this.curPriodIndex].semesters[i + 1].day
                            let d = this.getDays(sDate, eDate)
                            count -= d
                            //this.$set(this.schoolSetting.period[this.curPriodIndex].semesters[i], 'days', d)
                            this.semDays.push(d)
                        }
                    }
                    //this.$set(this.schoolSetting.period[this.curPriodIndex].semesters[index], 'days', count)
                    this.semDays.push(count)
                }
            }

        },
        //保存数据
        saveData() {
            this.handleData()
            this.isLoading = true
            this.$api.schoolSetting.schoolSettingSaveOrUpdate(this.schoolSetting).then(
                (res) => {
                    if (!res.error) {
                        this.$Message.success(this.$t('schoolBaseInfo.ssTips3'))
                        this.updated = false

                        let schoolStr = localStorage.getItem('school_profile')
                        if (schoolStr) {
                            schoolStr = decodeURIComponent(schoolStr, "utf-8")
                            let schoolJson = JSON.parse(schoolStr)
                            schoolJson.school_base = this.schoolSetting
                            this.$store.dispatch('user/setSchoolProfile', schoolJson)
                        } else {
                            this.$store.dispatch('user/getSchoolProfile')
                        }

                    }
                },
                (err) => {
                    console.log(err)
                    this.$Message.error(this.$t('schoolBaseInfo.saveErr'))
                }
            ).finally(() => {
                setTimeout(() => {
                    this.isLoading = false
                }, 400)
            })
        },
        getSchoolBaseData() {
            this.isLoading = true
            this.$store.dispatch('user/getSchoolProfile').then(
                (res) => {
                    if (res) {
                        this.isInit = true
                        this.schoolSetting = JSON.parse(JSON.stringify(res.school_base))
                        //计算学期天数
                        if (this.schoolSetting.period[this.curPriodIndex].semesters.length > 0) {
                            this.semDays = []
                            if (!this.schoolSetting.period[this.curPriodIndex].semesters[0].days) {
                                let count = 365
                                let index = 0
                                let year = new Date().getFullYear()
                                for (let i = 0; i < this.schoolSetting.period[this.curPriodIndex].semesters.length; i++) {
                                    if (i == (this.schoolSetting.period[this.curPriodIndex].semesters.length - 1)) {
                                        index = i
                                        break
                                    } else {
                                        let sDate = year + '-' + this.schoolSetting.period[this.curPriodIndex].semesters[i].month + '-' + this.schoolSetting.period[this.curPriodIndex].semesters[i].day
                                        let eDate = year + '-' + this.schoolSetting.period[this.curPriodIndex].semesters[i + 1].month + '-' + this.schoolSetting.period[this.curPriodIndex].semesters[i + 1].day
                                        let d = this.getDays(sDate, eDate)
                                        count -= d
                                        this.semDays.push(d)
                                    }
                                }
                                this.semDays.push(count)
                            }
                        }
                    } else {
                        this.getLocalDefaultData()
                        this.isInit = true
                        this.schoolSetting.period[0].grades = JSON.parse(JSON.stringify(this.dataDefault.grades))
                        this.schoolSetting.period[0].subjects = JSON.parse(JSON.stringify(this.dataDefault.subjects))
                    }
                },
                (err) => {
                    console.log(err)
                    this.getLocalDefaultData()
                    this.isInit = true
                    this.schoolSetting.period[0].grades = JSON.parse(JSON.stringify(this.dataDefault.grades))
                    this.schoolSetting.period[0].subjects = JSON.parse(JSON.stringify(this.dataDefault.subjects))
                }
            ).finally(() => {
                setTimeout(() => {
                    this.isLoading = false
                }, 500)
            })
        },
        handleData() {
            for (let i = 0; i < this.schoolSetting.period.length; i++) {
                this.schoolSetting.period[i].gradeCount = this.schoolSetting.period[i].grades.length
                this.schoolSetting.period[i].semesterCount = this.schoolSetting.period[i].semesters.length
                this.schoolSetting.period[i].subjectCount = this.schoolSetting.period[i].subjects.length
            }
        },
        guid() {
            function S4() {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
            }
            return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
        },
        addSubject() {
            this.schoolSetting.period[this.curPriodIndex].subjects.push({
                name: this.$t('schoolBaseInfo.presetSubject') + (this.schoolSetting.period[this.curPriodIndex].subjects.length + 1),
                id: this.guid()
            })
            this.editSubStatus = true
        },

        addGrade() {
            this.schoolSetting.period[this.curPriodIndex].grades.push({
                name: this.$t('schoolBaseInfo.persetGrade') + (this.schoolSetting.period[this.curPriodIndex].grades.length),
                id: this.guid()
            })
            this.editGraStatus = true
        },
        addPeriod() {
            this.schoolSetting.period.push({
                name: this.$t('schoolBaseInfo.presetPeriod') + (this.schoolSetting.period.length + 1),
                id: this.guid(),
                campusId: '',
                gradeCount: 0,
                semesterCount: 0,
                subjectCount: 0,
                semesters: JSON.parse(JSON.stringify(this.dataDefault.semesters)),
                grades: JSON.parse(JSON.stringify(this.dataDefault.grades)),
                subjects: JSON.parse(JSON.stringify(this.dataDefault.subjects)),
                analysis: {
                    income: 10,
                    touch: 10,
                    eugenics: 10,
                    type: this.$GLOBAL.EXAM_TYPE()
                }
            })
            this.choosePeriod(this.schoolSetting.period.length - 1)
            this.$nextTick(() => {
                setTimeout(() => {
                    this.editPrdIndex = this.curPriodIndex
                }, 200)
            })

        },
        addExamType() {
            if (!this.schoolSetting.period[this.curPriodIndex].analysis.type) {
                this.schoolSetting.period[this.curPriodIndex].analysis.type = []
            }
            this.schoolSetting.period[this.curPriodIndex].analysis.type.push({
                id: this.guid(),
                name: this.$t('schoolBaseInfo.examHolder')
            })
            this.editAnaStatus = true
        },
        // 添加学期
        addSemester() {
            let semLen = this.schoolSetting.period[this.curPriodIndex].semesters.length
            if (semLen < this.TERM_MAX_LENGTH) {
                let defMonth = semLen == 0 ? 1 : this.schoolSetting.period[this.curPriodIndex].semesters[semLen - 1].month + 1
                this.schoolSetting.period[this.curPriodIndex].semesters.push({
                    name: this.$t('schoolBaseInfo.persetSemester') + (this.schoolSetting.period[this.curPriodIndex].semesters.length + 1),
                    month: defMonth,
                    day: 26,
                    id: this.guid()
                })
                this.countSemDays()
                this.$nextTick(() => {
                    setTimeout(() => {
                        this.curSemIndex = this.schoolSetting.period[this.curPriodIndex].semesters.length - 1
                        this.editSemIndex = this.curSemIndex
                    }, 200)
                })
            } else {
                this.$Message.info(this.$t('schoolBaseInfo.ssTips7'))
            }
        },
        getLocalDefaultData() {
            let data = require('@/static/baseDataDefault.json')
            let lang = window.localStorage.getItem('local')
            let result = data.filter(item => {
                return item.lang == lang
            })
            this.dataDefault = result.length > 0 ? result[0] : data[0]
        },
        //根据语言读取时区列表
        getTimeZoneList() {
            let lang = window.localStorage.getItem('local')
            if (lang.indexOf('CN') != -1 || lang.indexOf('cn') != -1) {
                this.timeZoneList = require('@/static/time-zone/timeCN.json')
            } else if (lang.indexOf('TW') != -1 || lang.indexOf('tw') != -1) {
                this.timeZoneList = require('@/static/time-zone/timeTW.json')
            } else {
                this.timeZoneList = require('@/static/time-zone/timeEN.json')
            }
        }
    },
    watch: {
        schoolSetting: {
            handler(newValue, oldValue) {
                if (this.isInit) {
                    this.isInit = false
                } else {
                    this.updated = true
                }
            },
            deep: true
        }
    },
    created() {
        this.getLocalDefaultData()
        this.initData()
        this.getSchoolBaseData()
        this.getTimeZoneList()
        this.getMonthList()
    },
    beforeRouteLeave(to, from, next) {
        if (this.updated) {
            let config = {
                title: this.$t('schoolBaseInfo.saveWarning'),
                content: this.$t('schoolBaseInfo.ssTips8'),
                okText: this.$t('schoolBaseInfo.leaveText'),
                onOk: () => {
                    next()
                },
                onCancel: () => {
                    next(false)
                }
            }
            this.$Modal.confirm(config)
        } else {
            next()
        }
    },
    mounted() {
        this.colorList = ['#F16C6A', '#68CDF1', '#7C4DFF', '#00796B', '#D32F2F', '#0288D1', '#D32F2F', '#00796B', '#7C4DFF', '#0288D1']
    },
    computed: {
        //计算时区设置宽度
        tzWidth() {
            if (this.schoolSetting.timeZone && this.schoolSetting.timeZone.label) {
                return this.getWidth(0, this.schoolSetting.timeZone.label)
            } else {
                return 150
            }
        },
        snWitdh() {
            if (this.schoolSetting.name) {
                return this.getWidth(0, this.schoolSetting.name)
            } else {
                return 150
            }
        },
        dayList() {
            let mon = this.schoolSetting.period[this.curPriodIndex].semesters[this.curSemIndex].month
            let arr = []
            if (mon == 2) {
                arr = [...new Array(29).keys()]
            } else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
                arr = [...new Array(30).keys()]
            } else {
                arr = [...new Array(31).keys()]
            }
            let lang = window.localStorage.getItem('local')
            if (lang.indexOf('CN') != -1 || lang.indexOf('cn') != -1) {
                return arr.map((item) => {
                    return (item + 1) + '日'
                })
            } else if (lang.indexOf('TW') != -1 || lang.indexOf('tw') != -1) {
                return arr.map((item) => {
                    return (item + 1) + '日'
                })
            } else {
                return arr.map((item) => {
                    return item + 1
                })
            }
        },
        editIconStatus() {
            if (this.schoolSetting.period.length > 0) {
                return true
            } else {
                return false
            }
        },
    }
}
</script>

<style lang="less" scoped>
@import "./SystemSetting.less";
</style>
<style>
.school-name .ivu-input-disabled {
    color: white !important;
    margin-top: -4px;
    font-weight: 800;
}
.attr-content .ivu-input-number-disabled .ivu-input-number-input {
    cursor: text;
}

.time-zone-select .ivu-icon-ios-arrow-down:before {
    display: none;
}

.time-zone-select .ivu-select-selection {
    border-color: transparent;
}

.time-zone-select:hover .ivu-select-selection {
    border-color: #606060;
}

.time-zone-select:hover .ivu-icon-ios-arrow-down:before {
    display: inline-block;
}
.attr-box-item .ivu-icon-ios-arrow-down:before {
    display: inline-block !important;
}

.ghost {
    opacity: 0;
    background: #c8ebfb;
}

.second-arrow {
    margin-left: -14px;
}

.semester-name-label .ivu-input[disabled] {
    font-size: 20px !important;
    font-weight: bold;
    color: white;
}

.tag-item .ivu-input[disabled] {
    font-size: 14px !important;
    color: white;
    margin-top: -3px;
}

.term-item-start
    .ivu-select-single
    .ivu-select-selection
    .ivu-select-placeholder,
.term-item-start
    .ivu-select-single
    .ivu-select-selection
    .ivu-select-selected-value {
    padding-right: 6px;
}

.grade-item .ivu-input {
    text-align: center;
}
</style>