<template>
  <Mask :is-show="isShow" width="800" :height="height" title="挂号" @close="close"
        :show-footer="true">
    <template #default>
      <div style="padding:0 24px">
        <el-form
            v-loading="loading"
            :model="edit_data"
            label-width="auto"
            :rules="rules"
            ref="form"
        >
          <el-descriptions
              border
              direction="vertical"
              label-width="100"
              :column="4"
              style="margin-top: 20px"
          >
            <el-descriptions-item label="姓名">
              <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="性别">
              <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="年龄">
              <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="手机号">
              <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">
                 <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
                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%;"
            v-if="!isShowCard"
            height="160"
        >
          <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>
      </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">
          <el-button type="primary" @click="save" :disabled="edit_data.status==0">保存</el-button>
          <el-button @click="close">取消</el-button>
          <el-button v-if="edit_data.status==1" type="danger" @click="registrationCancel">退号</el-button>
        </div>
      </div>
    </template>
  </Mask>

</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 depts from "@/assets/config/directory/depts.json";
import {apiConfig} from "@/assets/config/apiConfig.ts";

const height = ref(470)
const certTypeList = ref<any>(
    Object.entries(psnCertTypes)
        .map(([id, name]) => ({id: Number(id), name}))
        .sort((a, b) => a.id - b.id)
)
const edit_data = ref<any>({})
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: 'blur'},
  ],
  spec: [
    {required: true, message: '请输入规格', trigger: 'blur'},
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
  ],
  organzationDoctorId: [
    {required: true, message: '请选择医生', trigger: 'blur'},
  ],
  certType: [
    {required: true, message: '请选择证件类型', trigger: 'blur'},
  ],
  certNo: [
    {required: true, message: '请输入证件码', trigger: 'blur'},
  ],
  visitType: [
    {required: true, message: '请选择就诊类型', trigger: 'blur'},
  ]
})
const isShow = ref(false)
const emit = defineEmits(['close'])
const close = () => {
  isShow.value = false
  edit_data.value = {}
  isShowCard.value = true
  nextTick(() => {
    cardDefaultRef.value?.close()
    height.value = 470
  })
  emit('close')
}
const form = ref()
const save = () => {
  let data = {
    ...edit_data.value,
    psnNo: socialCard.value?.data?.baseinfo.psn_no,
    insutype: socialCard.value?.data?.insuinfo[0].insutype
  }
  form.value.validate((v: any) => {
    if (v) {
      if (edit_data.value.id) {
        post('registration/edit', {
          data: data, mdtrtCertNo: socialCard.value?.mdtrtCertNo,
          mdtrtCertType: socialCard.value?.mdtrtCertType
        }).then(() => {
          ElMessage.success('修改成功')
          close()
        })
      } else {
        console.log(socialCard.value)
        post('registration/add', {
          data: data,
          mdtrtCertNo: socialCard.value?.mdtrtCertNo,
          mdtrtCertType: socialCard.value?.mdtrtCertType
        }).then(() => {
          ElMessage.success('挂号成功')
          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 init = (doctorId: any, id: any) => {
  isShow.value = true
  edit_data.value.organizationDoctorId = doctorId
  if (id) {
    post('registration/getById', {id: id}).then((res: any) => {
      edit_data.value = res
      edit_data.value.certType = Number(edit_data.value.certType)
    })
  }
  getSectionList()
  getDoctorList()
}
const isShowCard = ref<any>(true)
const tableData = ref<any>([])
const socialCardUpdate = (e: any) => {
  isShowCard.value = false
  if (e) {
    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 = Number(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
    if (edit_data.value.certNo) {
      post('vip/vip/list', {
        keyword: edit_data.value.certNo,
        page: 1,
        pageSize: 50
      }).then((res: any) => {
        edit_data.value.name = res.list[0].name
        edit_data.value.gender = res.list[0].sex
        edit_data.value.phone = res.list[0].phone
        edit_data.value.certType = Number(res.list[0].certType)
        edit_data.value.certNo = res.list[0].certNo
        edit_data.value.memo = res.list[0].remark
        edit_data.value.visitType = 1
      })
    }
  }
  nextTick(() => {
    if (tableData.value.length > 0) {
      height.value = 700

    } else {
      height.value = 470
    }
  })

  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 = 470
        })
      }
    },
  });
}
const showBtn = ref(false)
const showCardBtn = () => {
  showBtn.value = true
}
const hide = () => {
  showBtn.value = false
}
const sectionList = ref<any>([])
const getSectionList = () => {
  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
}
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;
}
</style>