<template>
  <view>
    <BackBar title="亲子关系" />
    <view class="tip">我是孩子的？</view>
    <view class="explain">请选择您与孩子的关系</view>

    <view class="selectContent">
      <view v-for="(item, index) in familyList" :key="index" class="item" @click="selectFun(index)">
        <image class="toux" :src="item.icon" mode="scaleToFill" />
        <text class="name">{{ item.name }}</text>

        <image
          class="select"
          :src="
            item.show ? `${OSS_URL}/urm/bindDevice/dx.png` : `${OSS_URL}/urm/bindDevice/nodx.png`
          "
          mode="scaleToFill"
        />
      </view>
    </view>

    <view class="sub" @click="subFun"> 确定 </view>
    <!-- 提交成功提示框 -->
    <TipPopup
      v-model="showSuccessPopup"
      showBtn
      :text="bindType === 'success' ? '绑定成功' : '绑定失败'"
      :type="bindType"
      :messageTip="successPopupText"
      :btnText="bindType === 'success' ? '确定' : '好的'"
      @backBtn="successPopupBtn"
    />
  </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { reactive, ref } from 'vue';
import { parentBindAdmin, getCurInfo } from '@/api';
import router from '@/router/router';
import TipPopup from '@/components/TipPopup/index.vue';
interface BindInfoType {
  adminFlag: boolean;
  bindFlag: number;
  bindText: string;
  icon: string;
  name: string;
  show: boolean;
}
const OSS_URL = import.meta.env.VITE_OSS_HOST;
const showSuccessPopup = ref(false); // 绑定成功提示
const successPopupText = ref('');
const type = ref<number>(); // 提交绑定状态
const bindType = ref('success');
const familyList = ref([
  {
    name: '爸爸',
    icon: `${OSS_URL}/urm/bindDevice/baba.png`,
    show: false,
    id: 1,
  },
  {
    name: '妈妈',
    icon: `${OSS_URL}/urm/bindDevice/mama.png`,
    show: false,
    id: 2,
  },
  {
    name: '爷爷',
    icon: `${OSS_URL}/urm/bindDevice/yeye.png`,
    show: false,
    id: 3,
  },
  {
    name: '奶奶',
    icon: `${OSS_URL}/urm/bindDevice/nainai.png`,
    show: false,
    id: 4,
  },
  {
    name: '外公',
    icon: `${OSS_URL}/urm/bindDevice/wg.png`,
    show: false,
    id: 5,
  },
  {
    name: '外婆',
    icon: `${OSS_URL}/urm/bindDevice/waipo.png`,
    show: false,
    id: 6,
  },
  {
    name: '其他',
    icon: `${OSS_URL}/urm/bindDevice/qita.png`,
    show: false,
    id: 7,
  },
]);
const bindInfo = ref({
  bindTwo: false, // 绑定两者
  bindChild: true,
  bindDevice: true,
});
// 参数暂存
const parameterData = reactive({
  childDto: {} as BindInfoType,
  deviceDto: {} as BindInfoType,
  simSerialNumber: '', // 设备序列号
  childUserId: '', // 孩子账号
  identityType: 7,
  type: 1, // type :1为绑定设备  2为绑定孩子 3都申请
});
const hidePopupAfterType = ref(); // 1向设备管理员申请 2向孩子管理员申请 3都成功 4 都失败
function selectFun(e) {
  familyList.value.forEach((item, index) => {
    if (index === e) {
      item.show = true;
    } else {
      item.show = false;
    }
  });
}

