<template>
  <page-layer>
    <template #header>
      <el-select placeholder="医生科室" v-model="queryParam.deptCode" filterable clearable>
        <el-option v-for="item in allMzDepts" :key="item.code" :value="item.code" :label="item.name"></el-option>
      </el-select>
      <el-input v-model="queryParam.doctorName" style="width: 120px" placeholder="医生姓名" clearable></el-input>
      <el-checkbox v-model="queryParam.includeDeleted" style="margin-left: 4px">搜索已删除医生</el-checkbox>
      <el-divider direction="vertical"></el-divider>
      <el-button type="primary" icon="Search" @click="fetchDoctors">查询</el-button>
      <el-button type="primary" icon="Refresh" @click="resetSearch">重置</el-button>
      <el-divider direction="vertical"></el-divider>
      <el-button icon="Top" @click="manageRecommendOrder">服务号推荐排序</el-button>
      <el-button icon="Warning" type="danger" @click="refreshWxDoctorCache">刷新服务号医生数据</el-button>
    </template>
    <template #main>
      <el-table :data="allDoctors" :height="tableHeight" stripe highlight-current-row>
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="code" label="编号" width="70"></el-table-column>
        <el-table-column prop="name" label="姓名" width="80"></el-table-column>
        <el-table-column prop="sexName" label="性别" width="60"></el-table-column>
        <el-table-column prop="deptName" label="科室" width="160"></el-table-column>
        <el-table-column prop="titleName" label="级别" width="160"></el-table-column>
        <el-table-column label="服务号首页推荐" width="160">
          <template v-slot="scope">
            <el-select v-model="scope.row.wxHomepageFlag" style="width: 100px" @change="(wxHomepageFlag) => handleSelectRec(scope.row.code, wxHomepageFlag)">
              <el-option v-for="item in yesOrNo" :key="item.code" :value="item.code" :label="item.name"> </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button @click="viewDoctor(scope.row)" text icon="View" type="success">查看</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button @click="editDoctor(scope.row)" text icon="Edit" type="primary">编辑</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button v-if="queryParam.includeDeleted" @click="undoDelete(scope.row)" text icon="Check" type="info">恢复</el-button>
            <el-button v-else @click="beforeDelete(scope.row)" text icon="Delete" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParam.currentPage"
          :page-sizes="[15, 30, 45]"
          :page-size="queryParam.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          style="margin-top: 5px"
      ></el-pagination>
      <el-drawer title="" v-model="drawer" size="40%" :with-header="false">
        <div v-if="edit" :style="editStyle" class="edit-doctor-info">
          <div>基本信息</div>
          <div>
            医生头像：请上传一寸照
            <el-upload
                class="upload-demo"
                ref="upload"
                :action="apiUrl + '/manageDoctorInfo/uploadPortrait'"
                :headers="header"
                :file-list="fileList"
                :limit="1"
                :data="{ code: doctor.code }"
                :on-exceed="fileSizeOutLimit"
                :before-upload="beforeAvatarUpload"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :auto-upload="false"
            >
              <template #trigger>
                <el-button type="primary" icon="Picture">选取文件</el-button>
              </template>
              <el-button style="margin-left: 10px" type="success" icon="Upload" @click="submitUpload">上传到服务器</el-button>
              <template #tip>
                <div class="el-upload__tip">只能上传 jpg/png 文件，且不超过 500kb</div>
              </template>
            </el-upload>
          </div>
          <div style="margin-top: 130px">
            <span class="require">*</span>
            医生编号：<el-input class="w200" v-model="doctor.code" disabled></el-input>
          </div>
          <div>
            <span class="require">*</span>
            医生姓名：<el-input class="w200" v-model="doctor.name"></el-input>
          </div>
          <div>
            <span class="require">*</span>
            医生性别：
            <el-select v-model="doctor.sex" class="w200">
              <el-option v-for="item in sexCodes" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </div>
          <div>
            <span class="require">*</span>
            所属科室：
            <el-select v-model="doctor.deptCode" class="w200" clearable filterable>
              <el-option v-for="item in allMzDepts" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </div>
          <div>
            <span class="require">*</span>
            医生职称：
            <el-select v-model="doctor.titleCode" class="w200" clearable filterable>
              <el-option v-for="item in allTitles" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </div>
          <div style="height: max-content; margin-top: 15px">
            <span class="require">*</span>
            医生擅长：
            <el-input class="w350" style="font-size: 13px" type="textarea" rows="3" maxlength="50" show-word-limit v-model="doctor.specialty"></el-input>
          </div>
          <div style="height: max-content; margin-top: 15px">
            <span>&nbsp;&nbsp;</span>
            医生介绍：
            <el-input class="w350" style="font-size: 13px" type="textarea" rows="7" maxlength="150" show-word-limit v-model="doctor.introduction"></el-input>
          </div>
          <div style="margin-top: 15px">
            <span>&nbsp;&nbsp;</span>
            <el-button type="primary" @click="saveDoctor" icon="Money">保存</el-button>
            <el-button plain @click="drawer = false" icon="Close">取消</el-button>
          </div>
        </div>
        <div v-else>
          <div style="height: 80px; width: 100%; background: #36af6b"></div>
          <div>
            <div class="inline pl15">
              <el-avatar src="https://empty" shape="circle" style="width: 88px; height: 120px; margin-top: -60px" @error="avatarError">
                <img :src="'data:image/png;base64,' + doctor.portrait" />
              </el-avatar>
            </div>
            <div class="inline child-pl15" style="width: calc(100% - 150px)">
              <div style="margin-top: -30px; font-size: 16px; font-weight: bold; color: white">
                {{ doctor.name }}
              </div>
              <div class="doctor-info">
                <div>医生编号：{{ doctor.code }}</div>
                <div>医生性别：{{ doctor.sexName }}</div>
                <div>所属科室：{{ doctor.deptName }}</div>
                <div>医生职称：{{ doctor.titleName }}</div>
                <div class="info-title">医生擅长：</div>
                <div style="height: max-content">
                  {{ doctor.specialty }}
                </div>
                <div class="info-title">医生介绍：</div>
                <div style="height: max-content">
                  {{ doctor.introduction }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-drawer>
      <el-dialog title="服务号推荐排序" width="60%" v-model="manageOrderDialog">
        <el-table :data="recommendDoctors" :height="tableHeight - 200" stripe highlight-current-row>
          <el-table-column prop="wxHomepageOrder" label="当前排序"></el-table-column>
          <el-table-column prop="code" label="编号"></el-table-column>
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column prop="sexName" label="性别"></el-table-column>
          <el-table-column prop="deptName" label="科室"></el-table-column>
          <el-table-column prop="titleName" label="级别"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button type="primary" plain icon="Edit" @click="modifyOrder(scope.row)">修改排序</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </template>
  </page-layer>
</template>

<script setup name="DoctorInfoManagement">
import { onMounted, reactive, ref } from 'vue'
import {
  updateDoctorStatus,
  getAllDoctors,
  getAllMzDept,
  getAllRecommendDoctors,
  getAllTitles,
  getDoctorInfo,
  saveDoctorInfo,
  updateDoctorWxHomepageFlag,
  updateWxHomepageOrder,
} from '@/api/manage-doctor-info'
import store from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import PageLayer from "@/layout/PageLayer";

const apiUrl = import.meta.env.VITE_BASE_URL
const windowSize = store.state.app.windowSize
const tableHeight = windowSize.h - 50
const allTitles = ref([])
const allMzDepts = ref([])
const allDoctors = ref([])
const totalSize = ref(0)
const yesOrNo = [
  { code: 1, name: '推荐' },
  { code: 0, name: '不推荐' },
]
const sexCodes = [
  { code: 1, name: '男' },
  { code: 2, name: '女' },
  { code: 9, name: '未知' },
]

const queryParam = reactive({
  deptCode: '',
  doctorName: '',
  includeDeleted: false,
  currentPage: 1,
  pageSize: 15,
})

const handleSizeChange = (val) => {
  queryParam.pageSize = val
  fetchDoctors()
}
const handleCurrentChange = (val) => {
  queryParam.currentPage = val
  fetchDoctors()
}

const resetSearch = () => {
  queryParam.deptCode = queryParam.doctorName = ''
  fetchDoctors()
}

const handleSelectRec = (code, flag) => {
  updateDoctorWxHomepageFlag(code, flag).then(() => {
    const message = flag === 1 ? '已在微信服务号首页推荐此医生。' : '已取消此医生在微信服务号首页的推荐。'
    const type = flag === 1 ? 'success' : 'warning'
    ElMessage({
      message,
      type,
      duration: 3000,
      showClose: true,
    })
  })
}

const viewDoctor = (val) => {
  getDoctorInfo(val.code).then((res) => {
    doctor.value = res
    edit.value = false
    drawer.value = true
  })
}
const editDoctor = (val) => {
  getDoctorInfo(val.code).then((res) => {
    doctor.value = res
    edit.value = true
    drawer.value = true
  })
}

const doctor = ref({})
const editStyle = {
  padding: '0 15px 15px 50px',
  height: window.innerHeight + 'px',
  overflowY: 'scroll',
}
const edit = ref(true)
const drawer = ref(false)

const fileList = ref([])

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt1M = file.size / 1024 / 1024 < 1
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 jpg 或 png 格式!')
  }
  if (!isLt1M) {
    ElMessage.error('上传头像图片大小不能超过 1MB!')
  }
  return isJPG && isLt1M
}

