
<script lang="ts">
// 医生管理
export default {
  name: 'schoolDoctor'
};
</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 { publicTree } from '@/utils/validate';
import { querySchoolDoctorPage, addSchoolDoctor,updateSchoolDoctor,delSchoolDoctor } from "@/api/regionmodule/schoolDoctor";
const schoolName =ref("")
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 cascaderList:any = ref([])
const defaultProps = { label: "name" };
const handleNodeClick = (data: Tree) => {
  schoolName.value = data.name
  checkedtreeid.value = data.id;
  getData();
};
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: "", // 医生名称
  gender:"",
  birth_date:"",
  mobile:"",
  wechat:"",
  email:"",
  certificate:"0",
  license:"", //从业执照
  signature:""
});
const title = ref("");
const dialogVisible = ref(false);
const regionId =ref(""); //行政区域名称
const regionType =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
  querySchoolDoctorPage(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;
      schoolName.value = res.data[0].name
    }
    nextTick(() => {
      treeRef.value?.setCurrentKey(checkedtreeid.value);
    });
    getData();
  }).catch(()=>{
    treeloading.value = false
  });
}
// 选中区域获取医生列表
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
  regionType.value = data.type
  getTreeData()
}
const multipleSelection = ref([]);
//定义医生填写规则
const moderules = reactive<FormRules>({
  code: [{ required: true, message: "请输入医生编码", trigger: "blur" }],
  name: [{ required: true, message: "请输入医生名称", trigger: "blur" }],
  mobile: [{ pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, 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, // 医生名称
          gender: info.value.gender, // 性别
          birthDate: info.value.birth_date, // 出生日期
          mobile: info.value.mobile, // 手机号
          wechat: info.value.wechat, // 微信号
          email: info.value.email, // 微信号
          certificate:info.value.certificate, //资格证书
          license:info.value.license, //从业执照
          signature:info.value.signature //电子签名
        };
        if(info.value.gender == '' || info.value.gender==null){
          data.gender = '0'
        }
        updateSchoolDoctor(data).then((item:any) => {
          if(item.code == '0'){
            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, // 医生名称
          gender: info.value.gender, // 性别
          birthDate: info.value.birth_date, // 出生日期
          mobile: info.value.mobile, // 手机号
          wechat: info.value.wechat, // 微信号
          email: info.value.email, // 微信号
          certificate:info.value.certificate, //资格证书
          license:info.value.license, //从业执照
          signature:info.value.signature //电子签名
        };
        if(info.value.gender == '' || info.value.gender==null){
          data.gender = '0'
        }
        addSchoolDoctor(data).then((item:any) => {
          if(item.code == '0'){
            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: "", // 医生名称
    gender:"",
    birth_date:"",
    mobile:"",
    wechat:"",
    email:"",
    certificate:"",
    signature:"",
    license:"", //从业执照

  });
  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,
    };
    delSchoolDoctor(params).then(() => {
      getData();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    });
  });
}
// 多选删除医生
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(','),
    };
    delSchoolDoctor(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();
    // 拼接
    return year + "-" + month + "-" + day + " ";
  }
}
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;
      };
    };
  }
}
/**
 * 
 * 上传Base64图片方法
 */
function uploadChange(file:any){
  var reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    info.value.license =reader.result
  };
  reader.onerror = function(error) {
    console.log("Error: ", error);
  };
}
function uploadQecodeChange(file:any){
  var reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    info.value.signature =reader.result
  };
  reader.onerror = function(error) {
    console.log("Error: ", error);
  };
}

