
<script lang="ts">
// 年级管理
export default {
  name: 'schoolGrade'
};
</script>

<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from "vue";
import { ElMessage, ElMessageBox, FormRules } from "element-plus";
import { queryRegion } from "@/api/regionmodule/region";
import { querySchoolList } from "@/api/regionmodule/school";
import Page from '@/components/Pagination/page.vue'
import { querySchoolGradePage, addSchoolGrade,updateSchoolGrade,delSchoolGrade } from "@/api/regionmodule/schoolGrade";
import { querySchoolTeacherList } from "@/api/regionmodule/schoolTeacher";
import { publicTree } from '@/utils/validate';
const schoolTeacherData:any = ref([])
function getSchoolTeacher(schoolId:any){
  let params ={
    name:'',
    schoolId:schoolId
  }
  querySchoolTeacherList(params).then((res) => {
    schoolTeacherData.value = res.data;
  
  });
}

const props1 = {
  checkStrictly: true,
  value:'id',
  label:'name'
}
//树形控件类型定义
interface Tree {
  [x: string]: any;
  label: string;
  children?: Tree[];
}
//搜索内容
const querystr = ref("");
// 左侧树
const cascaderdata: any = ref([]);
const defaultProps = { label: "name" };
const handleNodeClick = (data: Tree) => {
  checkedtreeid.value = data.id;
  getSchoolTeacher(data.id)
  getData();
};

const gradeTypeList:any = ref([{
  itemcode:"1",
  dictname:"小学一年级"
},{
  itemcode:"2",
  dictname:"小学二年级"
},{
  itemcode:"3",
  dictname:"小学三年级"
},{
  itemcode:"4",
  dictname:"小学四年级"
},{
  itemcode:"5",
  dictname:"小学五年级"
},{
  itemcode:"6",
  dictname:"小学六年级"
},{
  itemcode:"7",
  dictname:"初中一年级"
},{
  itemcode:"8",
  dictname:"初中二年级"
},{
  itemcode:"9",
  dictname:"初中三年级"
},{
  itemcode:"10",
  dictname:"初中四年级"
},{
  itemcode:"11",
  dictname:"高中一年级"
},{
  itemcode:"12",
  dictname:"高中二年级"
},{
  itemcode:"13",
  dictname:"高中三年级"
},{
  itemcode:"14",
  dictname:"高中四年级"
}])
const infoForm = ref();
const treeRef = ref();
// 表格数组类型定义
const tableData = ref([]);
const checkedtreeid = ref("");
const loading = ref(false);
const treeloading = ref(false);
//新建年级数组
const info:any = ref({
  school_id: "", //学校id
  code: "", // 年级代码
  name: "", // 年级名称
  grade_type:"1",
  org_type:"",
  teacher_id:"",
  teacher_name:""
});
const title = ref("");
const dialogVisible = ref(false);
const regionId =ref(""); //行政区域名称
const cascaderList: any = ref([])

