<template>
  <el-drawer :close-on-click-modal="false" :model-value="visible" :title="data._id ? '编辑信息' : '新增信息'" size="60%"
    style="--el-drawer-padding-primary: 0" @close="close">
    <my-layout>
      <layout-main>
        <el-form :label-width="120" label-suffix="：" class="p-15px pr-30px">
          <div class="mb-2.5 font-bold">基础信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item class="is-required" label="姓名" prop="doctorName">
                <el-input :model-value="form.doctorName" placeholder="请输入" maxlength="50"
                  @update:model-value="change($event, 'doctorName')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-radio-group :model-value="form.sex" @update:model-value="change($event, 'sex')">
                  <el-radio label="男" value="男">男</el-radio>
                  <el-radio label="女" value="女">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="mobile">
                <el-input :model-value="form.mobile" placeholder="请输入" maxlength="20"
                  @update:model-value="change($event, 'mobile')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属科室/部门" prop="dept">
                <!-- <el-select clearable :model-value="form.deptCode" placeholder="请选择" class="w-full"
                  @update:model-value="change($event, 'deptCode')">
                  <el-option v-for="item in deptList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select> -->
                <el-cascader class="w-full" :show-all-levels="false" :model-value="form.deptCode" :options="deptList"
                  :props="{ checkStrictly: true }" clearable @update:model-value="change($event, 'deptCode')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="岗位" prop="position">
                <el-select clearable :model-value="form.job" placeholder="请选择" class="w-full"
                  @update:model-value="change($event, 'job')">
                  <el-option v-for="item in jobList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="is-required" label="院内工号" prop="doctorNo">
                <el-input :model-value="form.doctorNo" placeholder="请输入" maxlength="50" :disabled="!!form._id"
                  @update:model-value="change($event, 'doctorNo')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职称" prop="title">
                <el-select clearable :model-value="form.title" placeholder="请选择" class="w-full"
                  @update:model-value="change($event, 'title')">
                  <el-option v-for="item in titleList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="头像" prop="avatar">
                <el-upload class="avatar-uploader" action="#" :show-file-list="false" :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
                  <el-button v-else>上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col> -->
          </el-row>
          <div class="mb-2.5 font-bold">介绍信息</div>
          <el-form-item label="个人介绍" prop="intro">
            <el-input :model-value="form.intro" type="textarea" :autosize="{ minRows: 5, maxRows: 10 }" maxlength="300"
              show-word-limit placeholder="请输入" @update:model-value="change($event, 'intro')" />
          </el-form-item>
          <el-form-item label="擅长领域" prop="goodAt">
            <el-input :model-value="form.goodAt" type="textarea" :autosize="{ minRows: 5, maxRows: 10 }" maxlength="300"
              show-word-limit placeholder="请输入" @update:model-value="change($event, 'goodAt')" />
          </el-form-item>
          <el-form-item label="门诊时间" prop="clinicTime">
            <el-input :model-value="form.clinicTime" placeholder="请输入"
              @update:model-value="change($event, 'clinicTime')" />
          </el-form-item>
          <el-row v-if="form.job === 'doctor' || form.job === 'pharmacist'">
            <el-col :span="24">
              <div class="mb-2.5 font-bold">业务配置</div>
            </el-col>
            <el-col v-if="form.job === 'doctor'" :span="12">
              <el-form-item label="视频问诊功能" prop="enableVideoConsult">
                <el-switch :model-value="!!form.enableVideoConsult"
                  @update:model-value="change($event, 'enableVideoConsult')" />
                <span class="ml-10px text-12px text-gray-500">开启后可在在线问诊工具栏发起视频问诊</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="140" :class="form.job === 'doctor' ? 'is-required' : ''"
                :label="form.job === 'doctor' ? '可开处方类型' : '可审处方类型'" prop="openWestPres">
                <el-checkbox :model-value="form.openWestPres"
                  @update:model-value="change($event, 'openWestPres')">西医处方</el-checkbox>
                <el-checkbox :model-value="form.openChinesePres"
                  @update:model-value="change($event, 'openChinesePres')">中医处方</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </layout-main>
      <layout-item>
        <div class="text-center py-10px">
          <el-button class="w-100px" @click="close()">取消</el-button>
          <el-button class="w-100px" :loading="loading" type="primary" @click="save()">保存</el-button>
        </div>
      </layout-item>
    </my-layout>
  </el-drawer>
</template>
<script setup>
import { computed, ref, watch } from 'vue';
import { ElMessage } from "element-plus";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import { verifyString, verifyNumber, verifyListItem } from '@/utils/index'
import validate from "@/utils/validate";
import { addHlwPerson, updateHlwPerson } from "@/api/hlw";
import { getDeptList } from "@/api/dept-manage";
import { getCateTreeData } from '@/utils'
import { jobList } from '@/baseData/hlw-job.js'

const emits = defineEmits(['close', 'change'])
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => ({})
  }
})
// const [namePass, name] = verifyString(form.value.name, '名称', 1, 50);