function delLicense(){
  info.value.license = ""
}
function delsignature(){
  info.value.signature = ""
}
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% ;display: flex;">
        <el-cascader v-if="isCascader" style="width: 90%; margin: auto;" placeholder="请输入行政区域" v-model="regionId" @change="handleChange" :options="cascaderdata" :props="props1" :show-all-levels="false" filterable>
          <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>
            <el-button :disabled="regionId=='' || multipleSelection.length == 0" @click="delClick"><el-icon style="margin-right: 5px;"><Delete /></el-icon> 删除</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="140"></el-table-column>
        <el-table-column prop="name" label="医生姓名" width="100"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            <span v-if="scope.row.gender == '0'">不详</span>
            <span v-if="scope.row.gender == '1'">男</span>
            <span v-if="scope.row.gender == '2'">女</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="所属学校" min-width="140">
          <template #default="scope">
            {{  schoolName }}
          </template>
        </el-table-column>
        <el-table-column prop="certificate" label="资格证书" width="120" align="center">
          <template #default="scope">
            <span v-if="scope.row.certificate == '0'">执业医师</span>
            <span v-if="scope.row.certificate == '1'">执业技师</span>
            <span v-if="scope.row.certificate == '2'">护士</span>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="出生日期" width="120" align="center">
          <template #default="scope">
            {{ dateFormat(scope.row.birth_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" width="120" align="center"></el-table-column>
        <el-table-column prop="license" label="从业执照" width="140">
          <template #default="scope">
            <img :src="scope.row.license" alt="" style="width: 70px;">
            <!-- <el-image
              style="width: 70px; height: 70px"
              :src="scope.row.license"
              :preview-src-list="[scope.row.license]"
              :initial-index="4"
              fit="cover"
              z-index="3000"
            /> -->
          </template>
        </el-table-column>
        <el-table-column prop="signature" label="电子签名" width="140">
          <template #default="scope">
            <img :src="scope.row.signature" alt="" style="width: 70px;">
          </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="所属学校" >
          <el-input v-model="schoolName" style="width: 100%"  :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="医生代码" >
          <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="gender">
          <el-radio-group v-model="info.gender">
            <el-radio label="1" border>男</el-radio>
            <el-radio label="2" border>女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期" prop="birth_date">
          <el-date-picker v-model="info.birth_date" type="date" placeholder="" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile" >
          <el-input v-model="info.mobile" style="width: 100%" placeholder="请输入医生手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="info.email" style="width: 100%" placeholder="请输入医生邮箱"></el-input>
        </el-form-item>
        <el-form-item label="微信号" prop="wechat">
          <el-input v-model="info.wechat" style="width: 100%" placeholder="请输入医生微信号"></el-input>
        </el-form-item>
        <el-form-item label="资格证书" prop="certificate">
          <el-radio-group v-model="info.certificate">
            <el-radio label="0" border>执业医师</el-radio>
            <el-radio label="1" border>执业技师</el-radio>
            <el-radio label="2" border>护士</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传图片" prop="organization_id">
          <div style="display: flex;">
            <el-upload
              class="avatar-uploader"
              accept=".png, .jpg, .jpeg"
              action=""
              :show-file-list="false"
              :auto-upload="false"
              @change="uploadChange" 
            >
            <div style="width: 100px;height: 100px;position: relative;" v-if="info.license">
              <img :src="info.license" class="avatar" />
              <div style="position: absolute;top: 0px;left: 0px;z-index: 1;width: 100px;height: 100px;background: rgba(0,0,0,0.3);color: cornflowerblue;">
                <el-icon style="position: absolute;top: 40px;left: 40px;z-index: 1;font-size: 20px;"
                @click.stop="delLicense"><Delete /></el-icon>
              </div>
            </div>
            <div  v-else>
              <el-icon class="newavatar-uploader-icon"><Plus /></el-icon>
              <div class="newavatar-uploader-text">从业执照</div>
            </div>
              
            </el-upload>
            <el-upload
              style="margin-left: 10px;"
              class="avatar-uploader"
              accept=".png, .jpg, .jpeg"
              action=""
              :show-file-list="false"
              :auto-upload="false"
              @change="uploadQecodeChange"
            >
              <div style="width: 100px;height: 100px;position: relative;" v-if="info.signature">
                <img :src="info.signature" class="avatar" />
                <div style="position: absolute;top: 0px;left: 0px;z-index: 1;width: 100px;height: 100px;background: rgba(0,0,0,0.3);color: cornflowerblue;">
                  <el-icon style="position: absolute;top: 40px;left: 40px;z-index: 1;font-size: 20px;"
                  @click.stop="delsignature"><Delete /></el-icon>
                </div>
              </div>
              <div  v-else>
                <el-icon class="newavatar-uploader-icon"><Plus /></el-icon>
                <div class="newavatar-uploader-text">电子签名</div>
              </div>
            </el-upload>
          </div>
        </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>