//获取行政区域
function getTree() {
  const params = {
    name: "",
    status:'01'
  };

  queryRegion(params).then((res: any) => {
    cascaderList.value = JSON.parse(JSON.stringify(res.data))
    cascaderdata.value = publicTree(res.data,"");
  })
  .catch((error:any)=>{
    treeloading.value = false
  })
}
const queryInfo :any = ref({
  current:1,
  size:10,
  total:0
})
const treeData:any = ref([])
function getData(){
  querystr.value = querystr.value.replace(/\s+/g, "");
  let params = {
    name: querystr.value,
    schoolId: checkedtreeid.value,
    current: queryInfo.value.current,
    size:queryInfo.value.size
  };
  loading.value = true
  querySchoolGradePage(params).then((res) => {
    tableData.value = res.data.records;
    queryInfo.value.total = res.data.total
    loading.value = false
  });


  

}
//获取年级列表
function getTreeData() {
  if(regionId.value == ''){
    treeData.value = []
    return
  }
  querystr.value = querystr.value.replace(/\s+/g, "");
  let params = {
    name: "",
    regionId: regionId.value,
    type:regionType.value
  };
  treeloading.value = true
  querySchoolList(params).then((res) => {
    treeData.value = res.data;
    treeloading.value = false
    checkedtreeid.value = ""
    if (checkedtreeid.value == "" &&cascaderdata.value.length != 0) {
      checkedtreeid.value = res.data[0].id;
      getSchoolTeacher(checkedtreeid.value)
    }
    nextTick(() => {
      treeRef.value?.setCurrentKey(checkedtreeid.value);
    });
    getData();
    
  }).catch(()=>{
    treeloading.value = false
  });
}
const regionType= ref("")
// 选中区域获取年级列表
function handleChange(value:any){
  isCascader.value = false
  setTimeout(()=>{
    isCascader.value = true
  },20)
  if(value.length != 0){
    regionId.value = value[value.length -1]
    for(let i=0;i<cascaderList.value.length;i++){
      if(regionId.value == cascaderList.value[i].id){
        regionType.value = cascaderList.value[i].type
        break
      }
    }
  }
  getTreeData()
}
function handleClick(data:any){
  if(data.children == null){
    isCascader.value = false
    setTimeout(()=>{
      isCascader.value = true
    },20)
  }
  regionId.value = data.id
  for(let i=0;i<cascaderList.value.length;i++){
    if(regionId.value == cascaderList.value[i].id){
      regionType.value = cascaderList.value[i].type
      break
    }
  }
  getTreeData()
}
const multipleSelection = ref([]);
//定义年级填写规则
const moderules = reactive<FormRules>({
  code: [{ required: true, message: "请输入年级代码", trigger: "blur" }],
  name: [{ required: true, message: "请输入年级名称", trigger: "blur" }],
  // grade_type: [{ required: true, message: "请选择年级类型", trigger: "blur" }],
});
function handleSelectionChange(val: any) {
  multipleSelection.value = val;
}
const isSwitch = ref(false) // 提交开关
//新建年级-保存/修改
function confirmClick(formEl: any) {
  formEl.validate((valid: any) => {
    if (valid) {      
      if(isSwitch.value == true){
        return
      }
      isSwitch.value = true
      if (info.value.id) {
        const data:any = {
          id:info.value.id,
          schoolId: info.value.school_id, //学校ID
          code: info.value.code, // 年级代码
          name: info.value.name, // 年级名称
          gradeType: info.value.grade_type, // 年级类型
          orgType: '6', // 组织类型 6-学校年级
          teacherId: info.value.teacher_id, // 年级主任ID
          teacherName: info.value.teacher_name, // 年级主任名称
        };
        updateSchoolGrade(data).then((item) => {
          dialogVisible.value = false;
          ElMessage({
            message: "修改成功",
            type: "success",
          });
          getData();
        }).catch(()=>{
          isSwitch.value = false
        })
      } else {
        const data:any = {
          schoolId: info.value.school_id, //学校ID
          code: info.value.code, // 年级代码
          name: info.value.name, // 年级名称
          gradeType: '1', // 年级类型
          orgType: '6', // 组织类型 6-学校年级
          teacherId: info.value.teacher_id, // 年级主任ID
          teacherName: info.value.teacher_name, // 年级主任名称
        };
        addSchoolGrade(data).then((item) => {
          dialogVisible.value = false;
          getData();
          ElMessage({
            message: "新增成功",
            type: "success",
          });
        }).catch(()=>{
          isSwitch.value = false
        })
      }  
    }
  })
}
//关闭弹窗
function handleClose() {
  if (infoForm.value != null) infoForm.value.resetFields();
  dialogVisible.value = false;
}


