<template>
  <Mask :is-show="isShow" width="800" :height="height" title="挂号" @close="close"
        :show-footer="true">
    <template #default>
      <div style="padding:0 24px 24px;height: 100%;display: flex;flex-direction: column">
        <el-scrollbar>
          <el-form
              v-loading="loading"
              :model="edit_data"
              label-width="auto"
              :rules="rules"
              ref="form"
              style="flex: 1;width: 100%"
          >
            <el-descriptions
                border
                direction="vertical"
                :column="4"
                style="margin-top: 20px"
            >
              <el-descriptions-item label="姓名" width="200">
                <el-form-item prop="name" style="margin-bottom: 2px">
                  <el-input v-model="edit_data.name" placeholder="请输入姓名" clearable
                            :disabled="edit_data.status==1||edit_data.status==3||edit_data.status==0"></el-input>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="性别" width="200">
                <el-form-item prop="gender">
                  <el-radio-group v-model="edit_data.gender"
                                  :disabled="edit_data.status==1||edit_data.status==3||edit_data.status==0">
                    <el-radio :value="1">男</el-radio>
                    <el-radio :value="2">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="年龄" width="200">
                <el-form-item prop="age">
                  <el-input v-model.number="edit_data.age" placeholder="请输入年龄"
                            :disabled="edit_data.status==1||edit_data.status==3||edit_data.status==0"></el-input>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="手机号" width="200">
                <el-form-item prop="phone">
                  <el-input v-model="edit_data.phone" placeholder="手机号"
                            :disabled="edit_data.status==3||edit_data.status==0"></el-input>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="医生">
                <el-form-item prop="organizationDoctorId">
                  <el-select
                      v-model="edit_data.organizationDoctorId"
                      placeholder="请选择医生"
                      @change="getSectionList"
                      :disabled="edit_data.status==3||edit_data.status==0"
                  >
                    <el-option
                        v-for="item in doctorList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="科室">
                <el-form-item>
                  <el-select
                      v-model="edit_data.organizationSectionId"
                      placeholder="选择科室"
                      :disabled="edit_data.status==3||edit_data.status==0"
                  >
                    <el-option
                        v-for="item in sectionList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="证件类型">
                <el-form-item prop="certType">
                  <el-select v-model="edit_data.certType" placeholder="证件类型"
                             :disabled="edit_data.status==1||edit_data.status==3||edit_data.status==0">
                    <el-option
                        v-for="item in certTypeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="证件码">
                <el-form-item prop="certNo">
                  <el-input v-model="edit_data.certNo" placeholder="请输入证件码"
                            :disabled="edit_data.status==1||edit_data.status==3||edit_data.status==0"></el-input>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="初/复诊">
                <el-form-item prop="visitType">
                  <el-select v-model="edit_data.visitType" placeholder="就诊类型" :disabled="edit_data.status==0">
                    <el-option label="初诊" :value="0"></el-option>
                    <el-option label="复诊" :value="1"></el-option>
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="费用类型">
                <el-form-item prop="type">
                  <el-select v-model="edit_data.type" :disabled="edit_data.status==0||isShowCard">
                    <el-option label="自费" :value="1"></el-option>
                    <el-option label="医保" :value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item
                  :span="2"
                  label="时间">


                <div style=" display: flex;">
                  <div style="flex: 1;min-width: 0" v-if="!isBtnShow&&dateName!='预约'">现在</div>
                  <div v-else style="flex:1;min-width:0;display: flex;align-items: center">
                    <el-date-picker
                        v-model="edit_data.date"
                        type="date"
                        format="YYYY/MM/DD"
                        value-format="YYYY-MM-DD"
                        placeholder="选择日期"
                        style="width: 50%"
                        :disabledDate="disabledDate"
                    />
                    <el-time-select
                        v-model="edit_data.time"
                        start="08:00"
                        step="00:15"
                        end="22:00"
                        :min-time="getCurrentTime(edit_data.date)"
                        placeholder="选择时间"
                        style="width: 50%"
                    />
                  </div>
                  <span v-if="dateName!='预约'"
                        :class="{disabled:edit_data.status==1||edit_data.status==3||edit_data.status==0}"
                        class="small-btn" @click="changeBtn">{{
                      isBtnShow ? '挂号' : '预约'
                    }}</span>
                </div>
              </el-descriptions-item>
              <el-descriptions-item
                  :span="4"
                  label="备注">
                <el-form-item>
                  <el-input v-model="edit_data.memo" placeholder="备注" :disabled="edit_data.status==0"></el-input>
                </el-form-item>
              </el-descriptions-item>
            </el-descriptions>
          </el-form>
          <h5 v-if="!isShowCard" style="margin:24px 0;font-size: 16px">险种列表</h5>
          <el-table
              :data="tableData"
              style="width: 100%;flex: 1"
              v-if="!isShowCard"
              highlight-current-row
              ref="multipleTable"
              @current-change="handleCurrentChange"
          >
            <el-table-column label="险种类型" prop="insutype">
              <template #default="scope">
                {{ getKey(insutypes, scope.row.insutype) }}
              </template>
            </el-table-column>
            <el-table-column label="待遇状态">
            </el-table-column>
            <el-table-column label="参保日期" prop="psn_insu_date"></el-table-column>
            <el-table-column label="剩余余额" prop="balc">
              <template #default="scope">
                ￥{{ scope.row.balc || 0 }}
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </div>
    </template>
    <template #footer>
      <div class="bottom">
        <el-dropdown v-if="isShowCard" placement="top-start" @show="showCardBtn" @hide="hide"
                     :disabled="edit_data.status==0">
          <div class="left" style="outline: none;">
            <span class="btnCard" type="primary">
              <img class="image" src="/static/images/registration/card.png" alt=""
                   srcset="">{{ edit_data.status == 0 ? '不能读卡' : '进行读卡' }}
              <img class="image1" :src="'/static/images/registration/'+(showBtn?2:1)+'.png'" alt="" srcset="">
            </span>
          </div>
          <template #dropdown>
            <CardDefault ref="cardDefaultRef" v-model="socialCard" @socialCardUpdate="socialCardUpdate"
                         @close="deleteCard" @changeLoading="changeLoading"/>
          </template>
        </el-dropdown>
        <div class="closeBtn" v-else @click="deleteCard" style="outline: none;">
          <img class="image" src="/static/images/registration/card.png" alt="" srcset="">
          退出医保
        </div>
        <div class="bottom-right">
          <span class="close-btn" @click="close">取消</span>
          <span class="danger-btn" v-if="edit_data.status==1" @click="registrationCancel">退号</span>
          <span class="small-btn" @click="save">保存</span>
        </div>
      </div>
    </template>
  </Mask>
  <Quick ref="quickRef" @close="close"></Quick>
