import { defineComponent, onMounted, ref, watch } from 'vue';
import styles from './index.module.less';
import { Radio, RadioGroup, Image, Button } from 'vant';
import checkBoxActive from './images/icon-n-1.png';
import checkBoxDefault from './images/icon-n-2.png';
import request from '@/helpers/request';
import { storage } from '@/helpers/storage';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import { setLogin } from '@/state';

export default defineComponent({
  name: 'login-change-model',
  props: {
    credential: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const radioChecked = ref();
    const btnLoading = ref(false);
    const list = ref([] as any);

    watch(
      () => props.credential,
      () => {
        getUserList();
      }
    );

    const getUserList = async () => {
      try {
        if (!props.credential?.token) return;
        const { data } = await request.post('/edu-app/open/user/getMultiUser', {
          data: {
            ...props.credential
          }
        });
        const result = data || [];
        const tempList = [] as any;
        result.forEach((item: any) => {
          tempList.push({
            userId: item.studentId,
            avatar: item.avatar,
            nickname: item.nickname,
            schoolName: item.schoolName,
            token: item.token,
            tokenExpireTime: item.tokenExpireTime
          });
        });
        list.value = tempList;
      } catch {
        //
      }
    };

    onMounted(async () => {
      getUserList();
    });
    return () => (
      <div class={styles.loginChangeModel}>
        <i
          class={styles.iconClose}
          onClick={() => {
            emit('close');
          }}></i>
        <div class={styles.popupTitle}>
          <span>选择学生</span>
        </div>
        <RadioGroup class={styles.selectStudent} v-model={radioChecked.value}>
          {list.value.map((item: any) => (
            <div
              class={[
                styles.cell,
                radioChecked.value === item.userId && styles.cellSelected
              ]}
              onClick={() => {
                radioChecked.value = item.userId;
                // emit('confirm', item);
                // emit('close');
              }}>
              <Radio name={item.userId}>
                {{
                  icon: (props: any) => (
                    <Image
                      class={styles.iconImage}
                      src={props.checked ? checkBoxActive : checkBoxDefault}
                    />
                  )
                }}
              </Radio>

              <div class={styles.userInfo}>
                <Image src={item.avatar} class={styles.userImg} fit="cover" />

                <div class={styles.usernames}>
                  <div class={styles.name}>
                    <span class={styles.names}>{item.nickname}</span>
                  </div>
                  {item.schoolName && (
                    <div class={styles.schoolname}>{item.schoolName}</div>
                  )}
                </div>
              </div>
            </div>
          ))}
        </RadioGroup>

        <div class={styles.addStudentBtn}>
          <Button
            block
            round
            loading={btnLoading.value}
            disabled={!radioChecked.value || btnLoading.value}
            onClick={async () => {
              btnLoading.value = true;
              try {
                const item = list.value.find(
                  (item: any) => item.userId === radioChecked.value
                );
                if (!item.userId) return;
                const forms: any = {
                  username: props.credential.phone,
                  client_id: 'cooleshow-student',
                  client_secret: 'cooleshow-student',
                  password: item.token,
                  grant_type: 'password',
                  loginType: 'TOKEN'
                };
                const result = await request.post('/edu-app/userlogin', {
                  requestType: 'form',
                  data: {
                    ...forms
                  }
                });

                storage.set(
                  ACCESS_TOKEN,
                  result.data.token_type + ' ' + result.data.access_token
                );

                const userCash = await request.get(
                  '/edu-app/user/getUserInfo',
                  {
                    initRequest: true // 初始化接口
                  }
                );
                setLogin(userCash.data);

                emit('confirm', {
                  loginTag: true
                });
                emit('close');
              } finally {
                //
                btnLoading.value = false;
              }
            }}>
            <span>确认</span>
          </Button>
        </div>
      </div>
    );
  }
});