//新建年级
function addClick() {
  isSwitch.value = false
  const infoagin = ref({
    id: null,
    school_id: checkedtreeid.value, //区域ID （年级所在城市
    code: "", // 年级代码
    name: "", // 年级名称
    grade_type:"",
    org_type:"",
    teacher_id:"",
    teacher_name:""

  });
  info.value = infoagin.value;
  title.value = "新增年级";
  dialogVisible.value = true;
}
//修改年级
function editHandle(row: any) {
  isSwitch.value = false
  title.value = "修改年级";
  info.value = JSON.parse(JSON.stringify(row));
  dialogVisible.value = true;
}
//删除年级
function delHandle(row: any) {
  ElMessageBox.confirm("确定删除此年级吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let params = {
      ids: row.id,
    };
    delSchoolGrade(params).then((res:any) => {
      if(res.code =='0'){
        getData();
        ElMessage({
          message: "删除成功",
          type: "success",
        });
      }else{
        ElMessage({
          message: res.msg,
          type: "error",
        });
      }
    });
  });
}
// 多选删除年级
function delClick() {
  ElMessageBox.confirm("确定删除已选择的年级吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let id = [] as any[];
    multipleSelection.value.forEach((item: any) => {
      id.push(item.id)
    })
    let params = {
      ids: id.join(','),
    };
    delSchoolGrade(params).then(() => {
      getData();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    });
  });
}
function dateFormat(row: any) {
  const daterc = row;
  if (daterc != null) {
    var date = new Date(daterc);
    var year = date.getFullYear();
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    // 拼接
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  }
}
onMounted(() => {
  getTree();
});
const vMove = {
  mounted(el: any) {
    el.onmousedown = function (e: any) {
      var init = e.clientX;
      var parent: any = document.getElementById("silderLeft");
      const initWidth: any = parent.offsetWidth;
      document.onmousemove = function (e) {
        var end = e.clientX;
        var newWidth = end - init + initWidth;
        parent.style.width = newWidth + "px";
      };
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null;
      };
    };
  }
}


function publicDict(list: any, itemcode: any) {
    let dictname = ''
    list.forEach((element: any) => {
        if (element.itemcode == itemcode) {
            dictname = element.dictname
        }
    })
    return dictname
}

function teacherChange(e:any){
  for(let i=0;i<schoolTeacherData.value.length;i++){
    if(schoolTeacherData.value[i].id == e){
      info.value.teacher_name = schoolTeacherData.value[i].name
    }
  }
}
const isCascader=ref(true)
</script>