</template>
<script setup lang="ts">
import {nextTick, onMounted, ref, watch} from 'vue'
import {post} from '@/utils/request.ts'
import CardDefault from '@/components/registration/CardDefault.vue'
import {ElMessage, ElMessageBox} from "element-plus";
import Mask from "@/components/common/Mask.vue";
import psnCertTypes from "@/assets/config/directory/psnCertTypes.json"
import {getKey} from "@/utils/discrotyUtil.ts";
import insutypes from "@/assets/config/directory/insutypes.json"
import {apiConfig} from "@/assets/config/apiConfig.ts";
import Quick from "@/components/charge/RecordsLog/Quick.vue";
import {getCurrentTime, getToday} from "@/utils/dateUtils.ts";

const height = ref(570)
const certTypeList = ref<any>([])
const edit_data = ref<any>({
  timeList: []
})
const rules = ref<any>({
  name: [
    {required: true, message: '请输入名称', trigger: 'blur'},
  ],
  age: [
    {required: true, message: '请输入年龄', trigger: 'blur'},
    {type: 'number', message: '年龄必须为数字值', trigger: 'blur'},
  ],
  gender: [
    {required: true, message: '请选择性别', trigger: 'change'},
  ],
  spec: [
    {required: true, message: '请输入规格', trigger: 'blur'},
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
  ],
  organizationDoctorId: [
    {required: true, message: '请选择医生', trigger: 'change'},
  ],
  certType: [
    {required: true, message: '请选择证件类型', trigger: 'change'},
  ],
  certNo: [
    {required: true, message: '请输入证件码', trigger: 'blur'},
  ],
  visitType: [
    {required: true, message: '请选择就诊类型', trigger: 'blur'},
  ],
  type: [
    {required: true, message: '请选择费用类型', trigger: 'change'},
  ],
  date: [
    {required: true, message: '请选择就诊时间', trigger: 'change'},
  ]
})
const isShow = ref(false)
const emit = defineEmits(['close'])
const close = () => {
  isShow.value = false
  isBtnShow.value = true
  time.value = ''
  edit_data.value = {
    insutype: '',
  }
  isShowCard.value = true
  nextTick(() => {
    cardDefaultRef.value?.close()
    height.value = 570
  })
  emit('close')
}
const form = ref()
const quickRef = ref()
const time = ref()
const disabledDate = (date: Date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 将时间设置为今天的 00:00:00
  return date < today; // 禁用今天之前的日期
};
const timeList = ref<any>([])
const dateName = defineModel()
const save = () => {
  form.value.validate((v: any) => {
    if (v) {
      let combinedDateTime = ''
      if (edit_data.value.date == undefined || edit_data.value.time == undefined) {
        combinedDateTime = ''
      } else {
        combinedDateTime = `${edit_data.value.date} ${edit_data.value.time}`
      }
      let data = {
        ...edit_data.value,
        appointmentTime: combinedDateTime || '',
        psnNo: socialCard.value?.data?.baseinfo.psn_no,
        insutype: edit_data.value.insutype || socialCard.value?.data?.insuinfo[0].insutype,
        insuBalance: socialCard.value?.data?.insuinfo[0].balc,

      }
      if (edit_data.value.id) {
        post(apiConfig.RegistrationEdit, {
          data: data, mdtrtCertNo: socialCard.value?.mdtrtCertNo,
          mdtrtCertType: socialCard.value?.mdtrtCertType
        }).then(() => {
          ElMessage.success('修改成功')
          close()
        })
      } else {
        post(apiConfig.RegistrationAdd, {
          data: data,
          mdtrtCertNo: socialCard.value?.mdtrtCertNo,
          mdtrtCertType: socialCard.value?.mdtrtCertType
        }).then(() => {
          ElMessage.success('挂号成功')
          if (quickShow.value) {
            nextTick(() => {
              quickRef.value?.init()
            })
            return
          } else {
            close()
          }
        })
      }
    }
  })

}
//退出挂号
const registrationCancel = () => {
  post(apiConfig.RegistrationChangeStatus, {id: edit_data.value.id, status: 0}).then(() => {
    ElMessage.success('退号成功')
    close()
  })
}
const doctorList = ref<any>([])
const getDoctorList = () => {
  let query = {
    role: 1
  }
  post('organization/member/search', {query: query}).then((res: any) => {
    doctorList.value = res
  })
}