const rules = computed(() => ({
  doctorName: val => verifyString(val, '姓名', 1, 30),
  sex: val => verifyListItem(val, ['男', '女'], false, '性别'),
  mobile: val => {
    if (typeof val === 'string' && val.trim() !== '') {
      const isMobile = validate.isMobile(val);
      return [isMobile, isMobile ? val.trim() : '请输入正确的手机号'];
    }
    return [true, '']
  },
  deptCode: val => {
    const deptCode = typeof val === 'string' ? val.trim() : (Array.isArray(val) ? val[0] || '' : '');
    return verifyListItem(deptCode, depts.value.map(item => item.value), false, '科室')
  },
  job: val => verifyListItem(val, jobList.map(item => item.value), false, '岗位'),
  doctorNo: val => {
    if (/\W/.test(val)) {
      return [false, '院内工号只能包含字母、数字和下划线'];
    }
    return verifyString(val, '院内工号', 1, 50)
  },
  title: val => verifyListItem(val, titleList.value.map(item => item.value), false, '职称'),
  intro: val => verifyString(val, '个人介绍', 0, 300),
  goodAt: val => verifyString(val, '擅长领域', 0, 300),
  clinicTime: val => verifyString(val, '门诊时间', 0, 100),
  enableVideoConsult: val => [true, !!val],
  openWestPres: val => [true, !!val],
  openChinesePres: val => [true, !!val],
}))

const editForm = ref({})
const loading = ref(false)
const form = computed(() => {
  return { ...props.data, ...editForm.value }
})

// 示例数据，实际应从接口获取
const depts = ref([])
const deptList = computed(() => getCateTreeData(depts.value))

const titleList = ref([
  { label: '主任医师', value: '主任医师' },
  { label: '主治医师', value: '主治医师' },
  { label: '执业医师', value: '执业医师' },
  { label: '主治中医师', value: '主治中医师' },
  { label: '执业中医师', value: '执业中医师' },
  { label: '副主任医师', value: '副主任医师' },
  { label: '主任中医师', value: '主任中医师' },
  { label: '副主任中医师', value: '副主任中医师' },
  { label: '主管药师', value: '主管药师' },
  { label: '药师', value: '药师' },
  { label: '中药师', value: '中药师' }
]);

function change(value, prop) {
  editForm.value[prop] = value;
  // 岗位选择医生或者药师时，默认开启西药处方 ，关闭中药处方
  if (prop === 'job' && ['pharmacist', 'doctor'].includes(value)) {
    editForm.value.openWestPres = true;
    editForm.value.openChinesePres = false;
  }

}

function changeDept(value) {
  const dept = deptList.value.find(item => item.value === value);
  editForm.value.deptCode = dept ? dept.value : '';
  editForm.value.deptName = dept ? dept.label : '';
}

function close() {
  if (loading.value) return;
  emits('close', false)
}

async function save() {
  if (loading.value) return;
  const params = {};
  const keys = Object.keys(rules.value);
  const editKeys = Object.keys(editForm.value);
  const validKeys = props.data._id ? keys.filter(key => editKeys.includes(key)) : [...keys];
  for (const key of validKeys) {
    const [pass, message] = rules.value[key](editForm.value[key]);
    if (pass) {
      params[key] = message;
    } else {
      ElMessage.error(message);
      return;
    }
  }
  if (form.value.job === 'doctor' && !form.value.openWestPres && !form.value.openChinesePres) {
    ElMessage.error('请选择是否开启西药处方或中药处方');
    return;
  }
  if ('deptCode' in params) {
    const dept = depts.value.find(item => item.value === params.deptCode);
    params.deptName = dept ? dept.label : '';
  }
  const api = props.data._id ? updateHlwPerson : addHlwPerson;
  loading.value = true;
  const { success, message } = await api({ ...params, _id: props.data._id });
  loading.value = false;
  if (success) {
    ElMessage.success(message);
    emits('change', true);
    close();
  } else {
    ElMessage.error(message);
  }
}

async function getCateList() {
  const { success, data, message } = await getDeptList({ corpId: sessionStorage.getItem('corpId') });
  depts.value = data && Array.isArray(data.list) ? data.list.map(i => ({
    ...i,
    label: i.deptName,
    value: i.deptId
  })) : [];
  // getCateTreeData
  // if (success) {
  //   cateList.value = data && Array.isArray(data.list) ? format(data.list) : [];
  //   const cate = cateList.value.find(i => i._id === id);
  //   if (cate) changeCurrent(cate);
  // } else {
  //   ElMessage.error(message);
  //   cateList.value = []
  // }
  // if (loading) loading.value = false;
}


watch(() => props.visible, (val) => {
  if (val) {
    editForm.value = {}
    getCateList()
  }
})

</script>
<style scoped>
.avatar-uploader .avatar {
  width: 60px;
  height: 60px;
  display: block;
  border-radius: 50%;
  object-fit: cover;
  margin-top: 4px;
}
</style>
