import {
  Button,
  Cell,
  SwipeCell,
  Tag,
  Image,
  Icon,
  List,
  Toast,
  Dialog,
  Empty
} from 'vant'
import { defineComponent, onMounted, onUpdated, reactive } from 'vue'
import styles from './index.module.less'
import iconEdit from '../images/icon-edit.png'
import { useRouter } from 'vue-router'
import request from '@/helpers/request'
import ColSticky from '@/components/col-sticky'
import ColResult from '@/components/col-result'
import ColHeader from '@/components/col-header'

export default defineComponent({
  name: 'shop-address',
  setup() {
    const router = useRouter()
    const form = reactive({
      isClick: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        page: 1,
        rows: 20
      },
      selectItem: {} // 选择的地址
    })
    const onBeforeClose = ({ position }: any, item: any) => {
      if (position === 'right') {
        Dialog.confirm({
          title: '提示',
          message: '确定删除吗？',
          confirmButtonColor: '#FF8021'
        }).then(async () => {
          // on confirm
          await request.post(
            '/api-mall-portal/member/address/delete/' + item.id,
            {
              requestType: 'form',
              data: {
                // id: item.id
              }
            }
          )

          setTimeout(() => {
            Toast('删除成功')
          }, 100)

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

    const onUpdate = (item: any) => {
      router.push({
        path: '/addressOperation',
        query: {
          id: item.id
        }
      })
    }

    // api-student/userReceiveAddress/page
    const getList = async () => {
      try {
        if (form.isClick) return
        form.isClick = true
        const res = await request.get('/api-mall-portal/member/address/list', {
          params: {
            ...form.params
          }
        })
        form.listState.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (form.list.length > 0 && result.current === 1) {
          return
        }
        form.list = form.list.concat(result || [])
        form.listState.finished = true //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 onDetails = (item: any) => {
      sessionStorage.setItem('addressDetails', JSON.stringify(item))
      router.back()
    }

    onMounted(() => {
      getList()
    })
    return () => (
      <div class={[styles.shopAddress]}>
        <ColHeader />
        {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) => (
              <SwipeCell
                class={styles.swipeCell}
                beforeClose={(args: any) => onBeforeClose(args, item)}
              >
                {{
                  default: () => (
                    <Cell center onClick={() => onDetails(item)}>
                      {{
                        title: () => (
                          <div class={styles.title}>
                            <span class={styles.name}>{item.name}</span>
                            <span class={styles.phone}>{item.phoneNumber}</span>
                            {item.defaultStatus && (
                              <Tag plain color="#FF8057">
                                默认
                              </Tag>
                            )}
                          </div>
                        ),
                        label: () => (
                          <div class={styles.content}>
                            {item.province}
                            {item.city}
                            {item.region}
                            {item.detailAddress}
                          </div>
                        ),
                        'right-icon': () => (
                          <Icon
                            name={iconEdit}
                            size="18"
                            onClick={(e: Event) => {
                              e.stopPropagation()
                              onUpdate(item)
                            }}
                          />
                        )
                      }}
                    </Cell>
                  ),
                  right: () => <Button type="danger">删除</Button>
                }}
              </SwipeCell>
            ))}
          </List>
        ) : (
          <div
            style={{
              'min-height': 'calc(100vh - var(--header-height))',
              display: 'flex',
              'align-items': 'center'
            }}
          >
            <ColResult type="empty" tips="暂无收货地址" btnStatus={false} />
          </div>
        )}
        <ColSticky position="bottom">
          <div class={'btnGroup'}>
            <Button
              type="primary"
              round
              block
              class={styles.createBtn}
              onClick={() => {
                router.push('/addressOperation')
              }}
            >
              新建收货地址
            </Button>
          </div>
        </ColSticky>
      </div>
    )
  }
})
