<template>
  <q-dialog v-model="persistent" content-class="bg-grey-1" persistent transition-show="scale" transition-hide="scale">
    <q-card style="width: 800px;max-width:900px;">
      <q-card-section>
        <div class="text-h6">{{objOption.TId==0?'新增教师信息':'修改教师信息'}}</div>
      </q-card-section>
      <q-card-section class="q-pt-none scroll" style="max-height: 70vh">
        <div class="text-caption q-mb-lg q-px-md text-grey-6">基本资料</div>
        <div class="row wrap">
          <q-input filled stack-label maxlength="15" :dense="false" v-model="objOption.TeacherName" ref="TeacherName"
            class="col-6 q-pr-lg q-pb-lg" label="教师名称" :rules="[val => !!val || '请填写教师姓名']" />
          <q-select filled stack-label option-value="SId" option-label="SName" v-model="objOption.School_Id"
            ref="School_Id" :options="schoolList" label="所属校区" :dense="false" class="col-6 q-pb-lg" emit-value
            map-options :rules="[val => !!val || '请选择所属校区']" @input="schoolChagne" />
          <q-input type="tel" filled stack-label maxlength="20" :dense="false" v-model="objOption.TeacherTel"
            ref="TeacherTel" class="col-6 q-pr-lg q-pb-lg" label="联系电话" :rules="[val => !!val || '请填写教师联系电话']" />
          <q-input filled stack-label maxlength="100" :dense="false" v-model="objOption.TeacherSay" ref="TeacherSay"
            class="col-6 q-pb-lg" label="教师营销语" />
          <selectTree v-if="DeptList&&DeptList.length>0" :treeData='DeptList' :defaultArray="returnString"
            nodeKey="DeptId" :multiple="false" labelKey="DeptName" childrenKey="ChildList" tipText="选择部门"
            @getChild="getChild" classStr="col-6 q-pr-lg q-pb-lg"></selectTree>
          <q-select filled stack-label option-value="PostId" option-label="PostName" v-model="objOption.Post_Id"
            ref="Post_Id" :options="PostList" label="岗位" :dense="false" class="col-6 q-pr-lg q-pb-lg" emit-value
            map-options />
          <q-input filled stack-label maxlength="5" :dense="false" v-model="objOption.BaseStuNum" ref="BaseStuNum"
            class="col-6 q-pb-lg q-pr-lg" label="带班基础人数" @keyup.native="checkInteger(objOption,'BaseStuNum')" />
          <q-input filled stack-label maxlength="5" :dense="false" v-model="objOption.BaseHourFee" ref="BaseHourFee"
            class="col-6 q-pr-lg q-pb-lg" label="基础课时费" @keyup.native="checkPrice(objOption,'BaseHourFee')" />
        </div>
        <div class="row wrap">
          <div class="col-6 q-pr-lg q-pb-lg">
            <q-uploader style="display: inline-block;height: 320px;max-width: 100%; background-repeat:no-repeat"
              :style="{'background-image':'url(' + objOption.TeacherHead + ')'}" max-files="1" hide-upload-btn
              @rejected="onRejected" label="教师头像" :max-file-size="5*1024*1024" accept=".jpg, image/*" auto-upload
              :factory="uploadFile" no-thumbnails @added="getType(1)">
            </q-uploader>
          </div>
          <div class="col-6 q-pb-lg">
            <q-uploader style="display: inline-block;height:320px; max-width: 100%;background-repeat:no-repeat"
              :style="{'background-image':'url(' + objOption.TeacherIcon + ')'}" max-files="1" hide-upload-btn
              @rejected="onRejected" label="教师形象照" :max-file-size="5*1024*1024" accept=".jpg, image/*" auto-upload
              :factory="uploadFile" no-thumbnails @added="getType(2)">
            </q-uploader>
          </div>
        </div>
        <ext-editor :defaultMsg="objOption.TeacherIntro" classStr="col-12" @getEditValue="getEditValue"></ext-editor>
        <div class="row wrap">
          <div class="col-6 q-pr-lg q-pb-lg">
            <q-toggle size="md" label="是否显示" color="primary" :false-value="0" :true-value="1"
              v-model="objOption.IsShow" />
            <div class="text-grey-6 text-caption">注意：隐藏后，教师将在其他任何地方无法显示</div>
          </div>
          <div class="col-6 q-pb-lg">
            <q-toggle size="md" label="是否推荐" color="primary" :false-value="0" :true-value="1"
              v-model="objOption.IsRecommend" />
            <div class="text-grey-6 text-caption">注意：推荐后教师将在营销端呈现</div>
          </div>
        </div>
        <div class="col-12 q-pb-lg">
          <q-field filled label="教师标签" bg-color="white" stack-label>
            <template v-slot:control>
              <div class="q-pt-md row" tabindex="0">
                <div v-if="tags.length<5" class="q-mr-md">
                  <input type="text" placeholder="输入标签后回车确认" v-model="tagText" class="tag-input"
                    @keyup.enter="createTag">
                </div>
                <div class="col">
                  <q-chip v-for="(x, i) in tags" @remove="removeTag(i)" :key="i" square color="red"
                    class="q-ma-none q-mr-md" icon="bookmark" text-color="white" :label="x" removable />
                </div>
              </div>
            </template>
          </q-field>
        </div>
        </div>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right" class="bg-white">
        <q-btn label="取消" flat color="grey-10" style="font-weight:400 !important" @click="closeSaveForm" />
        <q-btn label="立即提交" color="accent q-px-md" style="font-weight:400 !important" :loading="saveLoading"
          @click="saveTeacher" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script>
  import {
    getSchoolDropdown,
    saveTeacher
  } from '../../../api/school/index'
  import {
    UploadSelfFile
  } from '../../../api/common/common'
  //部门
  import {
    getDeptTree
  } from '../../../api/system/dept'
  //岗位
  import {
    queryDeptPostList
  } from '../../../api/system/post'
  import {
    GetClassConfig, //课程基础配置
  } from '../../../api/system/index';
  import extEditor from '../../common/ext-editor'
  import selectTree from '../../common/select-tree'
  export default {
    components: {
      extEditor,
      selectTree
    },
    props: {
      saveObj: {
        type: Object,
        default: null
      }
    },
    data() {
      return {
        persistent: true,
        objOption: {
          TId: 0,
          School_Id: '',
          TeacherName: "",
          TeacherTel: '',
          TeacherHead: '',
          TeacherIcon: '',
          TeacherSay: '',
          TeacherIntro: '',
          IsShow: 1,
          IsRecommend: 0,
          SortNum: 1,
          TeachTag: "",
          Dept_Id: 0, //部门编号
          Post_Id: 0, //岗位编号
          BaseStuNum: 0, //带班基础人数
          BaseHourFee: 0, //基础课时费
        },
        optionTitle: "",
        schoolList: [],
        uploadType: 0,
        saveLoading: false,
        tagText: "",
        tags: [],
        DeptList: [], //部门列表
        PostList: [], //岗位列表
        returnString: [], //默认岗位
        bacisClassConfig: {}, //班级基础配置
      }
    },
    created() {
      this.queryClassConfig();
      this.getSchool()
    },
    mounted() {
      this.initObj()
    },
    methods: {
      //获取课程基础配置
      queryClassConfig() {
        GetClassConfig({}).then(res => {
          if (res.Code == 1) {
            this.bacisClassConfig = res.Data;
          }
        });
      },
      //学校改变
      schoolChagne() {
        this.objOption.Dept_Id = 0;
        this.returnString = [0];
        this.objOption.Post_Id = 0;
        this.PostList = [];
        this.queryDeptTree();
      },
      //部门改变
      deptChange() {
        this.objOption.Post_Id = 0;
        this.PostList = [];
      },
      getChild(deptArray) {
        var tempStr = "";
        if (deptArray && deptArray != '') {
          tempStr = deptArray;
        }
        this.objOption.Dept_Id = tempStr;
        if (this.saveObj) {
          if (this.objOption.Dept_Id != this.saveObj.Dept_Id) {
            this.deptChange();
            this.queryPostList();
          }
        } else {
          this.deptChange();
          this.queryPostList();
        }
      },
      //获取部门结构树
      queryDeptTree() {
        var msg = {
          School_Id: 0
        };
        if (this.objOption.School_Id && this.objOption.School_Id != '') {
          msg.School_Id = this.objOption.School_Id;
        }
        getDeptTree(msg).then(res => {
          if (res.Code == 1) {
            this.DeptList = res.Data;
          }
        })
      },
      //获取岗位列表
      queryPostList() {
        var postMsg = {
          QDeptIds: "",
        };
        if (this.objOption.Dept_Id) {
          postMsg.QDeptIds = this.objOption.Dept_Id;
        }
        queryDeptPostList(postMsg).then(res => {
          if (res.Code == 1) {
            this.PostList = res.Data;
            this.$forceUpdate();
          }
        })
      },
      getType(type) {
        this.uploadType = type;
      },
      //获取编辑器值
      getEditValue(obj) {
        this.objOption.TeacherIntro = obj;
      },
      initObj() {
        if (this.saveObj) {
          this.optionTitle = "修改教师信息"
          this.objOption.TId = this.saveObj.TId;
          this.objOption.School_Id = this.saveObj.School_Id;
          this.objOption.TeacherName = this.saveObj.TeacherName;
          this.objOption.TeacherTel = this.saveObj.TeacherTel;
          this.objOption.TeacherHead = this.saveObj.TeacherHead;
          this.objOption.TeacherIcon = this.saveObj.TeacherIcon;
          this.objOption.TeacherSay = this.saveObj.TeacherSay;
          this.objOption.TeacherIntro = this.saveObj.TeacherIntro;
          this.objOption.IsShow = this.saveObj.IsShow;
          this.objOption.IsRecommend = this.saveObj.IsRecommend;
          this.objOption.SortNum = this.saveObj.SortNum;
          this.objOption.TeachTag = this.saveObj.TeachTag;
          this.objOption.Dept_Id = this.saveObj.Dept_Id;
          this.objOption.Post_Id = this.saveObj.Post_Id;
          this.objOption.BaseStuNum = this.saveObj.BaseStuNum;
          this.objOption.BaseHourFee = this.saveObj.BaseHourFee;
          if (this.objOption.School_Id) {
            this.queryDeptTree();
          }
          if (this.objOption.Dept_Id) {
            this.queryPostList();
            this.returnString.push(this.objOption.Dept_Id.toString());
          }
          if (this.objOption.TeachTag && this.objOption.TeachTag.length > 0) {
            this.tags = JSON.parse(this.objOption.TeachTag)
          }
        } else {
          this.optionTitle = "新增教师";

        }
      },
      removeTag(i) {
        this.tags.splice(i, 1)
      },
      getSchool() {
        getSchoolDropdown({}).then(res => {
          this.schoolList = res.Data;
          this.$forceUpdate();
        })
      },
      onRejected(rejectedEntries) {
        this.$q.notify({
          type: 'negative',
          position: "top",
          message: `文件验证失败，请重新上传`
        })
      },
      uploadFile(files) {
        UploadSelfFile('teacherIcon', files[0], res => {
          if (res.Code == 1) {
            if (this.uploadType == 1) {
              this.objOption.TeacherHead = res.FileUrl;
            } else if (this.uploadType == 2) {
              this.objOption.TeacherIcon = res.FileUrl;
            }
          }
        })
      },
      closeSaveForm() {
        this.$emit('close')
        this.persistent = false
      },
      createTag() {
        if (this.tagText.length > 0) {
          this.tags.push(this.tagText)
          this.tagText = ''
        }
      },
      saveTeacher() {
        this.saveLoading = true;
        if (this.objOption.Dept_Id && this.objOption.Dept_Id == "") {
          this.objOption.Dept_Id = 0;
        }
        this.$refs.School_Id.validate()
        this.$refs.TeacherName.validate()
        this.$refs.TeacherTel.validate()
        if (
          !this.$refs.School_Id.hasError &&
          !this.$refs.TeacherName.hasError &&
          !this.$refs.TeacherTel.hasError
        ) {
          let err_msg = ""
          if (this.objOption.TeacherIcon == '') {
            err_msg = "请上传教师形象照"
          } else if (this.objOption.TeacherHead == '') {
            err_msg = "请上传用户头像"
          }
          if (err_msg == "") {
            this.objOption.TeachTag = JSON.stringify(this.tags)
            saveTeacher(this.objOption).then(res => {
              this.saveLoading = false
              this.$q.notify({
                icon: 'iconfont icon-chenggong',
                color: 'accent',
                timeout: 2000,
                message: '数据保存成功！',
                position: 'top'
              })
              this.$emit("success")
              this.closeSaveForm()
            }).catch(() => {
              this.saveLoading = false
            })
          } else {
            this.$q.notify({
              type: 'negative',
              position: "top",
              message: err_msg
            })
            this.saveLoading = false
          }
        } else {
          this.saveLoading = false
        }
      },
    },
    watch: {
      bacisClassConfig: function (val) {
        if (this.objOption.TId == 0) {
          if (this.bacisClassConfig) {
            if (this.bacisClassConfig.BasicClassNum) {
              this.objOption.BaseStuNum = this.bacisClassConfig.BasicClassNum;
            }
            if (this.bacisClassConfig.BasicHourFee) {
              this.objOption.BaseHourFee = this.bacisClassConfig.BasicHourFee;
            }
          }
        }
      }
    },
  }

</script>

<style>
  .tag-input {
    border: 1px solid #777;
    outline: none;
    width: 140px;
    padding: 5px;
    border-radius: 4px;
  }

</style>
