<template>
  <Mask :width="650" :height="580" :is-show="show" @close="show=false" :title="id?'患者编辑':'患者建档'"
        :show-footer="true">
    <template #default>
      <el-scrollbar>
        <div class="content" v-loading="loading">
          <el-form
              :model="ruleForm"
              label-width="auto"
              :rules="rules"
              ref="ruleFormRef"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="等级">
                  <el-select
                      v-model="ruleForm.exp"
                      placeholder="等级"
                      size="default"
                      :disabled="ruleForm.id"
                      style="width: 100%"
                  >
                    <el-option
                        v-for="item in levelList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.startExp"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="ruleForm.name" placeholder="输入真实姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="ruleForm.sex">
                    <el-radio :value="1">男</el-radio>
                    <el-radio :value="2">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="年龄" prop="age">
                  <el-input v-model.number="ruleForm.age"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="ruleForm.phone" placeholder="输入电话号码"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="证件类型" prop="certType">
                  <el-select
                      v-model="ruleForm.certType"
                      placeholder="证件类型"
                      size="default"
                      style="width: 100%"
                  >
                    <el-option
                        v-for="item in cardTypeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="证件号" prop="certNo">
                  <el-input v-model="ruleForm.certNo" placeholder="证件号"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="生日" prop="birthday">
                  <el-date-picker style="width: 100%" v-model="ruleForm.birthday" type="date" placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="民族">
                  <el-select
                      v-model="ruleForm.nation"
                      placeholder="民族选择"
                      size="default"
                      style="width: 100%"
                  >
                    <el-option
                        v-for="item in antysList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="来源">
                  <el-select
                      v-model="ruleForm.source"
                      placeholder="来源选择"
                      size="default"
                      style="width: 100%"
                  >
                    <el-option
                        v-for="item in options1"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="地区">
              <SelectArea v-model="ruleForm.area" style="width: 100%"></SelectArea>
            </el-form-item>
            <el-form-item label="详细地址">
              <el-input v-model="ruleForm.address"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="ruleForm.remark"></el-input>
            </el-form-item>
            <el-form-item label="既往史">
              <el-input v-model="ruleForm.beforeMedicalHistory"></el-input>
            </el-form-item>
            <el-form-item label="过敏史">
              <el-input v-model="ruleForm.allergyHistory"></el-input>
            </el-form-item>
          </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>
      </el-scrollbar>
    </template>
    <template #footer>
      <div class="bottom">
        <el-dropdown v-if="isShowCard" placement="top-start" @show="showCardBtn" @hide="hide"
                     :disabled="ruleForm.status==0">
          <div class="left" style="outline: none;">
            <span class="btnCard" type="primary">
              <img class="image" src="/static/images/registration/card.png" alt=""
                   srcset="">{{ ruleForm.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="default-btn" @click="close">取消</span>
          <span class="default-btn" @click="submitForm">保存</span>
        </div>
      </div>
    </template>
  </Mask>
</template>
<script setup lang="ts">
import {nextTick, onMounted, ref} from "vue"
import {
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElRow,
  ElCol,
  ElRadioGroup,
  type FormInstance,
  ElMessageBox
} from "element-plus";
import SelectArea from "@/components/SelectArea.vue";
import {post} from "@/utils/request.ts";
import Mask from "@/components/common/Mask.vue";
import psnCertTypes from "@/assets/config/directory/psnCertTypes.json"
import antys from '@/assets/config/directory/antys.json'
import {formatDate} from "@/utils/dateUtils.ts";
import CardDefault from "@/components/registration/CardDefault.vue";
import {getKey} from "@/utils/discrotyUtil.ts";
import insutypes from "@/assets/config/directory/insutypes.json";


const ruleFormRef = ref<FormInstance>()
const id = ref<any>(null)
const show = ref<boolean>(false)
const emit = defineEmits(['close'])
const antysList = ref<any>(Object.entries(antys)
    .map(([id, name]) => ({id: Number(id), name}))
    .sort((a, b) => a.id - b.id))
const cardTypeList = ref<any>(Object.entries(psnCertTypes)
    .map(([id, name]) => ({id: Number(id), name}))
    .sort((a, b) => a.id - b.id))
const showBtn = ref(false)
const height = ref<any>(470)
const close = () => {
  ruleForm.value = {}
  id.value = ''
  show.value = false
  isShowCard.value = true
  nextTick(() => {
    cardDefaultRef.value?.close()
    height.value = 470
  })
  emit('close')
}
const showCardBtn = () => {
  showBtn.value = true
}
const hide = () => {
  showBtn.value = false
}
const isShowCard = ref<any>(true)
const tableData = ref<any>([])
const socialCard: any = ref({
  data: null,
  payInfo: {},
  lastUse: null
})
const socialCardUpdate = (e: any) => {
  isShowCard.value = false
  if (e) {
    isShowCard.value = false
    ruleForm.value.sex = Number(e.data.baseinfo.gend)
    ruleForm.value.name = e.data.baseinfo.psn_name
    ruleForm.value.certType = Number(e.data.baseinfo.psn_cert_type)
    ruleForm.value.nation = Number(e.data.baseinfo.naty)
    ruleForm.value.certNo = e.data.baseinfo.certno
    ruleForm.value.age = Math.floor(e.data.baseinfo.age)
    tableData.value = e.data.insuinfo
    // if (ruleForm.value.certNo) {
    //   post('vip/vip/list', {
    //     keyword: ruleForm.value.certNo,
    //     page: 1,
    //     pageSize: 50
    //   }).then((res: any) => {
    //     ruleForm.value.name = res.list[0].name
    //     ruleForm.value.sex = res.list[0].sex
    //     ruleForm.value.phone = res.list[0].phone
    //     ruleForm.value.certType = Number(res.list[0].certType)
    //     ruleForm.value.certNo = res.list[0].certNo
    //     ruleForm.value.memo = res.list[0].remark
    //     ruleForm.value.visitType = 1
    //   })
    // }
  }
// }

  loading.value = false
}
const loading = ref(false)
const changeLoading = (e: any) => {
  loading.value = e
}
const cardDefaultRef = ref<any>("")
const deleteCard = () => {
  ElMessageBox.confirm("退出识别", "提示", {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    callback: (action: any) => {
      if (action == "confirm") {
        isShowCard.value = true
        ruleForm.value = {}
        tableData.value = []
        nextTick(() => {
          cardDefaultRef.value?.close()
        })
      }
    },
  });
}
// form表单数据
let ruleForm = ref<any>({
  exp: 0,
  phone: '',
  name: '',
  sex: '',
  age: null,
  birthday: '',
  certNo: '',
  source: '',
  nation: '',
  area: '',
  address: '',
  remark: '',
  beforeMedicalHistory: '',
  allergyHistory: '',
  certType: '',
  levelId: ''
})

const options1 = [
  {
    value: '员工推荐',
    label: '员工推荐',
  },
  {
    value: '顾客推荐',
    label: '顾客推荐'
  },
  {
    value: '线上活动',
    label: '线上活动'
  },
  {
    value: '线下活动',
    label: '线下活动'
  },
  {
    value: '其他',
    label: '其他'
  }
]
const submitForm = async () => {
  let formEl = ruleFormRef.value
  if (!formEl) return
  await formEl.validate((valid: any) => {
    if (valid) {
      ruleForm.value.birthday = formatDate(ruleForm.value.birthday)
      if (ruleForm.value.id) {
        post("vip/vip/update", {vipInfo: ruleForm.value}).then(() => {
          close()
        })
      } else {
        post("vip/vip/create", {vipInfo: ruleForm.value}).then(() => {
          close()
        })
      }

    }
  })
}
const levelName = ref('')
const rules = ref<any>({
  name: [
    {required: true, message: '姓名不能为空', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '手机号不能为空', trigger: 'blur'}
  ],
  sex: [
    {required: true, message: '性别不能为空', trigger: 'blur'}
  ],
  birthday: [
    {required: true, message: '请选择生日', trigger: 'change'}
  ],
  certType: [
    {required: true, message: '请选择证件类型', trigger: 'blur'}
  ],
  certNo: [
    {required: true, message: '请输入证件号', trigger: 'blur'}
  ],
  age: [
    {required: true, message: '年龄不能为空', trigger: 'blur'},
    {type: 'number', message: '年龄必须为数字', trigger: 'blur'}
  ],
})
const init = (_id: any) => {
  id.value = _id
  levelName.value = ''
  show.value = true
  if (!id.value) {
    ruleForm.value = {}
    return
  } else {
    post("vip/vip/get", {id: _id}).then((res: any) => {
      ruleForm.value = res
      ruleForm.value.area = JSON.parse(ruleForm.value.area)
      ruleForm.value.levelId = ruleForm.value.levelId == 0 ? null : ruleForm.value.levelId
      ruleForm.value.certType=Number(ruleForm.value.certType)
      ruleForm.value.nation=Number(ruleForm.value.nation)||''
      if (!res.levelId) return
      post("vip/vipLevel/get", {levelId: res.levelId}).then((res: any) => {
        levelName.value = res.name
      })
    })
  }


}
const levelList = ref<any>([])
const getLevelConfig = () => {
  post("vip/vipLevel/list").then((res: any) => {
    levelList.value = res
  })
}
onMounted(() => {
  getLevelConfig()
})
defineExpose({init})
</script>
<style scoped lang="scss">
.content {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;

}

.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;
  }
}
</style>