import OHeader from '@/components/o-header'
import {
  Button,
  Cell,
  CellGroup,
  Grid,
  GridItem,
  Icon,
  Image,
  Popup,
  showDialog,
  showToast,
  Tag
} from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import styles from './companion-detail.module.less'
import { postMessage } from '@/helpers/native-message'
import iconTeacher from '@common/images/icon_teacher.png'
import iconMessage from '@common/images/icon-message.png'
import iconCallPhone from '@common/images/icon-call-phone.png'
import iconCallMessage from '@common/images/icon-call-message.png'
import OSticky from '@/components/o-sticky'
import request from '@/helpers/request'
import { state as baseState } from '@/state'
import { useRoute, useRouter } from 'vue-router'
import OEmpty from '@/components/o-empty'
import ODialog from '@/components/o-dialog'

export default defineComponent({
  name: 'companion-detail',
  setup(props, { slots, attrs, emit }) {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      showMessage: false,
      detail: {} as any,
      classList: [] as any
    })
    const getDetail = async () => {
      try {
        const query = route.query
        const { data } = await request.post('/api-school/teacher/detail', {
          data: {
            teacherId: query.id,
            schoolId: baseState.user.data.school.id
          }
        })
        state.detail = data
        const subjects = data.subjectName ? data.subjectName.split(',') : []
        state.detail.subjectNames = subjects
      } catch {
        //
      }
    }

    const getClassDetail = async () => {
      try {
        const query = route.query
        const { data } = await request.post('/api-school/classGroup/page', {
          data: {
            teacherId: query.id,
            schoolId: baseState.user.data.school.id,
            page: 1,
            rows: 100
          }
        })
        state.classList = data.rows || []
      } catch {
        //
      }
    }

    const onDetail = async () => {
      if (state.classList.length > 0) {
        router.push({
          path: '/companion-unbind',
          query: { id: route.query.id }
        })
        return
      }

      try {
        showDialog({
          title: '提示',
          message: '是否解除绑定',
          showCancelButton: true
        }).then(async () => {
          await request.post('/api-school/classGroup/handoverTeacher', {
            data: {
              teacherId: route.query.id
            }
          })
          setTimeout(() => {
            showToast('解绑成功')
          }, 100)
          setTimeout(() => {
            router.back()
          }, 1000)
        })
      } catch {
        //
      }
    }

    onMounted(() => {
      getDetail()
      getClassDetail()
    })
    return () => (
      <>
        <OHeader />

        <CellGroup inset class={styles.detailCellGroup}>
          <Cell center class={styles.detailCell}>
            {{
              icon: () => <Image class={styles.img} src={state.detail.avatar || iconTeacher} />,
              title: () => (
                <div class={styles.teacherContent}>
                  <div class={styles.content}>
                    <p class={[styles.name, 'van-ellipsis']}>{state.detail.nickname}</p>
                  </div>
                  <div class={styles.classNum}>
                    <p class={styles.num}>
                      {state.detail.completedCourseScheduleNum || 0}/
                      {state.detail.totalCourseScheduleNum || 0}
                    </p>
                    <p class={styles.numText}>课时</p>
                  </div>
                </div>
              ),
              value: () => (
                <Image
                  class={styles.messageImg}
                  src={iconMessage}
                  onClick={() => (state.showMessage = true)}
                />
              )
            }}
          </Cell>
          {state.detail.subjectNames && state.detail.subjectNames.legnth > 0 && (
            <Cell center>
              {{
                title: () => (
                  <div class={styles.subjectContainer}>
                    <span>声部：</span>
                    <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap' }}>
                      {state.detail.subjectNames &&
                        state.detail.subjectNames.map((subject: any) => (
                          <Tag type="primary" class={styles.tagSubject}>
                            {subject}
                          </Tag>
                        ))}
                    </div>
                  </div>
                )
              }}
            </Cell>
          )}
        </CellGroup>

        <div class={styles.sectionTitle}>
          <i></i>
          基本信息
        </div>

        <CellGroup inset class={[styles.detailCellGroup, styles.sectionCellGroup]}>
          <Cell title="手机号码" value={state.detail.phone}></Cell>
          <Cell
            title="性别"
            value={state.detail.gender == 1 ? '男' : state.detail.gender == 0 ? '女' : ''}
          ></Cell>
          <Cell title="声部" value={state.detail.subjectName}></Cell>
        </CellGroup>

        <div class={styles.sectionTitle}>
          <i></i>
          所在班级
        </div>
        <CellGroup inset class={[styles.detailCellGroup, styles.sectionCellGroup]}>
          {state.classList.map((item: any) => (
            <Cell center class={styles.companionCell}>
              {{
                title: () => (
                  <div class={styles.classInfo}>
                    <p class={styles.className}>{item.name}</p>
                    <p class={styles.musicName}>{item.orchestraName}</p>
                  </div>
                ),
                value: () => (
                  <div class={styles.num}>
                    <p class={styles.nums}>
                      {item.completeCourseScheduleNum}/{item.courseScheduleNum}
                    </p>
                    <p class={styles.numTip}>总课时</p>
                  </div>
                )
              }}
            </Cell>
          ))}
          {state.classList.length <= 0 && <OEmpty btnStatus={false} tips="暂无班级" />}
        </CellGroup>

        {state.detail.id && !state.detail.delFlag && (
          <OSticky position="bottom">
            <div class={['btnGroup']} style={{ paddingLeft: '13px', paddingRight: '13px' }}>
              <Button type="primary" round block onClick={onDetail}>
                解除绑定
              </Button>
            </div>
          </OSticky>
        )}

        <Popup
          v-model:show={state.showMessage}
          position="bottom"
          style={{ background: 'transparent' }}
        >
          <div class={styles.codeContainer}>
            <div class={styles.codeBottom}>
              <Icon
                name="cross"
                size={22}
                class={styles.close}
                color="#666"
                onClick={() => (state.showMessage = false)}
              />

              <h3 class={styles.title}>
                <i></i>联系方式
              </h3>
              <Grid columnNum={2} border={false}>
                <GridItem
                  onClick={() => {
                    postMessage({
                      api: 'joinChatGroup',
                      content: {
                        type: 'single', // single 单人 multi 多人
                        id: state.detail.imUserId
                      }
                    })
                    state.showMessage = false
                  }}
                >
                  {{
                    icon: () => <Image class={styles.shareImg} src={iconCallMessage} />,
                    text: () => <div class={styles.shareText}>发送消息</div>
                  }}
                </GridItem>
                <GridItem
                  onClick={() => {
                    postMessage({
                      api: 'callPhone',
                      content: {
                        phone: state.detail.phone
                      }
                    })
                    state.showMessage = false
                  }}
                >
                  {{
                    icon: () => <Image class={styles.shareImg} src={iconCallPhone} />,
                    text: () => <div class={styles.shareText}>拨打电话</div>
                  }}
                </GridItem>
              </Grid>
            </div>
          </div>
        </Popup>
      </>
    )
  }
})
