<template>
  <view class="w-body">
    <w-public />
    <w-navbar left-back fixed :title="edit ? '地址管理' : '地址选择'"></w-navbar>
    <mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback">
      <view
        v-for="item in list" 
        :key="item.id" 
        class="item-group"
        :class="{defaulted:item.defaulted}" 
        :hover-class="edit?'':'w-hover'" 
        style="line-height: 1.8; color: var(--w-text-light);" 
        @click="if(!edit){proxy.getOpenerEventChannel().emit('select',item);$w.back()}"
        >
        <view>
          <view style="font-size: .8em; color: var(--w-text-light-2); display: flex; align-items: center;">
            <view style="margin-right: .5em; flex-shrink: 1;"><up-tag :text="item.tags" plain size="mini" type="warning"></up-tag></view>
            {{ item.addrName }}
          </view>
          <view>{{ item.addrDesc }}</view>
          <view style="display: grid; grid-template-columns: 3fr 2fr;">
            <view style="font-size: .8em; color: var(--w-text-light-1);">{{ item.tel }} {{ item.name }} {{
              item.gender ? '先生' : '女士' }}</view>

            <view class="w-links" v-if="edit">
              <view v-if="!item.defaulted" style="color: var(--w-primary);" @click="setDefault(item)">设为默认</view>
              <view style="color: var(--w-info);" @click="update(item)">修改</view>
              <view style="color: var(--w-error);" @click="del(item)">删除</view>
            </view>
          </view>
        </view>

      </view>
    </mescroll-body>
    <w-fab v-if="edit" style="font-size: 1.5rem;" @click="form.open = true; form.add = true; form.data = {};" />
    <u-popup :show="form.open" closeable mode="bottom" @close="form.open = false">
      <view class="w-address-form">
        <view class="title w-flex">{{ form.add ? '新增地址' : '修改地址' }}</view>
        <view class="w-item">
          <view>姓名:</view>
          <view style="width: 10em;"><u-input fontSize="1em" placeholder="请输入姓名" maxlength="16" v-model="form.data.name"
              border="bottom"></u-input></view>
          <view class="w-radio w-flex" :class="{ selected: form.data.gender == true }"
            @click="form.data.gender = true;">先生
          </view>
          <view class="w-radio w-flex" :class="{ selected: form.data.gender == false }"
            @click="form.data.gender = false;">女士
          </view>
        </view>
        <view class="w-item">
          <view>联系电话:</view>
          <view style="width: 12em;"><u-input fontSize="1em" v-model="form.data.tel" maxlength="18"
              placeholder="请输入联系电话" border="bottom"></u-input></view>
        </view>
        <view class="w-item">
          <view>所在地区:</view>
          <view @click="proxy.$refs.citySelectRef.open(form.data.addrCode)" style="flex-grow: 2; padding: .5em;"
            hover-class="w-hover-before">{{ form.data.addrName || '请选择' }}</view>
        </view>

        <view class="w-item">
          <view>详细地址:</view>
          <view style="flex-grow: 2;"><u-input fontSize="1em" v-model="form.data.addrDesc" maxlength="64"
              placeholder="请输入详细地址" border="bottom"></u-input></view>
        </view>


        <view class="w-item">
          <view>标签:</view>
          <view style="width: 5em;"><u-input fontSize=".9em" v-model="form.data.tags" maxlength="5" placeholder="标签"
              border="bottom"></u-input></view>
          <view class="w-tag" :class="{ selected: form.data.tags == '家' }" @click="form.data.tags = '家'">家</view>
          <view class="w-tag" :class="{ selected: form.data.tags == '公司' }" @click="form.data.tags = '公司'">公司</view>
        </view>

        <view class="w-btn" style="margin-top: 1em;" @click="doSubmit" hover-class="w-hover">确定</view>
      </view>
    </u-popup>
    <c-city-select ref="citySelectRef" level="4"
      @change="form.data.addrCode = $event.code; form.data.addrName = $event.name" />
  </view>
</template>

<script setup>
import { onLoad, onShow, onReady } from '@dcloudio/uni-app'
import { ref, getCurrentInstance } from 'vue'
import * as addressApi from '@/api/address/address'

const { proxy } = getCurrentInstance();

const edit = ref(false);


onLoad(async (e) => {
  edit.value = e.edit != 'false'
})

const form = ref({
  open: false,
  add: true,
  data: {}
})

const params = ref({})

const doSearch = () => {
  getMescroll().resetUpScroll()
  getMescroll().scrollTo(0, 0)
}

onShow(async () => {
  await proxy.$nextTick()
  doSearch()
})

//分页逻辑
import { onPageScroll, onReachBottom } from '@dcloudio/uni-app'
import useMescroll from "@/uni_modules/mescroll-uni/hooks/useMescroll.js"
const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom)

const list = ref([]);
// 上拉加载的回调: 其中num:当前页 从1开始, size:每页数据条数,默认10
const upCallback = (mescroll) => {
  params.value.current = mescroll.num;
  params.value.size = mescroll.size;
  addressApi.page(params.value).then(res => {
    console.log(res);
    const curPageData = res.records || [] // 当前页数据

    if (mescroll.num == 1) list.value = []; // 第一页需手动制空列表
    list.value = list.value.concat(curPageData); //追加新数据

    mescroll.endBySize(curPageData.length, res.total); // 请求成功, 结束加载
  }).catch(() => {
    mescroll.endErr(); // 请求失败, 结束加载
  })
}

const doSubmit = async () => {
  let fn = form.value.add ? addressApi.add : addressApi.update
  let r = await fn(form.value.data)
  form.value.open = false
  doSearch()
}

const update = (item) => {
  form.value.add = false
  form.value.data = item
  form.value.open = true
}

const setDefault = async (item) => {
  await addressApi.updateDefaulted(item.id)
  doSearch()
}

const del = async(item) => {
  await uni.$w.confirm('确定要删除吗？')
  await addressApi.del(item.id)
  doSearch()
}

</script>

<style lang="scss" scoped>
.w-body {
  --navbar-height: 44px;
  background-color: var(--w-bg);
  font-size: .8rem;
  min-height: 100vh;

  .defaulted::after {
    content: '默 认';
    position: absolute;
    top: 0;
    right: 0;
    font-size: .7em;
    background-color: var(--w-success-dark-1);
    background-clip: padding-box;
    color: var(--w-bg-light);
    padding: .1em 1.5em;
    border-style: dashed;
    border-width: 0 .15em;
    border-color: var(--w-success-dark-1);
    transform: translateX(2em) rotate(45deg) scale(.7);
  }

  .w-links {
    display: flex;
    justify-content: flex-end;
    font-size: .8em;

    &>view {
      margin-left: .5em;
    }

  }

  .w-address-form {
    padding: .8em;

    .title {
      font-size: 1.2em;
      font-weight: bold;
      height: 2em;
    }

    .w-item {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      margin-top: .8em;

      &>view {
        margin-right: .5em;

        &:first-child {
          flex-shrink: 1;
          width: 5em;
          text-align: right;
        }
      }



      .w-tag {
        font-size: .8em;
        border: solid 1px #0003;
        padding: .4em .9em;
        border-radius: 10em;
        min-width: 3em;
        text-align: center;

        &.selected {
          background-color: var(--w-main-dark);
          color: var(--w-bg-light);
        }
      }
    }
  }
}
</style>