async function subFun() {
  let obj = familyList.value.filter(item => {
    return item.show === true;
  });
  if (obj.length === 0) {
    uni.showToast({ title: '请选择您与孩子的关系', icon: 'none' });
    return;
  }
  parameterData.identityType = obj[0].id;
  let bindAdminObj;

  if (bindInfo.value.bindTwo) {
    // 两者都选
    if (!parameterData.childDto.adminFlag && !parameterData.deviceDto.adminFlag) {
      bindAdminObj = {
        childDto: {
          childId: parameterData.childUserId,
          identityType: parameterData.identityType,
        },
        deviceDto: {
          simSerialNumber: parameterData.simSerialNumber,
          identityType: parameterData.identityType,
        },
      };
      await handleParentBindAmin(bindAdminObj);
    } else if (parameterData.childDto.adminFlag && parameterData.deviceDto.adminFlag) {
      parameterData.type = 3;
      router.navigateTo({
        path: '/pages/home/bindDevice/applyForBinding',
        query: { parameter: JSON.stringify(parameterData) }
      });
    } else if (parameterData.deviceDto.adminFlag) {
      bindAdminObj = {
        childDto: {
          childId: parameterData.childUserId,
          identityType: parameterData.identityType,
        },
      };
      await handleParentBindAmin(bindAdminObj, true);
      hidePopupAfterType.value = 1;
    } else {
      bindAdminObj = {
        deviceDto: {
          simSerialNumber: parameterData.simSerialNumber,
          identityType: parameterData.identityType,
        },
      };
      await handleParentBindAmin(bindAdminObj, true);
      hidePopupAfterType.value = 2;
    }
  } else if (bindInfo.value.bindDevice) {
    // 只绑设备
    if (parameterData.deviceDto.adminFlag) {
      parameterData.type = 1;
      router.navigateTo({
        path: '/pages/home/bindDevice/applyForBinding',
        query: { parameter: JSON.stringify(parameterData) }
      });
    } else {
      bindAdminObj = {
        deviceDto: {
          simSerialNumber: parameterData.simSerialNumber,
          identityType: parameterData.identityType,
        },
      };
      await handleParentBindAmin(bindAdminObj);
    }
  } else if (bindInfo.value.bindChild) {
    // 只绑孩子
    if (parameterData.childDto.adminFlag) {
      parameterData.type = 2;
      router.navigateTo({
        path: '/pages/home/bindDevice/applyForBinding',
        query: { parameter: JSON.stringify(parameterData) }
      });
    } else {
      bindAdminObj = {
        childDto: {
          childId: parameterData.childUserId,
          identityType: parameterData.identityType,
        },
      };
      await handleParentBindAmin(bindAdminObj);
    }
  }

  // 查看最新绑定结果
  // await getCurInfo({
  //     ...parameterData,
  // }).then(res => {
  //     console.log('xxxx', res);
  // });

  // parameterData.identityType = chatData.value.map(i => i.errorType).includes(1)
  // uni.navigateTo({ url: './applyForBinding' })
}
// 绑定成管理员
async function handleParentBindAmin(obj, isTwo?: boolean) {
  const res = await parentBindAdmin(obj);
  type.value = res.data;
  showSuccessPopup.value = true;
  switch (type.value) {
    case 0: // 孩子和设备绑定都失败
      bindType.value = 'fail';
      successPopupText.value = '请稍后再进行尝试～';
      hidePopupAfterType.value = 4;
      break;
    case 1: // 孩子绑定成功，设备绑定失败
      bindType.value = 'success';
      successPopupText.value = `您已成为孩子管理员！还需向设备<br>管理员申请绑定设备～`;
      hidePopupAfterType.value = 1;
      break;
    case 2: // 孩子绑定失败，设备绑定成功
      bindType.value = 'success';
      successPopupText.value = `您已成为设备管理员！还需向家长<br>管理员申请绑定孩子～`;
      hidePopupAfterType.value = 2;
      break;
    case 3: // 孩子和设备绑定都成功
      bindType.value = 'success';
      successPopupText.value = `您已成为设备管理员和孩子账号的<br>家长管理员！`;
      hidePopupAfterType.value = 3;
      break;
    case 4: // 孩子绑定成功
      bindType.value = 'success';
      if (isTwo) {
        successPopupText.value = `您已成为孩子管理员！还需向设备<br>管理员申请绑定设备～`;
        hidePopupAfterType.value = 1;
      } else {
        successPopupText.value = `您已成为孩子管理员！`;
        hidePopupAfterType.value = 3;
      }
      break;
    case 5: // 孩子绑定失败
      bindType.value = 'fail';
      successPopupText.value = `请稍后再进行尝试～`;
      hidePopupAfterType.value = 4;
      break;
    case 6: // 设备绑定成功
      bindType.value = 'success';
      if (isTwo) {
        successPopupText.value = `您已成为设备管理员！还需向家长<br>管理员申请绑定孩子～`;
        hidePopupAfterType.value = 2;
      } else {
        successPopupText.value = `您已成为设备管理员`;
        hidePopupAfterType.value = 3;
      }
      break;
    case 7: // 设备绑定失败
      bindType.value = 'fail';
      successPopupText.value = `请稍后再进行尝试～`;
      hidePopupAfterType.value = 4;
      break;
  }
}
function successPopupBtn() {
  showSuccessPopup.value = false;
  switch (hidePopupAfterType.value) {
    case 1:
      parameterData.type = 1;
      router.navigateTo({
        path: '/pages/home/bindDevice/applyForBinding',
        query: { parameter: JSON.stringify(parameterData) }
      });
      break;
    case 2:
      parameterData.type = 2;
      router.navigateTo({
        path: '/pages/home/bindDevice/applyForBinding',
        query: { parameter: JSON.stringify(parameterData) }
      });
      break;
    case 3:
      router.navigateTo('/pages/home/index');
      break;
    case 4:
      router.navigateTo('/pages/home/index');
      break;
  }
}
onLoad(option => {
  let datas = JSON.parse(option.parameter);
  parameterData.childUserId = datas.childUserId;
  parameterData.simSerialNumber = datas.simSerialNumber;
  parameterData.childDto = datas.childDto;
  parameterData.deviceDto = datas.deviceDto;
  bindInfo.value.bindChild = datas.childUserId ? true : false;
  bindInfo.value.bindDevice = datas.simSerialNumber ? true : false;
  bindInfo.value.bindTwo = datas.simSerialNumber && datas.childUserId ? true : false;
});
</script>

<style lang="scss" scoped>
.tip {
  margin-top: 50upx;
  font-size: 34upx;
  color: rgba(51, 51, 51, 1);
  width: 100%;
  text-align: center;
}
.explain {
  font-size: 30upx;
  color: rgba(102, 102, 102, 1);
  margin-top: 20upx;
  width: 100%;
  text-align: center;
}

.selectContent {
  width: 100%;
  padding: 30upx;
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  gap: 30upx;
  .item {
    width: 330upx;
    height: 160upx;
    display: flex;
    align-items: center;
    padding: 30upx;
    box-sizing: border-box;
    border-radius: 20upx;
    background-color: #fff;
    position: relative;

    .toux {
      width: 100upx;
      height: 100upx;
    }
    .name {
      font-size: 30upx;
      margin-left: 20upx;
    }

    .select {
      width: 30upx;
      height: 30upx;
      position: absolute;
      right: 30upx;
      top: 65upx;
    }
  }
}

.sub {
  width: 690upx;
  height: 90upx;
  border-radius: 20upx;
  color: #fff;
  font-size: 30upx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 120upx;
  background-color: rgba(97, 93, 255, 1);
  margin-left: 30upx;
}
:deep(.tip_popup .popup_box) {
  height: 423rpx;
}
</style>
