import OEmpty from '@/components/o-empty'
import OFullRefresh from '@/components/o-full-refresh'
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, showToast } from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AddInformation from './modal/add-information'
import styles from './orchestra-information.module.less'

export default defineComponent({
  name: 'orchestra-information',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      addStatus: false,
      isLoading: 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,
            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
      }
    }

    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 {
        console.log(item, 'item')
        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
    }

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

          setTimeout(() => {
            onSearch()
          }, 1100)
        } catch {
          //
        }
      })
    }

    onMounted(() => {
      getList()
    })
    return () => (
      <div class={styles.information}>
        <OSticky
          position="top"
          onGetHeight={(height: any) => {
            state.listState.height = height
          }}
        >
          <div style="background: #f6f8f9; overflow: hidden;">
            <Button
              icon="plus"
              block
              class={styles.addPhone}
              onClick={() => {
                state.selectType = 'add'
                state.addStatus = true
              }}
            >
              添加资讯
            </Button>
          </div>
        </OSticky>

        {state.listState.dataShow ? (
          <OFullRefresh
            v-model:modelValue={state.listState.refreshing}
            onRefresh={onSearch}
            style={{
              minHeight: `calc(100vh - ${state.listState.height}px)`
            }}
          >
            <List
              v-model:loading={state.listState.loading}
              finished={state.listState.finished}
              finishedText=" "
              onLoad={getList}
              immediateCheck={false}
              class={styles.informationGroup}
            >
              {state.list.map((item: any, index: number) => (
                <Cell center class={styles.cell} onClick={() => onDetail(item)}>
                  {{
                    icon: () => <Image src={item.coverImage} class={styles.img} />,
                    title: () => (
                      <div>
                        <div class={[styles.title, 'van-ellipsis']}>{item.title}</div>
                        <div class={[styles.content, 'van-multi-ellipsis--l2']}>{item.memo}</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>
              ))}
            </List>
          </OFullRefresh>
        ) : (
          <OEmpty btnStatus={false} tips="暂无资讯" />
        )}

        <OPopup v-model:modelValue={state.addStatus} style={{ background: '#f8f8f8' }} destroy>
          <AddInformation
            selectType={state.selectType}
            selectItem={state.selectItem}
            onClose={() => (state.addStatus = false)}
            onGetList={onSearch}
          />
        </OPopup>

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