<style lang="less" scoped>
  @import './SystemSetting.less';
</style>
<style>
  .second-arrow {
    margin-left: -16px;
  }
  .color-check {
    color: #08d0c8;
  }
  .color-uncheck {
    color: #FF6C6B;
  }
  .bg-color-check {
    background-color: #08d0c8 !important;
  }
  .bg-color-uncheck {
    background-color: #FF6C6B !important;
  }
</style>
<template>
  <div class="sm-system">
    <div class="sm-school-name">
      <div>
        <span class="setting-title">{{$t('schoolBaseInfo.schoolNameLabel')}}</span>
        <!--<span class="school-name">{{schoolSetting.name}}</span>-->
        <div class="editable">
          <EditableLabel ref="schoolName" class="school-name" :content="schoolSetting.name" @editComplete="handleEditSchoolName($event,-1)">
          </EditableLabel>
          <Icon type="md-create" class="edit-btn" title="编辑" @click="changeSchoolNameStatus()" />
        </div>
      </div>
      <span class="school-tools" @click="saveData()" v-if="updated"><Icon type="ios-albums-outline" />{{$t('schoolBaseInfo.saveInfo')}}</span>
    </div>

    <div class="sm-system-body">
      <div class="sm-system-left">
        <div class="col-title">
          <span>{{$t('schoolBaseInfo.periodSettingLabel')}}</span>
          <Icon type="md-add" @click="addPeriod()" />
        </div>
        <div class="col-order">
          <Icon type="md-cube" />
          <span>{{$t('schoolBaseInfo.order')}}</span>
        </div>
        <div class="period-list">
          <div class="period-item" v-for="(item,index) in schoolSetting.period" :key="index" @click="choosePeriod(index)" :class="index == currentSchoolSysIndex ? 'item-active-div':''">
            <p class="period-item-name">
              <EditableLabel ref="periodName" class="term-item-name" :content="item.name" @editComplete="handleEditPeriod($event,index)">
              </EditableLabel>
              <Icon type="md-create" class="period-btn-edit" title="编辑" @click="changePeriodEditStatus(index)" />
            </p>
            <p class="period-item-num"><span></span>{{ $t('schoolBaseInfo.semesterNum') + item.semester.length}}</p>
            <p class="period-item-num"><span></span>{{ $t('schoolBaseInfo.gradeNum') + item.grade.length}}</p>
            <p class="period-item-num"><span></span>{{ $t('schoolBaseInfo.periodNum') + item.subject.length}}</p>
            <div class="period-item-tool">
              <!--<Icon type="ios-copy" title="不知道" />-->
              <Icon type="md-trash" title="删除" @click.stop="delPeriod(index)" />
            </div>
          </div>
        </div>
      </div>
      <div class="sm-system-center">
        <div class="col-title">
          <span>{{$t('schoolBaseInfo.semesterSetting')}}</span>
          <Icon type="md-add" @click="handleAddTerm" />
        </div>
        <div class="col-body">
          <div class="no-data-text" v-if="!schoolSetting.period[currentSchoolSysIndex].semester.length">{{$t('schoolBaseInfo.noSemester')}}</div>
          <div class="term-list" v-if="schoolSetting.period[currentSchoolSysIndex].semester.length">
            <div class="term-item editable" v-for="(item,index) in schoolSetting.period[currentSchoolSysIndex].semester" :key="index" :class="index == currentSemesterIndex ? 'item-active-div':''" @click="chooseSemester(index)">
              <span class="term-item-name-line" :style="{backgroundColor: colorList[index]}"></span>
              <EditableLabel ref="semesterName" class="term-item-name" :content="item.name" @editComplete="handleEditSemester($event,index)">
              </EditableLabel>
              <Icon type="md-create" class="edit-btn" :title="$t('schoolBaseInfo.editLabel')" @click="changeSemesterStatus(index)" />
              <!--<p class="term-item-students-num">涉及学生数：0人</p>-->
              <div class="term-item-start">
                <span>{{$t('schoolBaseInfo.startDate')}}</span>
                <Select v-model="item.month" :placeholder="$t('schoolBaseInfo.monthHolder')">
                  <Option v-for="(item,index) in monthList" :value="item" :key="index">{{ item }}</Option>
                </Select>
                <span> / </span>
                <Select v-model="item.day" :placeholder="$t('schoolBaseInfo.dayHolder')" @on-change="test()">
                  <Option v-for="(item,index) in dayList" :value="(item+1).toString()" :key="index">{{ (item+1).toString() }}</Option>
                </Select>
              </div>
              <p class="term-item-students-num">{{$t('schoolBaseInfo.semesterDuration')+"156" + $t('schoolBaseInfo.dayUnit')  }}</p>
              <div class="term-item-tool">
                <Icon type="md-trash" :title="$t('schoolBaseInfo.delete')" @click.stop="delSemester(index)" />
              </div>
            </div>
          </div>
          <div class="term-item-time-line" v-if="schoolSetting.period[currentSchoolSysIndex].semester.length">
            <ul>
              <li v-for="(item,index) in monthEnList" :key="index">
                <span class="time-label">{{item}}.</span>
                <span class="time-dot">
                  <span v-if="auto" class="time-inner-dot" :class="index + 1 >= schoolSetting.period[currentSchoolSysIndex].semester[currentSemesterIndex].month && index < endMonth ? 'bg-color-check':'bg-color-uncheck'"></span>
                  <span v-else class="time-inner-dot" :class="index + 1 >= schoolSetting.period[currentSchoolSysIndex].semester[currentSemesterIndex].month || index < endMonth ? 'bg-color-check':'bg-color-uncheck'"></span>
                  <span class="time-line-tail"></span>
                </span>
                <div>
                  <Icon class="first-arrow" size="22" type="ios-arrow-back" v-if="index + 1 == schoolSetting.period[currentSchoolSysIndex].semester[currentSemesterIndex].month || index + 1 == endMonth" />
                  <!--<Icon class="second-arrow" size="22" :class="index  < endMonth ? 'color-check':'color-uncheck'" type="ios-arrow-back" v-if="index + 1 == schoolSetting.period[currentSchoolSysIndex].semester[currentSemesterIndex].month || index + 1 == endMonth" />-->
                  <span v-if="auto">
                    <Icon class="second-arrow" size="22" :class="index  < endMonth ? 'color-check':'color-uncheck'" type="ios-arrow-back" v-if="index + 1 == schoolSetting.period[currentSchoolSysIndex].semester[currentSemesterIndex].month || index + 1 == endMonth" />
                  </span>
                  <span v-else>
                    <Icon class="second-arrow" size="22" :class="index + 1 >= endMonth ? 'color-check':'color-uncheck'" type="ios-arrow-back" v-if="index + 1 == schoolSetting.period[currentSchoolSysIndex].semester[currentSemesterIndex].month || index + 1 == endMonth" />
                  </span>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="sm-system-right">
        <div class="col-title">
          <span>{{$t('schoolBaseInfo.gradeSetting')}}</span>
          <div>
            <Icon type="md-add" @click="addGrade" />
            <Icon type="md-trash" v-show="gradeSelectList.length" />
          </div>
        </div>
        <div class="grade-body">
          <div class="grade-item item-active" v-for="(item,index) in schoolSetting.period[currentSchoolSysIndex].grade" :key="index">
            <span class="grade-item-icon"></span>
            <EditableLabel ref="gradeName" class="grade-item-name" :content="item.name" @editComplete="handleEditGrade($event,index)">
            </EditableLabel>
            <Icon type="md-create" class="period-btn-edit" title="编辑" @click="changeGradeEditStatus(index)" />
            <Icon type="md-close" @click="delGrade(index)" />
          </div>
        </div>
        <div class="col-title">
          <span>{{$t('schoolBaseInfo.subjectSetting')}}</span>
          <div>
            <Icon type="md-add" @click="addSubject()" />
            <Icon type="md-trash" v-show="subjectSelectList.length" />
          </div>
        </div>
        <div class="grade-body">
          <div class="grade-item item-active" v-for="(item,index) in schoolSetting.period[currentSchoolSysIndex].subject" :key="index">
            <span class="grade-item-icon"></span>
            <EditableLabel ref="subjectName" class="grade-item-name" :content="item.name" @editComplete="handleEditSubject($event,index)">
            </EditableLabel>
            <Icon type="md-create" class="period-btn-edit" :title="$t('schoolBaseInfo.editLabel')" @click="changeSubjectEditStatus(index)" />
            <Icon type="md-close" @click="delSubject(index)" />
          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
  import EditableLabel from "@/common/EditableLabel.vue"

    //学期默认模板
  const defaultTerm = {
    name: "点击设置名称",
    startMonth: 1,
    startDay:1,
    durationDays:157
  }
  export default {
    components: {
      EditableLabel
    },
    data() {
      return {
        demoLoginInfo: {
          user: "admin",
          teamModelId: "habook#0001",
          school: "醍摩豆书院",
          schoolCode:"HBCN"
        },
        auto: true,
        updated:false,
        currentSchoolSysIndex:0,
        currentSemesterIndex: 0,
        isInit: true,
        schoolSetting: {
          code: "",
          name: "",
          period: []
        },
        tabIndex: 0,
        periodList: [
          {
            name:"紫藤小学北区"
          }
        ],
        termList: [],
        gradeList:[],
        subjectList:[],
        monthList: [],
        monthEnList:[],
        dayList: [],
        colorList:[],
        gradeSelectList:[],
        subjectSelectList:[],
        termMonthVal:1,
        termDayVal: 1,
        TERM_MAX_LENGTH:3, //学期数上限
      }
    },
    methods: {
      //删除节点
      delGrade(index) {
        this.schoolSetting.period[this.currentSchoolSysIndex].grade.splice(index, 1);
      },
      delSubject(index) {
        this.schoolSetting.period[this.currentSchoolSysIndex].subject.splice(index, 1);
      },
      delPeriod(index) {
        if (this.currentSchoolSysIndex >= index && index > 0) {
          this.currentSemesterIndex = 0;
          this.currentSchoolSysIndex = 0;
        }
        if (this.schoolSetting.period.length > 1) {
          this.currentSchoolSysIndex = 0;
          this.currentSemesterIndex = 0;
          this.schoolSetting.period.splice(index, 1);
        } else {
          this.$Message.warning(this.$t('schoolBaseInfo.ssTips2'));
        }
      },
      delSemester(index) {
        if (this.schoolSetting.period[this.currentSchoolSysIndex].semester.length > 1) {
          this.currentSchoolSysIndex = 0;
          this.currentSemesterIndex = 0;
          this.schoolSetting.period[this.currentSchoolSysIndex].semester.splice(index, 1);
        } else {
          this.$Message.warning(this.$t('schoolBaseInfo.ssTips2'));
        }
      }, 
      initData() {
        this.schoolSetting.code = this.demoLoginInfo.schoolCode;
        this.schoolSetting.name = this.demoLoginInfo.school;
        this.schoolSetting.period.push({
          name: this.$t('schoolBaseInfo.presetPeriod')+"1",
          code: this.guid(),
          gradeCount: 0,
          semesterCount: 0,
          subjectCount: 0,
          semester: [],
          grade: [],
          subject: []
        });
        this.schoolSetting.period[0].grade.push({
          name: this.$t('schoolBaseInfo.presetGrade1'),
          code: this.guid()
        });
        this.schoolSetting.period[0].grade.push({
          name: this.$t('schoolBaseInfo.presetGrade2'),
          code: this.guid()
        });
        this.schoolSetting.period[0].grade.push({
          name: this.$t('schoolBaseInfo.presetGrade3'),
          code: this.guid()
        });
        this.schoolSetting.period[0].subject.push({
          name: this.$t('schoolBaseInfo.presetSubject1'),
          code: this.guid()
        });
        this.schoolSetting.period[0].subject.push({
          name: this.$t('schoolBaseInfo.presetSubject2'),
          code: this.guid()
        });
        this.schoolSetting.period[0].subject.push({
          name: this.$t('schoolBaseInfo.presetSubject3'),
          code: this.guid()
        });
        this.updated = false;
      },
      changeGradeEditStatus(index) {
        this.$refs.gradeName[index].handleEdit();
      },
      changeSubjectEditStatus(index) {
        this.$refs.subjectName[index].handleEdit();
      },
      chooseSemester(index) {
        this.currentSemesterIndex = index;
      },
      choosePeriod(index) {
        this.currentSemesterIndex = 0;
        this.currentSchoolSysIndex = index;

      },
      saveData() {
        this.handleData();
        this.$api.schoolSetting.schoolSettingSaveOrUpdate(this.schoolSetting).then(res => {
          if (res.error == null) {
            this.$Message.success(this.$t('schoolBaseInfo.ssTips3'));
            this.updated = false;
          }
        }
        );
      },
      getData() {
        this.$api.schoolSetting.findSchoolSystem({
          Code: this.demoLoginInfo.schoolCode
        }).then(res => {
          if (res.error == null) {
            if (res.result.data.length > 0) {
              this.schoolSetting = res.result.data[0];
              this.updated = false;
            } 
            console.log(this.schoolSetting);
          }
        }
        );
      },
      handleData() {
        for (let i = 0; i < this.schoolSetting.period.length; i++) {
          this.schoolSetting.period[i].gradeCount = this.schoolSetting.period[i].grade.length;
          this.schoolSetting.period[i].semesterCount = this.schoolSetting.period[i].semester.length;
          this.schoolSetting.period[i].subjectCount = this.schoolSetting.period[i].subject.length;
        }
      },
      handleEditGrade(val, index) {
        let flag = false;
        this.schoolSetting.period[this.currentSchoolSysIndex].grade.forEach((v, i) => {
          if (v.name == val) {
            flag = true;
          }
        });
        if (flag) {
          this.$Message.warning(this.$t('schoolBaseInfo.ssTips4'));
        } else {
          this.schoolSetting.period[this.currentSchoolSysIndex].grade[index].name = val;
        }
        
      },
      handleEditSubject(val, index) {
        let flag = false;
        this.schoolSetting.period[this.currentSchoolSysIndex].subject.forEach((v, i) => {
          if (v.name == val) {
            flag = true;
          }
        });
        if (flag) {
          this.$Message.warning(this.$t('schoolBaseInfo.ssTips4'));
        } else {
          this.schoolSetting.period[this.currentSchoolSysIndex].subject[index].name = val;
        }
      },
      handleEditSchoolName(val) {
        this.schoolSetting.name = val;
      },
      handleEditPeriod(val, index) {
        let flag = false;
        this.schoolSetting.period.forEach((v, i) => {
          if (v.name == val) {
            flag = true;
          }
        });
        if (flag) {
          this.$Message.warning(this.$t('schoolBaseInfo.ssTips4'));
        } else {
          this.schoolSetting.period[index].name = val;
        }
      },
      handleEditSemester(val, index) {
        let flag = false;
        this.schoolSetting.period[this.currentSchoolSysIndex].semester.forEach((v, i) => {
          if (v.name == val) {
            flag = true;
          }
        });
        if (flag) {
          this.$Message.warning(this.$t('schoolBaseInfo.ssTips4'));
        } else {
          this.schoolSetting.period[this.currentSchoolSysIndex].semester[index].name = val;
        }
      },
      changePeriodEditStatus(index) {
        this.$refs.periodName[index].handleEdit();
      },
      changeSchoolNameStatus() {
        this.$refs.schoolName.handleEdit();
      },
      changeSemesterStatus(index) {
        this.$refs.semesterName[index].handleEdit();
      },
      addSubject() {
        if (this.termList.length < this.TERM_MAX_LENGTH) {
          let newTerm = Object.assign({}, defaultTerm);
          this.schoolSetting.period[this.currentSchoolSysIndex].subject.push({
            name: this.$t('schoolBaseInfo.presetSubject')+(this.schoolSetting.period[this.currentSchoolSysIndex].subject.length+1),
            code:this.guid()
          });
        } else {
          this.$Message.info(this.$t('schoolBaseInfo.ssTips5'));
        }
      },
      guid() {
        function S4() {
          return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
      },
      addGrade() {
        if (this.termList.length < this.TERM_MAX_LENGTH) {
          let newTerm = Object.assign({}, defaultTerm);
          this.schoolSetting.period[this.currentSchoolSysIndex].grade.push({
            name: this.$t('schoolBaseInfo.persetGrade')+(this.schoolSetting.period[this.currentSchoolSysIndex].grade.length),
            code:this.guid()
          });
        } else {
          this.$Message.info(this.$t('schoolBaseInfo.ssTips6'));
        }
      },
      addPeriod() {
        this.schoolSetting.period.push({
          name: this.$t('schoolBaseInfo.presetPeriod') + (this.schoolSetting.period.length + 1),
          code: this.guid(),
          gradeCount: 0,
          semesterCount: 0,
          subjectCount: 0,
          semester: [
            {
              name: this.$t('schoolBaseInfo.persetSemester') +  "1",
              studentCount: "学生人数",
              month: this.schoolSetting.period[this.currentSchoolSysIndex].semester[this.currentSemesterIndex].month + 1,
              day: 26
            }
          ],
          grade: [
            {
              code: "年级编码",
              name: this.$t('schoolBaseInfo.persetGrade') +  "1"
            }
          ],
          subject: [
            {
              code: "科目编码",
              name: this.$t('schoolBaseInfo.presetSubject') +  "1"
            }
          ]
        });
      },
      //获取随机颜色十六进制
      getRandomColor() {
        return '#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0');
      },
      //添加学期
      handleAddTerm() {
        if (this.termList.length < this.TERM_MAX_LENGTH) {
          let newTerm = Object.assign({}, defaultTerm);
          let defMonth = this.schoolSetting.period[this.currentSchoolSysIndex].semester.length == 0 ? 1 : this.schoolSetting.period[this.currentSchoolSysIndex].semester[this.currentSemesterIndex].month + 1;
          this.schoolSetting.period[this.currentSchoolSysIndex].semester.push({
            name: this.$t('schoolBaseInfo.persetSemester') + (this.schoolSetting.period[this.currentSchoolSysIndex].semester.length+1),
            studentCount: "学生人数",
            month: defMonth,
            day: 26
          });
        } else {
          this.$Message.info(this.$t('schoolBaseInfo.ssTips7'));
        }
      },
      //年级选择事件
      handleGradeClick(item, e) {
        e.preventDefault();
        let isExist = this.gradeSelectList.indexOf(item);
        if (isExist > -1) {
          this.gradeSelectList.splice(isExist, 1);
        } else {
          this.gradeSelectList.push(item);
        }
      },

      //年级选择事件
      handleSubjectClick(item, e) {
        e.preventDefault();
        let isExist = this.subjectSelectList.indexOf(item);
        if (isExist > -1) {
          this.subjectSelectList.splice(isExist, 1);
        } else {
          this.subjectSelectList.push(item);
        }
      },

    },
    watch: {
      schoolSetting: {
        handler(newValue, oldValue) {
          if (this.isInit) {
            this.isInit = false;
          } else {
            this.updated = true;
          }
　　　　},
　　　　deep: true
      }
    },
    created() {
      this.initData();
      this.getData();
    },
    beforeRouteLeave(to, from, next) {
      if (this.updated == true) {
        let config = {
          render: (h) => {
            return h("h3", {
              style: {
                  textAlign: "center",
              },
              domProps: {
                innerText: this.$t('schoolBaseInfo.ssTips8')
               }
            } );
          },
          onOk: () => {
            next();
          },
          onCancel: () => {
            next(false)
          }
        }
        this.$Modal.confirm(config);
      } else {
         next();
      }
    },
    mounted() {
      this.monthList = ['1','2','3','4','5','6','7','8','9','10','11','12',];
      //this.monthList = [...Array(12).keys()];
      this.gradeList = ['一年级','二年级','三年级','四年级','五年级'];
      this.subjectList = ['语文','数学','外语','化学','物理','语文','数学','外语','化学','物理'];
      this.dayList = [...Array(30).keys()];
      this.monthEnList = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
      this.colorList = ['#F16C6A', '#68CDF1', '#00796B', '#7C4DFF', '#0288D1', '#D32F2F', '#00796B', '#7C4DFF', '#0288D1', '#D32F2F', '#00796B', '#7C4DFF'];
      
    },
    computed: {
      endMonth() {
        let end = 1;
        if(this.schoolSetting.period[this.currentSchoolSysIndex].semester.length == 1){
          end = 12;
          this.auto = true;
        } else if (this.currentSemesterIndex + 1 < this.schoolSetting.period[this.currentSchoolSysIndex].semester.length) {
          end = this.schoolSetting.period[this.currentSchoolSysIndex].semester[this.currentSemesterIndex + 1].month;
          this.auto = true;
        } else if (this.currentSemesterIndex + 1 == this.schoolSetting.period[this.currentSchoolSysIndex].semester.length){
          end = this.schoolSetting.period[this.currentSchoolSysIndex].semester[0].month;
          this.auto = false;
        }
        return end;
      }
    }

  }
</script>

<!-- 覆盖iview样式 -->
<style>
  .term-item-start .ivu-select {
    width:60px;
    color:rgb(191, 191, 191);
    margin:0 10px;
  }

  .term-item-start .ivu-select-selected-value {
    font-size:16px !important;
  }

  .term-item-start .ivu-select-selection {
    background:#333333;
    border-color:rgba(196,196,196,.2);
    border-radius: 8px;
  }

  .term-item-start .ivu-select-arrow {
   /*top:72%;*/
  }
</style>
