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,
  closeToast,
  Grid,
  GridItem,
  Icon,
  Image,
  List,
  Popup,
  showFailToast,
  showLoadingToast,
  showSuccessToast,
  showToast
} 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 iconTeacher from '@common/images/icon_teacher.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 html2canvas from 'html2canvas'
import { promisefiyPostMessage, postMessage } from '@/helpers/native-message'

export default defineComponent({
  name: 'companion-teacher',
  setup() {
    const router = useRouter()
    const form = reactive({
      oPopover: false,
      showQrcode: false,
      schoolName: null,
      schoolId: null,
      url: null as any,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      statusText: '状态',
      params: {
        keyword: null,
        status: null,
        page: 1,
        rows: 20
      },
      isClick: false
    })

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

    const getList = async () => {
      try {
        if (form.isClick) return
        form.isClick = true
        const res = await request.post('/api-school/schoolStaff/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
        }
        form.list = form.list.concat(result.rows || [])
        form.listState.finished = result.current >= result.pages
        form.params.page = result.current + 1
        form.listState.dataShow = form.list.length > 0
        form.isClick = false
      } catch {
        form.listState.dataShow = false
        form.listState.finished = true
        form.isClick = false
      }
    }

    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: '/manage-teacher-detail',
        query: {
          id: item.id
        }
      })
    }

    const imgs = reactive({
      saveLoading: false,
      image: null as any,
      shareLoading: 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 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 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(() => {
      // console.log(state.user.data.id, '1212')
      getDetail(state.user.data.id)

      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) => {
              console.log(val)
              form.params.keyword = val
              onSearch()
            }}
            v-slots={{
              left: () => (
                <div
                  class={styles.searchBand}
                  style={{ marginRight: '13px' }}
                  onClick={() => (form.oPopover = true)}
                >
                  {form.statusText} <Icon name={form.oPopover ? 'arrow-up' : 'arrow-down'} />
                </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) => (
              <Cell center isLink class={styles.manageCell} onClick={() => onDetail(item)}>
                {{
                  icon: () => (
                    <Image class={styles.img} src={item.avatar ? item.avatar : iconTeacher} />
                  ),
                  title: () => (
                    <div class={styles.content}>
                      <p class={[styles.name, 'van-ellipsis']}>{item.nickname}</p>
                      <p class={styles.phone}>{item.phone}</p>
                    </div>
                  ),
                  value: () => (
                    <span class={[styles.status, item.status === 'LOCKED' ? styles.frozen : '']}>
                      {manageTeacherType[item.status]}
                    </span>
                  )
                }}
              </Cell>
            ))}
          </List>
        ) : (
          <OEmpty btnStatus={false} tips="暂无管理老师" />
        )}

        <Popup
          v-model:show={form.showQrcode}
          position="bottom"
          style={{ background: 'transparent' }}
          // safeAreaInsetBottom={true}
        >
          <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>

        {/* <van-action-sheet v-model:show="show" :actions="actions" @select="onSelect" /> */}

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