const upload = ref(null)
const header = {
  token: store.state.user.token,
}
const submitUpload = () => {
  upload.value.submit()
}
const fileSizeOutLimit = () => {
  ElMessage.error('已经选取头像，如须更换请先移除已选取的头像！')
}
const uploadSuccess = () => {
  ElMessage.success('上传成功！')
}
const uploadError = () => {
  ElMessage.error('上传失败！')
}

const saveDoctor = () => {
  saveDoctorInfo(doctor.value).then(() => {
    ElMessage.success('保存成功')
  })
}

const avatarError = () => {
  return true
}

const manageOrderDialog = ref(false)
const recommendDoctors = ref([])
const manageRecommendOrder = () => {
  getAllRecommendDoctors().then((res) => {
    recommendDoctors.value = res
    manageOrderDialog.value = true
  })
}
const modifyOrder = (val) => {
  ElMessageBox.prompt('请输入新序号', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[1-9]\d*$/,
    inputErrorMessage: '请输入大于0的整数',
  })
    .then(({ value }) => {
      updateWxHomepageOrder(val.code, value).then(() => {
        val.wxHomepageOrder = value
        ElMessage({
          message: '保存排序成功',
          type: 'success',
          duration: 2000,
          showClose: true,
        })
      })
    })
    .catch(() => {})
}