const socialCard: any = ref({
  data: null,
  payInfo: {},
  lastUse: null
})
const quickShow = ref<any>(false)
const init = (doctorId: any = "", id: any = null, show: any = false) => {
  certTypeList.value = Object.entries(psnCertTypes)
      .map(([id, name]) => ({id, name}))
      .sort((a, b) => Number(a.id) - Number(b.id))
  isShow.value = true
  quickShow.value = show
  edit_data.value.organizationDoctorId = doctorId || ""
  edit_data.value.type = 1
  isBtnShow.value = dateName.value == '现在';
  if (id) {
    post('registration/getById', {id: id}).then((res: any) => {
      edit_data.value = res
      time.value = edit_data.value.timeList[edit_data.value.timeList.length - 1]
    })
  }
  getSectionList()
  getDoctorList()
}
const isShowCard = ref<any>(true)
const tableData = ref<any>([])
const multipleTable = ref<any>()
const socialCardUpdate = (e: any) => {
  isShowCard.value = false
  if (!e) return;
  isShowCard.value = false
  edit_data.value.gender = Number(e.data.baseinfo.gend)
  edit_data.value.name = e.data.baseinfo.psn_name
  edit_data.value.certType = e.data.baseinfo.psn_cert_type
  edit_data.value.certNo = e.data.baseinfo.certno
  edit_data.value.age = Math.floor(e.data.baseinfo.age)
  tableData.value = e.data.insuinfo
  edit_data.value.type = 2
  if (!edit_data.value.certNo) return;
  post('vip/vip/list', {
    keyword: edit_data.value.certNo,
    page: 1,
    pageSize: 50
  }).then((res: any) => {
    edit_data.value.phone = res.list[0].phone
  })

  nextTick(() => {
    if (tableData.value.length > 0) {
      height.value = 820
      multipleTable.value?.setCurrentRow(tableData.value[0])
    } else {
      height.value = 570
    }
  })
  loading.value = false
}
const cardDefaultRef = ref<any>("")
const deleteCard = () => {
  ElMessageBox.confirm("退出识别", "提示", {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    callback: (action: any) => {
      if (action == "confirm") {
        isShowCard.value = true
        edit_data.value = {}
        tableData.value = []
        nextTick(() => {
          cardDefaultRef.value?.close()
          height.value = 570
        })
      }
    },
  });
}
const showBtn = ref(false)
const showCardBtn = () => {
  showBtn.value = true
}
const hide = () => {
  showBtn.value = false
}
const sectionList = ref<any>([])
const getSectionList = () => {
  if (!edit_data.value.organizationDoctorId) return
  post(apiConfig.OrganizationSectionListByMemberId, {memberId: edit_data.value.organizationDoctorId}).then((res: any) => {
    sectionList.value = res
    if (res.length > 0) {
      edit_data.value.organizationSectionId = res[0].id
    }
  })
}
const loading = ref(false)
const changeLoading = (e: any) => {
  loading.value = e
}
const isBtnShow = ref(true)
const changeBtn = () => {
  if (edit_data.value.status == 1 || edit_data.value.status == 3 || edit_data.value.status == 0) return
  isBtnShow.value = !isBtnShow.value
  if (isBtnShow.value) {
    time.value = ''
    timeList.value = []
  }
}
const handleCurrentChange = (val: any) => {
  edit_data.value.insutype = val.insutype
}
defineExpose({init})
</script>
<style scoped lang="scss">
.title {
  color: #000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
}

.bottom {
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
}

.btnCard {
  width: 150px;
  height: 36px;
  background: #FFFFFF;
  border-radius: 8px;
  border: 1px solid #4D6DE4;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 400;
  font-size: 15px;
  color: #4D6DE4;
  font-style: normal;

  .image {
    width: 20px;
    height: 17px;
    margin-right: 6px;
  }

  .image1 {
    width: 12px;
    height: 6px;
    margin-left: 16px;
  }

  &:hover {
    cursor: pointer;
    border: 1px solid #4D6DE4;
  }
}

.closeBtn {
  width: 150px;
  height: 36px;
  background: #FFFFFF;
  border-radius: 8px;
  border: 1px solid #4D6DE4;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 400;
  font-size: 15px;
  color: #4D6DE4;
  font-style: normal;

  .image {
    width: 20px;
    height: 17px;
    margin-right: 6px;
  }

  &:hover {
    cursor: pointer;
    border: 1px solid #4D6DE4;
  }
}

:deep(.el-dropdown) {
  &:hover {
    border: none;
  }
}

:deep(.el-form-item) {
  margin-bottom: 2px !important;
}

.disabled {
  cursor: not-allowed;
  background: rgba(#4D6DE4,.5);
}
</style>