import ODialog from '@/components/o-dialog'
import OEmpty from '@/components/o-empty'
import OFullRefresh from '@/components/o-full-refresh'
import OHeader from '@/components/o-header'
import OPopup from '@/components/o-popup'
import OSticky from '@/components/o-sticky'
import request from '@/helpers/request'
import { router } from '@/router/routes-common'
import dayjs from 'dayjs'
import { ActionSheet, Button, Cell, Icon, Image, List, showConfirmDialog } from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import styles from './orchestra-information.module.less'

export default defineComponent({
  props: {
    type: {
      type: String,
      default: ''
    },
    headHeight: {
      type: Number,
      default: 0
    }
  },
  emits: ['changeList'],
  name: 'orchestra-information-list',
  setup(props, { emit }) {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      addStatus: false,
      isLoading: false,
      dialogStatus: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false,
        refreshing: false,
        height: 0 // 页面头部高度，为了处理下拉刷新用的
      },
      params: {
        type: 'HOT_CONSULTATION',
        clientType: 'SCHOOL',
        page: 1,
        rows: 20
      },
      oPopover: false,
      selectItem: {} as any,
      selectType: 'add'
    })

    const getList = async () => {
      try {
        if (state.isLoading) return
        state.isLoading = true
        const res = await request.post('/api-school/sysNewsInformation/page', {
          data: {
            ...state.params,
            status: props.type === '1' ? true : false,
            orchestraPhotoAlbumId: route.query.photoId
          }
        })
        state.listState.loading = false
        state.listState.refreshing = false
        const result = res.data || {}
        // 处理重复请求数据
        if (state.list.length > 0 && result.current === 1) {
          return
        }
        const rows = result.rows || []
        state.list = state.list.concat(rows)
        state.listState.finished = result.current >= result.pages
        state.params.page = result.current + 1
        state.listState.dataShow = state.list.length > 0
        state.isLoading = false
      } catch {
        state.listState.dataShow = false
        state.listState.finished = true
        state.listState.refreshing = false
        state.isLoading = false
      }
      emit('changeList')
    }

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

    const onDetail = (item: any) => {
      try {
        if (item.linkUrl) {
          window.location.href = item.linkUrl
        } else {
          router.push({
            path: '/information-detail',
            query: {
              id: item.id
            }
          })
        }
      } catch {
        //
      }
    }

    const onUpdate = async () => {
      // state.selectType = 'update'
      // state.addStatus = true
      router.push({
        name: 'add-information',
        query: {
          id: state.selectItem.id
        }
      })
    }

    const onRemove = async () => {
      showConfirmDialog({
        message: '您确认删除该资讯吗？'
      }).then(async () => {
        try {
          await request.post('/api-school/sysNewsInformation/remove', {
            requestType: 'form',
            data: {
              id: state.selectItem.id
            }
          })
          onSearch()
        } catch {
          //
        }
      })
    }

    onMounted(() => {
      getList()
    })
    return () => (
      <div class={[styles.information]}>
        {props.type === '1' && (
          <Button
            style={{ marginTop: '12px', marginBottom: '12px' }}
            icon="plus"
            block
            class={styles.addPhoneBtn}
            onClick={() => {
              router.push('/add-information')
            }}
          >
            添加资讯
          </Button>
        )}

        {state.listState.dataShow ? (
          <OFullRefresh
            v-model:modelValue={state.listState.refreshing}
            onRefresh={onSearch}
            style={{
              minHeight:
                props.type === '1'
                  ? `calc(100vh - var(--header-height) - var(--van-button-default-height) - 24px)`
                  : `calc(100vh - var(--header-height))`
            }}
          >
            <List
              // v-model:loading={state.listState.loading}
              finished={state.listState.finished}
              finishedText=" "
              onLoad={getList}
              immediateCheck={false}
              class={styles.informationGroup}
            >
              {state.list.map((item: any) => (
                <div class={styles.cellGroup}>
                  <Cell class={styles.cell} onClick={() => onDetail(item)} border={false}>
                    {{
                      icon: () => <Image src={item.coverImage} class={styles.img} fit="cover" />,
                      title: () => (
                        <div class={styles.cellItemContent}>
                          <div class={[styles.title, 'van-multi-ellipsis--l2']}>{item.title}</div>
                          {/* <div class={[styles.content, 'van-multi-ellipsis--l2']}>{item.summary}</div> */}
                          <div
                            style={{
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'space-between'
                            }}
                          >
                            <div class={styles.time}>
                              {item.createTime
                                ? dayjs(item.createTime).format('YYYY年MM月DD日')
                                : ''}
                            </div>
                            <Icon
                              name="ellipsis"
                              size={23}
                              color="#777777"
                              style={{ fontWeight: 'bold' }}
                              onClick={(e: any) => {
                                e.stopPropagation()
                                state.selectItem = item
                                state.oPopover = true
                              }}
                            />
                          </div>
                        </div>
                      )
                    }}
                  </Cell>
                  {!item.status && (
                    <div class={styles.cellReason}>
                      <span>下架原因：</span>
                      {item.reason}
                    </div>
                  )}
                </div>
              ))}
            </List>
          </OFullRefresh>
        ) : (
          <div
            style={{
              minHeight:
                props.type === '1'
                  ? `calc(100vh - var(--header-height) - var(--van-button-default-height) - 24px)`
                  : `calc(100vh - var(--header-height))`
            }}
            class={!state.listState.dataShow && 'emptyRootContainer'}
          >
            <OEmpty btnStatus={false} tips="暂无资讯" />
          </div>
        )}

        <ActionSheet
          teleport={'body'}
          cancelText="取消"
          v-model:show={state.oPopover}
          closeOnClickAction
          actions={[
            { name: '修改', callback: () => onUpdate() },
            {
              name: '删除',
              color: '#F44541',
              callback: () => {
                state.dialogStatus = true
              }
            }
          ]}
        />

        <ODialog
          teleport={'body'}
          v-model:show={state.dialogStatus}
          title="删除资讯"
          message={
            props.type === '1'
              ? '是否删除该资讯？确认后学员端、伴学端将同步删除'
              : '是否删除该资讯？'
          }
          messageAlign="left"
          dialogMarginTop="env(safe-area-inset-top)"
          showCancelButton
          onConfirm={onRemove}
        />
      </div>
    )
  }
})