<template>
  <div class="faulttemplate-box">
    <aside id="silderLeft">
      <div class="lefttitle">
        <div class="line"></div>
        <div class="treetitle">学校列表</div>
      </div>
      <div style="width:100% ;height:32px; display: flex;">
        <el-cascader v-if="isCascader" style="width: 90%; margin: auto;" placeholder="请输入行政区域" v-model="regionId" :options="cascaderdata" :props="props1" :show-all-levels="false"
        filterable @change="handleChange">
          <template #default="{ node, data }">
            <div @click.stop="handleClick(data)">{{ data.name }}</div>
          </template>
        </el-cascader>
      </div>
       <!-- <el-input v-model="regionName" placeholder="请输入行政区域" clearable style="width: 100%;margin-bottom: 10px;" 
         @keyup.enter="getTree" /> -->
         <el-tree v-loading="treeloading"
          ref="treeRef" node-key="id" :data="treeData" :highlight-current="true" :props="defaultProps"
          :expand-on-click-node="false"
          @node-click="handleNodeClick" style="height: calc(100vh - 245px); overflow: auto;margin-top: 10px;">
        </el-tree>
      
      <div class="moveBtn" v-move>
        <div class="moveBtn-line" v-move></div>
      </div>
    </aside>
    <main class="silderRight">
      <el-row style="margin-bottom: 10px">
        <el-col :span="24" class="top-nav">
          <div>
            <el-input v-model="querystr" placeholder="请输入年级名称" clearable style="width: 200px;"
              @keyup.enter="getData" />
            <el-button type="primary" style="margin-left: 10px;" @click="getData">搜索</el-button>
          </div>
          <div class="left-nav">
            <el-button :disabled="regionId==''" type="primary" @click="addClick"><img style="margin-right:5px;" src="@/assets/MenuIcon/jscz_xz.png" alt=""> 新增</el-button>
          </div>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="tableData" style="width: 100%; height:calc(100% - 105px);" row-key="id" border
        @selection-change="handleSelectionChange" default-expand-all :header-cell-style="{background:'rgb(250 250 250)',height:'50px'}"
        >
        <!-- <el-table-column type="selection" width="50" align="center" /> -->
        <!-- <el-table-column prop="code" label="年级代码" min-width="100"></el-table-column> -->
        <el-table-column prop="name" label="年级名称" min-width="140"></el-table-column>
        <!-- <el-table-column prop="grade_type" label="年级类型" min-width="140">
          <template #default="scope">
            {{ publicDict(gradeTypeList,scope.row.grade_type) }}
          </template>
        </el-table-column> -->
        <!-- <el-table-column prop="org_type" label="组织类型" min-width="140"></el-table-column> -->
        <el-table-column prop="teacher_name" label="年级主任" min-width="140"></el-table-column>
        <el-table-column prop="creator" label="创建人" width="174"></el-table-column>
        <el-table-column prop="create_time" label="创建日期" width="196">
          <template #default="scope">
            {{ dateFormat(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80">
          <template #default="scope">
            <span style="display: flex;display: -webkit-flex;justify-content: space-around; -webkit-justify-content: space-around; ">
              <img src="@/assets/MenuIcon/lbcz_xg.png" title="修改" style="cursor: pointer;"
              @click="editHandle(scope.row)" >
            <img src="@/assets/MenuIcon/lbcz_sc.png" title="删除" style="cursor: pointer;"
              @click="delHandle(scope.row)" >
            </span>
          </template>
        </el-table-column>
      </el-table>
      <Page class="mt-[20px]" :total="queryInfo.total" v-model:size="queryInfo.size" v-model:current="queryInfo.current"
          @pagination="getData" />
    </main>

    <!-- 年级 弹框-->
    <el-dialog v-model="dialogVisible" :before-close="handleClose" :title="title" draggable width="620px">
      
      <el-form ref="infoForm" :model="info" label-width="100px" :rules="moderules">
        <el-form-item label="年级代码" prop="code">
          <el-input v-model="info.code" style="width: 100%"  placeholder="请输入年级代码"></el-input>
        </el-form-item>
        <el-form-item label="年级名称" prop="name">
          <el-input v-model="info.name" style="width: 100%" placeholder="请输入年级名称"></el-input>
        </el-form-item>
        <!-- <el-form-item label="年级类型" prop="grade_type">
          <el-select v-model="info.grade_type" class="!w-full" placeholder="请选择年级类型">
            <el-option v-for="(i, index) in gradeTypeList" :key="index" :label="i.dictname"
              :value="i.itemcode"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="年级主任" prop="teacher_name">
          <el-select v-model="info.teacher_id" class="!w-full" placeholder="请选择年级主任" @change="teacherChange"
            filterable>
            <el-option v-for="(i, index) in schoolTeacherData" :key="index"  :label="i.code + ' - ' +  i.name +
            ' - ' + (i.gender == '0'?'不详':'') + (i.gender == '1'?'男':'') + (i.gender == '2'?'女':'')
            "
              :value="i.id">
              <span>{{ i.code }}</span>
              <span> - </span>
              <span>{{ i.name }}</span>
              <span> - </span>
              <span v-if="i.gender == '0'">不详</span>
              <span v-if="i.gender == '1'">男</span>
              <span v-if="i.gender == '2'">女</span>
            </el-option>
          </el-select>

        </el-form-item>
      </el-form>
      <span class="dialog-footer">
        <el-button style="padding: 10px 15px" @click="handleClose">取 消</el-button>
        <el-button type="primary" style="padding: 10px 15px" @click="confirmClick(infoForm)">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style scoped  lang="scss">
.silderLeft-default {
  :deep(.custom-tree-node, .treedelicon, .treeediticon) {
    font-size: 16px !important;
  }

  :deep(.custom-tree-large, .treedelicon, .treeediticon) {
    font-size: 14px !important;
  }
}

.faulttemplate-box {
  height: 100%;
  display: -webkit-flex;
  display: flex;
  background-color: #f2f4f9;
}

#silderLeft {
  width: 255px;
  box-sizing: border-box;
  background: #fff;
  border-radius: 3px;
  position: relative;
  &:hover {
    .moveBtn {
      opacity: 1;
    }
  }
}

/* 拖动条 */
.moveBtn {
  height: 100%;
  width: 15px;
  padding: 0 6px;
  opacity: 0;
  position: absolute;
  right: -15px;
  top: 0;
}

.moveBtn-line {
  width: 100%;
  height: 100%;
  cursor: col-resize;
  user-select: none;
  background-color: #60bfff;
}

.dialog-footer {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  -webkit-justify-content: flex-end;
}

.silderRight {
  flex: 1;
  position: relative;
  width: 100%;
  height: calc(100vh - 130px);
  overflow: auto;
  background-color: rgba(255, 255, 255, 1);
  border-radius: 3px;
  padding: 15px;
  padding-bottom: 0px;
  margin-left: 15px;
  box-sizing: border-box;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  width: 100%;
  height: 40px;
  background-color: #409eff !important;
  color: #fff !important;
}

:deep(.el-tree-node__content) {
  width: 100%;
  height: 40px;
  line-height: 40px;
}

:deep(.el-tree-node__content:hover) {
  background-color: #409eff19;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  display: -webkit-flex;
  align-items: center;
  -webkit-align-items: center;
  justify-content: space-between;
  -webkit-justify-content: space-between; 
  padding-right: 8px;

}

.faulttemplate-box {
  .is-current .treeediticon {
    color: #ffffff !important;
  }

  .is-current .treedelicon {
    color: #ffffff !important;
  }

  .el-tree-node__content:hover .treeediticon {
    color: #00cccc;
  }

  .el-tree-node__content:hover .treedelicon {
    color: #f56c6c;
  }
}

.treeediticon,
.treedelicon {
  color: #fff;
  margin: 0 5px;
}
:deep(.el-table__cell){
  color: #383838;
}
.top-nav {
  display: -webkit-flex;
  display: flex;
  justify-content: space-between;
  -webkit-justify-content: space-between;
}

.lefttitle {
  min-width: 130px;
  display: flex;
  align-items: center;
  padding: 10px 15px;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial';
  font-weight: 700;
  font-style: normal;
  font-size: 16px;
  color: #1B1B1B;
  border-bottom: 1px var(--el-border-color) var(--el-border-style);
  margin-bottom: 10px;
  .line{
    border-width: 0px;
    width: 5px;
    height: 14px;
    margin-right: 7px;
    background: inherit;
    background-color: rgba(64, 158, 255, 1);
    border: none;
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
  }
}
:deep(.el-upload--picture-card){
  --el-upload-picture-card-size: 148px;
    background-color: var(--el-fill-color-lighter);
    border: 1px dashed var(--el-border-color-darker);
    border-radius: 6px;
    box-sizing: border-box;
    width: var(--el-upload-picture-card-size);
    height: var(--el-upload-picture-card-size);
    cursor: pointer;
    vertical-align: top;
    display: inline-flex;
    justify-content: center;
    align-items: center;
}
.newavatar-uploader-icon{
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  text-align: center;
}
.newavatar-uploader-text{
  width: 100%;text-align: center;line-height: 20px;
  font-family: 'Arial Normal', 'Arial';
    font-weight: 400;
    font-style: normal;
    font-size: 12px;
    color: #949494;
}
</style>