const refreshWxDoctorCache = () => {
  axios('http://192.168.200.3/wxserver/homepage/refreshHomePageDoctors').then((res) => {
    if (res.data.code === 200) {
      ElMessage({
        message: '强制刷新成功',
        type: 'success',
        duration: 2000,
        showClose: true,
      })
    } else {
      ElMessage.error(res.data.message)
    }
  })
}

const undoDelete = (row) => {
  updateDoctorStatus(row.code, 1).then((res) => {
    ElMessage({
      message: res,
      type: 'success',
      duration: 2000,
      showClose: true,
    })
    fetchDoctors()
  })
}

const beforeDelete = (row) => {
  ElMessageBox.confirm('删除后将无法在服务号首页推荐，是否确认删除？', '提示', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消',
  })
    .then(() => {
      updateDoctorStatus(row.code, 0).then((res) => {
        ElMessage({
          message: res,
          type: 'success',
          duration: 2000,
          showClose: true,
        })
        fetchDoctors()
      })
    })
    .catch(() => {})
}

const fetchDoctors = () => {
  getAllDoctors(queryParam).then((res) => {
    totalSize.value = res.totalSize
    allDoctors.value = res.list
  })
}

onMounted(() => {
  getAllTitles().then((res) => {
    allTitles.value = res
  })
  getAllMzDept().then((res) => {
    allMzDepts.value = res
    fetchDoctors()
  })
})
</script>

<style scoped>
.inline {
  display: inline-block;
  vertical-align: top;
}
.pl15 {
  padding-left: 50px;
}
.child-pl15 > div {
  padding: 0 50px 0 15px;
}
.doctor-info,
.edit-doctor-info {
  font-size: 13px;
  color: gray;
  margin-top: 15px;
}
.doctor-info > div {
  height: 30px;
  line-height: 30px;
}
.edit-doctor-info > div {
  height: 35px;
  line-height: 35px;
}
.info-title {
  margin-top: 15px;
  color: #333333;
}
.require {
  color: #db4242;
}
.w200 {
  width: 200px;
}
.w350 {
  width: 75%;
}
</style>
