import {
  Button,
  Cell,
  SwipeCell,
  Tag,
  Image,
  Icon,
  showConfirmDialog,
  List,
  showToast
} from 'vant';
import { defineComponent, onMounted, onUpdated, reactive } from 'vue';
import styles from './index.module.less';
import iconEdit from '../images/icon-edit.png';
import OSticky from '@/components/m-sticky';
import OEmpty from '@/components/m-empty';
import { useRouter } from 'vue-router';
import request from '@/helpers/request';

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') {
        showConfirmDialog({
          title: '确定删除吗？',
          confirmButtonColor: '#FF8021'
        }).then(async () => {
          await request.post('/edu-app/userReceiveAddress/remove', {
            requestType: 'form',
            data: {
              id: item.id
            }
          });

          setTimeout(() => {
            showToast('删除成功');
          }, 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.post('/edu-app/userReceiveAddress/page', {
          data: {
            ...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.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 onDetails = (item: any) => {
      sessionStorage.setItem('addressDetails', JSON.stringify(item));
      router.back();
    };

    onMounted(() => {
      getList();
    });
    return () => (
      <div class={[styles.shopAddress]}>
        {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.provinceName}
                            {item.cityName}
                            {item.regionName}
                            {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'
            }}>
            <OEmpty description="暂无收货地址" />
          </div>
        )}
        <OSticky position="bottom">
          <div class={'btnGroup'}>
            <Button
              type="primary"
              round
              block
              class={styles.createBtn}
              onClick={() => {
                router.push('addressOperation');
              }}>
              新建收货地址
            </Button>
          </div>
        </OSticky>
      </div>
    );
  }
});
