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, onUnmounted, 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'
import OFullRefresh from '@/components/o-full-refresh'
import { format } from 'path'
import OActionSheet from '@/components/o-action-sheet'

export default defineComponent({
  name: 'companion-teacher',
  setup() {
    const router = useRouter()
    const form = reactive({
      showMessage: false,
      showPopover: false,
      oPopover: false,
      subjectList: [{ text: '全部声部', value: 'ALL' }] as any,
      action: [
        {
          name: '解绑',
          id: true
        },
        {
          name: '绑定',
          id: false,
          selected: true
        }
      ],
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false,
        refreshing: false,
        height: 0 // 页面头部高度，为了处理下拉刷新用的
      },
      subjectText: '全部声部',
      statusText: '绑定',
      params: {
        keyword: null,
        delFlag: false,
        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 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
        form.listState.refreshing = 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.refreshing = 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()
    }

    onMounted(async () => {
      getSubjects()
      getList()

      // 处理返回上一页的问题
      window.history.pushState(null, '', document.URL)
      window.addEventListener('popstate', onBack, false)
    })

    const onBack = () => {
      postMessage({ api: 'back' })
    }

    onUnmounted(() => {
      window.removeEventListener('popstate', onBack)
    })
    return () => (
      <div class={!form.listState.dataShow && 'emptyRootContainer'}>
        <OSticky
          position="top"
          onGetHeight={(height: any) => {
            form.listState.height = height
          }}
        >
          <OHeader border={false}>
            {{
              right: () => (
                <Icon
                  name="plus"
                  size={19}
                  onClick={() => {
                    router.push({
                      path: 'save-share-image',
                      query: {
                        type: 'teacher'
                      }
                    })
                  }}
                />
              )
            }}
          </OHeader>
          <OSearch
            placeholder="请输入伴学老师姓名"
            // inputBackground="white"
            // background="#f6f8f9"
            class="searchGroupInput"
            onSearch={(val: any) => {
              form.params.keyword = val
              onSearch()
            }}
          />
          <div class={'searchGroup'}>
            <div
              class={['searchItem', form.showPopover && 'searchItem-active']}
              onClick={() => (form.showPopover = true)}
            >
              <span>{form.subjectText}</span>
              <i class="arrow"></i>
            </div>
            <div
              class={['searchItem', form.oPopover && 'searchItem-active']}
              onClick={() => (form.oPopover = true)}
            >
              <span>{form.statusText}</span>
              <i class="arrow"></i>
            </div>
          </div>
        </OSticky>

        {form.listState.dataShow ? (
          <OFullRefresh
            v-model:modelValue={form.listState.refreshing}
            onRefresh={onSearch}
            style={{
              minHeight: `calc(100vh - ${form.listState.height}px)`
            }}
          >
            <List
              // v-model:loading={form.listState.loading}
              finished={form.listState.finished}
              finishedText=" "
              class={[styles.liveList]}
              onLoad={getList}
              style={{ paddingTop: '12px' }}
              immediateCheck={false}
            >
              {form.list.map((item: any) => (
                <CellGroup inset style={{ marginBottom: '12px' }} onClick={() => onDetail(item)}>
                  <Cell center isLink class={styles.manageCell} clickable={false}>
                    {{
                      icon: () => (
                        <div class={styles.avatarContainer}>
                          <Image
                            class={styles.img}
                            src={item.avatar ? item.avatar : iconTeacher}
                            fit="cover"
                          />
                          {item.delFlag && (
                            <Tag class={styles.avatarType} round color="#F44541" textColor="#fff">
                              解绑
                            </Tag>
                          )}
                        </div>
                      ),
                      title: () => (
                        <div class={styles.teacherContent}>
                          <div class={styles.content}>
                            <p class={[styles.name, 'van-ellipsis']}>{item.nickname}</p>
                          </div>
                        </div>
                      ),
                      value: () => (
                        <div class={styles.teacherContent}>
                          <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>
                      )
                    }}
                  </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}
                                  color="#FFE7DA"
                                  textColor="#F67146"
                                >
                                  {subject}
                                </Tag>
                              ))}
                          </div>
                        </div>
                      )
                    }}
                  </Cell>
                </CellGroup>
              ))}
            </List>
          </OFullRefresh>
        ) : (
          <OEmpty btnStatus={false} tips="暂无伴学老师" />
        )}

        <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>

        <OActionSheet
          v-model:show={form.oPopover}
          actions={form.action}
          onSelect={(val: any) => {
            form.action.forEach((child: any) => {
              child.selected = false
            })
            val.selected = true
            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" class={'popupBottomSearch'}>
          <Picker
            columns={form.subjectList}
            onCancel={() => (form.showPopover = false)}
            onConfirm={(item: any) => onConfirmSubject(item)}
          />
        </Popup>
      </div>
    )
  }
})
