import OHeader from '@/components/o-header'
import OQrcode from '@/components/o-qrcode'
import OSearch from '@/components/o-search'
import OSticky from '@/components/o-sticky'
import {
  ActionSheet,
  Cell,
  CellGroup,
  closeToast,
  Grid,
  GridItem,
  Icon,
  Image,
  List,
  Picker,
  Popup,
  showFailToast,
  showLoadingToast,
  showSuccessToast,
  showToast,
  Tag
} from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import styles from './index.module.less'
import iconSaveImage from '@/school/orchestra/images/icon-save-image.png'
import iconWechat from '@/school/orchestra/images/icon-wechat.png'
import iconCallPhone from '@common/images/icon-call-phone.png'
import iconCallMessage from '@common/images/icon-call-message.png'
import iconTeacher from '@common/images/icon_teacher.png'
import iconMessage from '@common/images/icon-message.png'
import { useRouter } from 'vue-router'
import request from '@/helpers/request'
import { state } from '@/state'
import OEmpty from '@/components/o-empty'
import { manageTeacherType } from '@/constant'
import { postMessage, promisefiyPostMessage } from '@/helpers/native-message'
import html2canvas from 'html2canvas'
import { forms } from '../train-planning/create'

export default defineComponent({
  name: 'companion-teacher',
  setup() {
    const router = useRouter()
    const form = reactive({
      showMessage: false,
      showPopover: false,
      oPopover: false,
      showQrcode: false,
      schoolName: null,
      schoolId: null,
      url: null as any,
      subjectList: [{ text: '全部声部', value: 'ALL' }] as any,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      subjectText: '全部声部',
      statusText: '状态',
      params: {
        keyword: null,
        delFlag: null,
        subjectId: null,
        page: 1,
        rows: 20
      },
      selectItem: {} as any
    })

    const getSubjects = async () => {
      try {
        const { data } = await request.post('/api-school/subjectBasicConfig/page', {
          data: {
            page: 1,
            rows: 50
          }
        })
        // console.log(data, 'data')
        const temp = data.rows || []
        temp.forEach((row: any) => {
          form.subjectList.push({
            text: row.subjectName,
            value: row.subjectId
          })
        })
      } catch {
        //
      }
    }

    // 获取当前用户所在的学校
    const getDetail = async (id: string | number) => {
      try {
        const res = await request.get('/api-school/schoolStaff/detail/' + id)
        form.schoolName = res.data.schoolName
        form.schoolId = res.data.schoolId
        form.url =
          location.origin +
          '/orchestra-school/#/companion-teacher-register?id=' +
          res.data.schoolId +
          '&name=' +
          res.data.schoolName

        console.log(form.url)
      } catch {
        //
      }
    }

    const getList = async () => {
      try {
        const res = await request.post('/api-school/teacher/page', {
          data: {
            ...form.params,
            schoolId: state.user.data.school.id
          }
        })
        form.listState.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (form.list.length > 0 && result.current === 1) {
          return
        }
        const rows = result.rows || []
        rows.forEach((item: any) => {
          item.subjectNames = item.subjectName ? item.subjectName.split(',') : []
        })
        form.list = form.list.concat(rows)
        form.listState.finished = result.current >= result.pages
        form.params.page = result.current + 1
        form.listState.dataShow = form.list.length > 0
      } catch {
        form.listState.dataShow = false
        form.listState.finished = true
      }
    }

    const onSearch = () => {
      form.params.page = 1
      form.list = []
      form.listState.dataShow = true // 判断是否有数据
      form.listState.loading = false
      form.listState.finished = false
      getList()
    }

    // 详情
    const onDetail = (item: any) => {
      router.push({
        path: '/companion-teacher-detail',
        query: {
          id: item.id
        }
      })
    }

    // 选择声部
    const onConfirmSubject = (item: any) => {
      form.subjectText = item.selectedOptions[0].text
      form.params.subjectId =
        item.selectedOptions[0].value === 'ALL' ? null : item.selectedOptions[0].value
      form.showPopover = false
      onSearch()
    }

    const imgs = reactive({
      saveLoading: false,
      image: null as any,
      shareLoading: false
    })
    const onSaveImg = async () => {
      // 判断是否在保存中...
      if (imgs.saveLoading) {
        return
      }
      imgs.saveLoading = true
      // 判断是否已经生成图片
      if (imgs.image) {
        saveImg()
      } else {
        const container: any = document.getElementById(`preview-container`)
        html2canvas(container, {
          allowTaint: true,
          useCORS: true,
          backgroundColor: null
        })
          .then(async (canvas) => {
            const url = canvas.toDataURL('image/png')
            imgs.image = url
            saveImg()
          })
          .catch(() => {
            closeToast()
            imgs.saveLoading = false
          })
      }
    }
    const onShare = () => {
      if (imgs.shareLoading) {
        return
      }
      imgs.shareLoading = true
      if (imgs.image) {
        openShare()
      } else {
        const container: any = document.getElementById(`preview-container`)
        html2canvas(container, {
          allowTaint: true,
          useCORS: true,
          backgroundColor: null
        })
          .then(async (canvas) => {
            const url = canvas.toDataURL('image/png')
            imgs.image = url
            openShare()
          })
          .catch(() => {
            closeToast()
            imgs.shareLoading = false
          })
      }
    }
    const openShare = () => {
      const image = imgs.image
      setTimeout(() => {
        imgs.shareLoading = false
      }, 100)
      if (image) {
        postMessage(
          {
            api: 'shareTripartite',
            content: {
              title: '',
              desc: '',
              image,
              video: '',
              type: 'image',
              // button: ['copy']
              shareType: 'wechat'
            }
          },
          (res: any) => {
            if (res && res.content) {
              showToast(res.content.message || (res.content.status ? '分享成功' : '分享失败'))
            }
          }
        )
      }
    }
    const saveImg = async () => {
      showLoadingToast({ message: '图片生成中...', forbidClick: true })
      setTimeout(() => {
        imgs.saveLoading = false
      }, 100)
      const res = await promisefiyPostMessage({
        api: 'savePicture',
        content: {
          base64: imgs.image
        }
      })
      if (res?.content?.status === 'success') {
        showSuccessToast('保存成功')
        form.showQrcode = false
      } else {
        showFailToast('保存失败')
      }
    }

    onMounted(() => {
      getDetail(state.user.data.id)
      getSubjects()
      getList()
    })
    return () => (
      <>
        <OSticky position="top">
          <OHeader border={false}>
            {{
              right: () => <Icon name="plus" size={19} onClick={() => (form.showQrcode = true)} />
            }}
          </OHeader>
          <OSearch
            placeholder="请输入伴学老师姓名"
            inputBackground="white"
            background="#f6f8f9"
            onSearch={(val: any) => {
              form.params.keyword = val
              onSearch()
            }}
          />
          <div style={{ padding: '12px 13px 16px', background: '#F8F8F8' }}>
            <div class={styles.searchBand} onClick={() => (form.showPopover = true)}>
              {form.subjectText} <Icon name={form.showPopover ? 'arrow-up' : 'arrow-down'} />
            </div>

            <div
              class={styles.searchBand}
              style="margin-left: 16px"
              onClick={() => (form.oPopover = true)}
            >
              {form.statusText} <Icon name={form.oPopover ? 'arrow-up' : 'arrow-down'} />
            </div>
          </div>
        </OSticky>

        {form.listState.dataShow ? (
          <List
            v-model:loading={form.listState.loading}
            finished={form.listState.finished}
            finishedText=" "
            class={[styles.liveList]}
            onLoad={getList}
            immediateCheck={false}
          >
            {form.list.map((item: any) => (
              <CellGroup inset style={{ marginBottom: '12px' }} onClick={() => onDetail(item)}>
                <Cell center isLink class={styles.manageCell}>
                  {{
                    icon: () => (
                      <Image class={styles.img} src={item.avatar ? item.avatar : iconTeacher} />
                    ),
                    title: () => (
                      <div class={styles.teacherContent}>
                        <div class={styles.content}>
                          <p class={[styles.name, 'van-ellipsis']}>{item.nickname}</p>
                        </div>
                        <div class={styles.classNum}>
                          <p class={styles.num}>
                            {item.completedCourseScheduleNum || 0}/
                            {item.totalCourseScheduleNum || 0}
                          </p>
                          <p class={styles.numText}>课时</p>
                        </div>
                        <div
                          class={styles.message}
                          onClick={(e: any) => {
                            e.stopPropagation()
                            e.preventDefault()
                            form.showMessage = true
                            form.selectItem = item
                          }}
                        >
                          <Image class={styles.messageImg} src={iconMessage} />
                        </div>
                      </div>
                    ),
                    value: () => (
                      <span class={[styles.status, item.delFlag ? styles.frozen : '']}>
                        {!item.delFlag ? '绑定' : '解绑'}
                      </span>
                    )
                  }}
                </Cell>
                <Cell center>
                  {{
                    title: () => (
                      <div class={styles.subjectContainer}>
                        <span>声部：</span>
                        <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap' }}>
                          {item.subjectNames &&
                            item.subjectNames.length > 0 &&
                            item.subjectNames.map((subject: any) => (
                              <Tag type="primary" class={styles.tagSubject}>
                                {subject}
                              </Tag>
                            ))}
                        </div>
                      </div>
                    )
                  }}
                </Cell>
              </CellGroup>
            ))}
          </List>
        ) : (
          <OEmpty btnStatus={false} tips="暂无伴学老师" />
        )}

        <Popup
          v-model:show={form.showQrcode}
          position="bottom"
          style={{ background: 'transparent' }}
        >
          <div class={styles.codeContainer}>
            <div class={styles.codeImg} id="preview-container">
              <div class={styles.codeContent}>
                <h2 class={[styles.codeTitle, 'van-ellipsis']}>{form.schoolName}</h2>
                <div class={styles.codeName}>邀请您成为乐团伴学老师</div>

                <div class={styles.codeQr}>
                  <OQrcode text={form.url} size={'100%'} />
                </div>
                <div style={{ textAlign: 'center' }}>
                  <span class={styles.codeBtnText}>扫描上方二维码完成资料填写</span>
                </div>
                <div class={styles.codeTips}>二维码将在两小时后失效，请及时登记</div>
              </div>
            </div>
            <div class={styles.codeBottom}>
              <Icon
                name="cross"
                size={22}
                class={styles.close}
                color="#666"
                onClick={() => (form.showQrcode = false)}
              />

              <h3 class={styles.title}>
                <i></i>分享方式
              </h3>
              <Grid columnNum={2} border={false}>
                <GridItem onClick={onSaveImg}>
                  {{
                    icon: () => <Image class={styles.shareImg} src={iconSaveImage} />,
                    text: () => <div class={styles.shareText}>保存图片</div>
                  }}
                </GridItem>
                <GridItem onClick={onShare}>
                  {{
                    icon: () => <Image class={styles.shareImg} src={iconWechat} />,
                    text: () => <div class={styles.shareText}>微信</div>
                  }}
                </GridItem>
              </Grid>
            </div>
          </div>
        </Popup>

        <Popup
          v-model:show={form.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={() => (form.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: form.selectItem.imUserId
                      }
                    })
                    form.showMessage = false
                  }}
                >
                  {{
                    icon: () => <Image class={styles.shareImg} src={iconCallMessage} />,
                    text: () => <div class={styles.shareText}>发送消息</div>
                  }}
                </GridItem>
                <GridItem
                  onClick={() => {
                    postMessage({
                      api: 'callPhone',
                      content: {
                        phone: form.selectItem.phone
                      }
                    })
                    form.showMessage = false
                  }}
                >
                  {{
                    icon: () => <Image class={styles.shareImg} src={iconCallPhone} />,
                    text: () => <div class={styles.shareText}>拨打电话</div>
                  }}
                </GridItem>
              </Grid>
            </div>
          </div>
        </Popup>

        <ActionSheet
          v-model:show={form.oPopover}
          cancelText="取消"
          actions={
            [
              { name: '全部', id: 'ALL' },
              { name: '解绑', id: true },
              { name: '绑定', id: false }
              // { name: '注销', id: 'CANCEL' },
              // { name: '冻结', id: 'LOCKED' },
              // { name: '正常', id: 'ACTIVATION' }
            ] as any
          }
          onSelect={(val: any) => {
            form.statusText = val.name
            form.params.delFlag = val.id === 'ALL' ? null : val.id
            form.oPopover = false
            onSearch()
          }}
        />

        <Popup v-model:show={form.showPopover} round position="bottom">
          <Picker
            columns={form.subjectList}
            onCancel={() => (form.showPopover = false)}
            onConfirm={(item: any) => onConfirmSubject(item)}
          />
        </Popup>
      </>
    )
  }
})
