<template>
  <view class="container safe-area-inset-bottom">
    <MessageNotification />
    <!-- 标题 -->
    <view class="title">
      您需要为谁{{ registerType === '3'? '购药' : '挂号' }}
      <text>请选择患者信息，以便医生给出更准确的诊疗建议，患者信息仅医生可见</text>
    </view>
    <!-- 就诊人 -->
    <view class="detail">
      <!-- relation -->
      <view class="one" :class="actived==item.id ? 'active' :''" @click="choose(item.id)"
            v-for="(item,index) in setInfoList" :key="item.id">
        <view class="name">
          {{item.name}}
          <text class="iconfont icon-bianji" v-if="actived==item.id" @click="toEdit"></text>
        </view>
        <text>{{(item.sex)% 2 == 1 ? "男" : "女"}} &nbsp; {{item.age}}岁</text>
        <image src="@/static/choose/choosed.png" mode=""></image>
      </view>


      <!-- 添加就诊人 -->
      <view class="other" @click="goAdd(0)">
        <text>+</text>
      </view>
    </view>

    <!-- 挂号类型展示（只读） -->
    <view class="card" style="padding-bottom: 0">
      <view class="card_title">
        挂号类型
      </view>
      <view class="card_names">
        <view class="register-type-display">
          <text class="type-label">{{ registerTypeLabel }}</text>
        </view>
      </view>
    </view>

    <!-- 健康信息（仅线下问诊时显示） -->
    <view class="card" v-if="actived!=1 && registerType === '0'" style="margin-top: 0;">
      <view class="card_title">
        健康信息
      </view>
      <!-- 肝功能 -->
      <view class="card_names">
        <text>肝功能</text>
        <u-radio-group v-model="liver" size="44rpx">
          <u-radio size="44rpx" active-color="#2979FF" :name="liver">
            {{liver}}
          </u-radio>
        </u-radio-group>
      </view>

      <!-- 肾功能 -->
      <view class="card_names">
        <text>肾功能</text>
        <u-radio-group v-model="renal" size="44rpx">
          <u-radio :name="renal">
            {{renal}}
          </u-radio>
        </u-radio-group>
      </view>
      <!-- 过敏史 -->
      <view class="card_history">
        <view class="name">
          <text>过敏史</text>
          <u-radio-group v-model="allergic" size="44rpx">
            <u-radio :name="allergic">
              {{allergic}}
            </u-radio>
          </u-radio-group>
        </view>
        <view class="tabs" v-if="allergicList[0]!='' && allergic === '有'">
          <u-tag bg-color="#2979FF" color="#FFFFFF" v-for="(item,index) in allergicList" :key="index"
                 :text="item" mode="dark" />
        </view>
      </view>
      <!-- 个人病史 -->
      <view class="card_history">
        <view class="name">
          <text>个人病史</text>
          <u-radio-group v-model="person" @change="radioGroupChange" size="44rpx">
            <u-radio :name="person">
              {{person}}
            </u-radio>
          </u-radio-group>
        </view>
        <view class="tabs" v-if="personList[0]!='' && person === '有'">
          <u-tag bg-color="#2979FF" color="#FFFFFF" v-for="(item,index) in personList" :key="index"
                 :text="item" mode="dark" />
        </view>
      </view>
      <!-- 家族病史 -->
      <view class="card_history">
        <view class="name">
          <text>家族病史</text>
          <u-radio-group v-model="family" @change="radioGroupChange" size="44rpx">
            <d-radio :name="family">
              {{family}}
            </d-radio>
          </u-radio-group>
        </view>
        <view class="tabs" v-if="familyList[0]!='' && family === '有'">
          <u-tag bg-color="#2979FF" color="#FFFFFF" v-for="(item,index) in familyList" :key="index"
                 :text="item" mode="dark" />
        </view>
      </view>
    </view>

    <!-- 底部 -->
    <view class="footer">
      <view class="infos" @click="subScriptionMessage">
        确认
      </view>
    </view>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
import {
  userList,
  userEidtPatient,
  registe
} from '@/request/api/api.js'
import {checkDev} from "@/utils/utils";
import {genOrderApi, saveRegisterInfoApi} from "@/request/api/order";
import request from "@/request/api/request";
export default {
  data() {
    return {
      Did: "",
      show: false,
      addtext: "",
      addNum: 0,
      text: "", // 添加
      actived: 1, // 选中 // 就诊人id
      list: [{
        name: '无',
        checked: true,
        disabled: true,
      }, {
        name: '有',
        checked: true,
        disabled: true,
      }],
      lists: [{
        name: '正常',
        checked: true,
        disabled: true
      },
        {
          name: '异常',
          checked: true,
          disabled: true
        }
      ],

      visitList: [{
        name: '是',
        disabled: false
      }],
      // u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
      isVisit: '', // 是否接诊过
      visitDesc: "", // 病情
      infoList: [], // 就诊人列表
      register_id: "", // 挂号id
      liver: "", // 肝功能
      renal: "", // 肾功能
      allergic: "", // 过敏史
      allergicList: [],
      person: "", // 个人病史
      personList: [],
      family: "", // 家庭病史
      familyList: [],
      type: "",
      avator: "",
      name: "",
      heathList: [], // 健康信息
      rInfo: [], // 健康信息
      registerType: "0", // 新增：挂号类型（0线下/1线上）
      delegateStoreId: '', // 委托诊所ID（购药时使用）
    }
  },
  onLoad(e) {
    this.Did = e.id
    if (e.r_type) {
      this.registerType = e.r_type
      // 对 r_info 进行 URL 解码（如果它是字符串）
      if (e.r_info) {
        try {
          // 如果是字符串，先解码再解析 JSON
          if (typeof e.r_info === 'string') {
            this.rInfo = JSON.parse(decodeURIComponent(e.r_info))
          } else {
            // 如果已经是对象，直接使用
      this.rInfo = e.r_info
          }
        } catch (error) {
          console.error('解析 r_info 失败:', error)
          this.rInfo = {}
        }
      } else {
        this.rInfo = {}
      }
    }
    // 获取委托诊所ID（如果有）
    this.delegateStoreId = e.delegate_store_id || '';

    console.log(e)
  },
  computed: {
    setInfoList() {
      let list = []
      list = this.infoList.map((item) => {

        return {
          ...item,
          // age: this.getAge(item.id_card),
        }
      })
      return list
    },
    // 挂号类型标签
    registerTypeLabel() {
      const typeMap = {
        '0': '线下就诊',
        '1': '在线问诊',
        '2': '预约购药',
        '3': '在线复诊'
      };
      return typeMap[this.registerType] || '未知类型';
    }
  },
  methods: {
    checkDev,
    // 处理挂号类型切换
    handleTypeChange(type) {
      this.registerType = type;
    },

    // 年龄
    getAge(identityCard) {
      var len = (identityCard + "").length;
      if (len == 0) {
        return '';
      } else {
        if ((len != 15) && (len != 18)) //身份证号码只能为15位或18位其它不合法
        {
          return '';
        }
      }
      var strBirthday = "";
      if (len == 18) //处理18位的身份证号码从号码中得到生日和性别代码
      {
        strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(
            12, 2);
      }
      if (len == 15) {
        strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard
            .substr(10, 2);
      }
      //时间字符串里，必须是“/”
      var birthDate = new Date(strBirthday);
      var nowDateTime = new Date();
      var age = nowDateTime.getFullYear() - birthDate.getFullYear();
      //再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
      if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() &&
          nowDateTime.getDate() < birthDate.getDate())) {
        age--;
      }
      return age;
    },
    // 选中某个单选框时，由radio时触发
    radioChange(e) {
      // console.log(e,'e');
    },
    // 选中任一radio时，由radio-group触发
    radioGroupChange(e) {
      // console.log(e, '1');

      // console.log(this.family, 'is');
    },
    // 返回
    goback() {
      uni.navigateBack({
        delta: 1
      })
    },

    // 添加就诊人
    goAdd(e) {
      // console.log(e,'eeee');
      uni.navigateTo({
        url: "/subPackages/my/myinfo-add?id=",
      })
    },

    // 修改信息
    toEdit() {
      uni.navigateTo({
        url: '/subPackages/my/myinfo-edit?id=' + this.actived
      })
    },

    // 切换
    choose(id) {
      this.actived = id
      this.getHeath()
    },

    // 就诊人列表
    getInfolist() {
      userList({
        method: "post",
        data: {
          store_id: uni.getStorageSync('store_id') || '11001',
        }
      }).then((res) => {
        // console.log(res, 'info');
        if (res.data.errcode == 0) {
          this.infoList = res.data.data

          this.infoList.filter(item => {
            if (item.is_default == 1) {
              // console.log(`${item.id}`);

              this.actived = item.id
            }
          })
          this.getHeath()
        }
      })
    },

    // 挂号
    getAsk() {
      uni.showLoading({
        title: "加载中...",
        mask: true
      });
      // 如果是购药类型(register_type=3)且有委托诊所ID，则使用委托诊所ID；否则使用当前门店ID
      const storeId = (this.registerType != '0' && this.delegateStoreId)
        ? this.delegateStoreId 
        : (uni.getStorageSync('store_id') || '11001');
      // const storeId = ((this.registerType === '3' || this.registerType == '2') && this.delegateStoreId)
      //   ? this.delegateStoreId
      //   : (uni.getStorageSync('store_id') || '11001');
      registe({
        method: "post",
        data: {
          user_id: uni.getStorageSync('user_id'),
          user_patient_id: this.actived,
          store_id: storeId,
          service_user_id: this.Did,
          register_type: this.registerType // 新增：挂号类型参数
        }
      }).then((res) => {
        // console.log(res, 'ask');

        if (res.data.errcode == 0) {
          this.register_id = res.data.data.register_id
          // if (this.registerType === "3" || this.registerType === "2") {
          if (this.registerType === "3") {
            // this.rInfo 在 onLoad 中已经解析为对象，直接使用
            let params = typeof this.rInfo === 'string' ? JSON.parse(this.rInfo) : this.rInfo;

            // 如果有 info_id，使用新接口更新关联；否则用旧接口保存
            if (params.info_id) {
              // 新流程：更新已创建的 RegisterInfo 的 register_id
              request('/xkApi/order/update-register-info-register-id', {
                method: 'POST',
                data: {
                  info_id: params.info_id,
                  register_id: this.register_id,
                }
              }).then(() => {
                // 跳转到挂号页面，让用户确认挂号并支付
                const rInfoStr = typeof this.rInfo === 'string' ? this.rInfo : JSON.stringify(this.rInfo);
                uni.navigateTo({
                  url: `/subPackages/register/register?id=${this.register_id}&doctor_id=${this.Did}&r_info=${encodeURIComponent(rInfoStr)}`
                });
              }).catch((error) => {
                console.error('更新就诊信息关联失败:', error);
                // 即使更新失败，也跳转到挂号页面
                uni.navigateTo({
                  url: `/subPackages/register/register?id=${this.register_id}&doctor_id=${this.Did}&r_info=${encodeURIComponent(typeof this.rInfo === 'string' ? this.rInfo : JSON.stringify(this.rInfo))}`
                });
              });
            } else {
              // 旧流程：保存病患信息（兼容没有 info_id 的情况）
              saveRegisterInfoApi({
                register_id: this.register_id,
                doctor_id: params.doctor_id || this.Did,
                drug_id: params.drug_id || params.id,
                has_visited: params.has_visited || params.hasVisited,
                has_used_drug: params.has_used_drug || params.hasUsedDrug,
                illnessInfo: params.illness_info || params.illnessInfo,
                type: params.type,
                number: params.number,
                store_id: uni.getStorageSync('store_id') || '11001',
              }).then(() => {
                // 跳转到挂号页面，让用户确认挂号并支付
                const rInfoStr = typeof this.rInfo === 'string' ? this.rInfo : JSON.stringify(this.rInfo);
                uni.navigateTo({
                  url: `/subPackages/register/register?id=${this.register_id}&doctor_id=${this.Did}&r_info=${encodeURIComponent(rInfoStr)}`
                });
              }).catch((error) => {
                console.error('保存患者就诊信息失败:', error);
                // 即使保存失败，也跳转到挂号页面
                uni.navigateTo({
                  url: `/subPackages/register/register?id=${this.register_id}&doctor_id=${this.Did}&r_info=${this.rInfo}`
                });
              });
            }
            return;
          }
          uni.setStorageSync('register_id', this.register_id)

          if (res.data.data.isHas == 0) {
            uni.navigateTo({
              url: `/subPackages/register/register?id=${this.register_id}&doctor_id=${this.Did}&r_info=${this.rInfo}`,
            })
          } else {
            this.$refs.uToast.show({
              title: '您已挂号该医生，请继续问诊服务',
              type: 'default',
              icon: false
            })
            setTimeout(() => {
              uni.navigateTo({
                url: `/subPackages/register/register?id=${this.register_id}&doctor_id=${this.Did}&r_info=${this.rInfo}`,
              })
            }, 900)
          }
        } else {
          this.$refs.uToast.show({
            title: res.data.msg,
            type: 'default',
            icon: false
          })
        }
      }).finally(() => {
        uni.hideLoading();
      })

    },

    // 健康信息
    getHeath() {
      userEidtPatient({
        method: "post",
        data: {
          user_patient_id: this.actived,
          store_id: uni.getStorageSync('store_id') || '11001',
        }
      }).then((res) => {
        // console.log(res, 'heath');
        if (res.data.errcode == 0) {
          this.heathList = res.data.data

          this.liver = (this.heathList.liver_function) % 2 == 0 ? '正常' : '异常'
          this.renal = (this.heathList.renal_function) % 2 == 0 ? '正常' : '异常'

          this.allergic = (this.heathList.allergic_status) % 2 == 0 ? '无' : '有'
          this.allergicList = (this.heathList.allergic_history) == 'Array' ? [] : (this.heathList
              .allergic_history)

          this.person = (this.heathList.person_status) % 2 == 0 ? '无' : '有'
          this.personList = (this.heathList.person_history) == 'Array' ? [] : (this.heathList
              .person_history)

          this.family = (this.heathList.family_status) % 2 == 0 ? '无' : '有'
          this.familyList = (this.heathList.family_history) == 'Array' ? [] : (this.heathList
              .family_history)
        }
      })
    },
    //订阅消息
    subScriptionMessage() {
      uni.requestSubscribeMessage({
        tmplIds: ['O5P8ZZB6T01V5Z66tkbhmzlobSaSRoEfdoCLATuP2Mw',
          'ddT3v-m_Sr4kXwGCBLf0O4P89mOS5q10LFMZeEuQm10'
        ],
        complete: (res) => {
          // console.log(res,'xxxxxxxxxxxx');
          this.getAsk()
        }
      })
    },
  },
  mounted() {
    this.getInfolist()
  },
  onShow() {
    this.getInfolist()
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 750rpx;
  max-height: 100%;
  min-height: 100vh;

  .title {
    width: 686rpx;
    height: 120rpx;
    font-size: 36rpx;
    font-family: PingFang SC-Medium, PingFang SC;
    font-weight: 500;
    color: #1E293B;
    margin: 32rpx 32rpx 0 32rpx;

    text {
      display: inline-block;
      font-size: 24rpx;
      font-weight: 400;
      color: #6C7380;
      margin-top: 16rpx;
    }
  }

  .detail {
    width: 710rpx;
    height: 280rpx;
    margin: 32rpx;
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .one {
      width: 218rpx;
      height: 124rpx;
      border-radius: 8rpx;
      margin: 0 16rpx 16rpx 0;
      border: 2rpx solid #CBD5E1;
      position: relative;

      .name {
        margin: 16rpx 0 8rpx 32rpx;
        height: 44rpx;
        font-size: 32rpx;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #0F172A;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-right: 18rpx;

        .iconfont {
          font-size: 32rpx;
          color: #94A3B8;
        }
      }

      text {
        height: 40rpx;
        font-size: 28rpx;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #94A3B8;
        margin-left: 32rpx;
      }

      image {
        width: 50rpx;
        height: 50rpx;
        position: absolute;
        right: -2rpx;
        bottom: -1rpx;
        display: none;
      }


    }

    .active {

      border: 2rpx solid #536DFE;

      image {
        display: block;
      }
    }

    .other {
      width: 218rpx;
      height: 124rpx;
      line-height: 104rpx;
      text-align: center;
      border-radius: 8rpx;
      border: 2rpx solid #CBD5E1; /* 修复：移除多余的b字符 */
      margin-top: -10rpx;

      text {
        font-size: 68rpx;
        color: #CBD5E1;
      }
    }
  }


  .card {
    width: 710rpx;
    background: #FFFFFF;
    border-radius: 8rpx;
    margin: 20rpx auto 40rpx;
    padding: 0 32rpx 190rpx;
    font-family: PingFang SC-Regular, PingFang SC;

    .card_title {
      height: 114rpx;
      line-height: 114rpx;
      font-size: 36rpx;
      font-weight: 500;
      color: #1E293B;
      border-bottom: 1rpx solid #E2E8F0;
    }

    .card_name:last-child {
      border-bottom: 0;
    }

    .card_names {
      width: 646rpx;
      padding: 34rpx 0 32rpx 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 30rpx;
      border-bottom: 1rpx solid #E2E8F0;

      text {
        font-weight: 400;
        color: #1E293B;
      }

      ::v-deep .u-input {
        width: 380rpx;
      }

      .register-type-display {
        display: flex;
        align-items: center;
        
        .type-label {
          display: inline-block;
          padding: 8rpx 24rpx;
          background: linear-gradient(135deg, #4175EE 0%, #298dff 100%);
          color: #FFFFFF;
          font-size: 28rpx;
          font-weight: 500;
          border-radius: 8rpx;
        }
      }
    }

    .card_history {
      width: 646rpx;
      padding: 34rpx 0 32rpx 0;
      font-size: 30rpx;
      border-bottom: 1rpx solid #E2E8F0;

      .name {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-right: 5rpx;
        margin-bottom: 10rpx;

        text {
          font-weight: 400;
          color: #1E293B;
        }

        ::v-deep .uni-radio-wrapper .uni-radio-input {
          background-color: transparent;
          border: 2rpx solid #E8E9EB;
        }

        ::v-deep .uni-radio-wrapper .uni-radio-input.uni-radio-input-checked {
          background-color: rgba($color: #000000, $alpha: 0) !important;
          border: 2rpx solid #2979FF;
          position: relative;

          &::before {
            display: inline-block;
            content: '';
            width: 70%;
            height: 70%;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            background-color: #2979FF;
            border: none;
            border-radius: 50%;
          }
        }

      }

      .tabs {
        display: flex;
        flex-wrap: wrap;

        ::v-deep .u-tag {
          margin: 10rpx 20rpx 10rpx 0;
        }

        text {
          font-size: 28rpx;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          color: #4175EE;
          margin: 10rpx 20rpx;
          text-align: center;
          border: 1rpx solid #4175EE;
          padding: 4rpx 8rpx;
        }
      }

    }

    .card_history:last-child {
      border-bottom: 0;
    }


    .card_relation {
      width: 646rpx;
      height: 106rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 30rpx;
      border-bottom: 1rpx solid #E2E8F0;

      text {
        font-weight: 400;
        color: #1E293B;
      }

      .u-icon {
        vertical-align: middle;
        margin-top: 2rpx;
      }

      ::v-deep .u-input {
        margin-left: 130rpx;
      }

      ::v-deep .u-input__right-icon ::before {
        content: ""
      }

      .choose {
        font-weight: 400;
        color: #94A3B8;
      }
    }

    .card_telephone {
      width: 646rpx;
      height: 106rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 30rpx;

      text {
        font-weight: 400;
        color: #1E293B;
      }

    }
  }

  .floor {
    z-index: 99;

    .floor_item {
      padding: 32rpx;
      font-size: 32rpx;
      text-align: center;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;

      .title {
        height: 66rpx;
        width: 620rpx;
        font-size: 36rpx;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #1E293B;
      }

      .u_btn {
        margin: 40rpx 0;
      }

      .u_inp {
        margin: 40rpx 0;

        ::v-deep .u-input {
          background: #F1F5F9;
        }
      }

      .info {
        width: 620rpx;
        margin: 40rpx 0;

        .addinfo {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 620rpx;

          .words {
            height: 42rpx;
            font-size: 30rpx;
            font-family: PingFang SC-Regular, PingFang SC;
            font-weight: 400;
            color: #1E293B;
            margin: 20rpx 0 10rpx;
          }

          .radios {}
        }

      }
    }
  }

  .footer {
    width: 750rpx;
    height: 104rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border: 2rpx solid #F2F3F5;
    position: fixed;
    left: 0;
    bottom: env(safe-area-inset-bottom);
    background-color: #fff;



    .infos {
      width: 686rpx;
      height: 90rpx;
      line-height: 90rpx;
      display: flex;
      justify-content: space-around;
      align-items: center;
      margin: 16rpx 0;
      font-size: 32rpx;
      font-family: PingFang SC-Medium, PingFang SC;
      font-weight: 500;
      text-align: center;
      height: 86rpx;
      background: #4175EE;
      border-radius: 198rpx;
      color: #FFFFFF;
      margin-left: 32rpx;
    }
  }
}
</style>