<template>
  <ay-container :showSpac="false">
    <ay-sticky relativeTo="#orderList" targetSelector="#top">
      <div class="center pt-spac pb-spac" id="top">
        <uni-datetime-picker
          v-model="data.range"
          type="daterange"
          :clearIcon="false"
          @change="methods.changeDate"
        />
        <button
          type="primary"
          plain="true"
          size="mini"
          class="ml-spac"
          @click="methods.showFilters"
        >
          筛选{{ data.checkCount ? ` · ${data.checkCount}` : '' }}
        </button>
        <!-- <uni-badge type="primary" :text="data.checkCount" absolute="rightTop" :offset="[-3, 3]">
          <uni-icons
            class="ml-spacd2"
            type="settings"
            color=""
            size="24"
            @click="methods.showFilters"
          />
        </uni-badge> -->
      </div>
    </ay-sticky>
    <div class="center justify-between s-fz tags">
      <div
        class="text-center chunk tag"
        v-for="(t, i) in data.tags"
        :key="i"
        :class="{ odd: i % 2 === 0 }"
      >
        <div>{{ t.title }}</div>
        <div>{{ t.unit }}</div>
        <div class="font-bold p-fz">
          {{ func.convert.nullView(t.value, 1) }}
          <!-- <ay-numer :value="func.convert.nullView(t.value, 1)" /> -->
        </div>
      </div>
    </div>
    <div id="orderList">
      <div
        class="chunk childs-fcjb-mbd2"
        v-for="(o, i) in data.orderList"
        :key="i"
        @click="methods.goDetail(o)"
      >
        <div>
          <div class="font-bold p-fz">{{ o.nickName }}</div>
          <div>{{ func.convert.getOrderStatusStr(o.settleStatus) }}</div>
        </div>
        <div>
          <div>加气量（公斤）</div>
          <div>{{ o.gasQty }}</div>
        </div>
        <div>
          <div>结算金额（元）</div>
          <div class="font-bold bs-fz">{{ o.amount }}</div>
        </div>
        <div>
          <div class="gray-color">{{ func.getDate(o.createDate).format() }}</div>
        </div>
      </div>
    </div>
    <uni-drawer
      ref="drawer"
      mode="right"
      :maskClick="true"
      :width="config.common.SystemInfo.windowWidth"
      @change="methods.drawerChange"
    >
      <div class="m-spac">
        <div class="center b-fz mb-spac">
          <div class="font-bold">
            <span>筛选</span>
            <span v-if="checkCount">
              <span>·</span>
              <span class="p-color">{{ checkCount }}</span>
            </span>
          </div>

          <uni-icons
            type="closeempty"
            color=""
            size="24"
            class="abs-right"
            @click="methods.closeFilters"
          />
        </div>
        <div>
          <div>
            <div v-for="(f, i) in filtersView" :key="i" :class="{ 'nmt-spac': f.type === 1 }">
              <div
                class="section"
                :class="{
                  'font-bold': !f.type,
                  'ml-spacd2': f.type === 1,
                  's-fz': f.type === 1,
                }"
              >
                {{ f.label }}
              </div>

              <div class="center justify-between flex-wrap s-fz">
                <div
                  class="center whitespace-nowrap p-spacd2 chunk f-item"
                  :class="{
                    'checked-full': item.checked,
                    isall: item.value === staticData.nullValue,
                  }"
                  v-for="(item, ii) in f.items"
                  :key="ii"
                  @click="methods.filterCheck(f, item)"
                >
                  <!-- <div class="tag-rb" v-if="item.isPerson">个人支付</div> -->
                  {{ item.label }}
                </div>
                <div class="f-item" v-if="f.items.length % 3 === 2"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="btns">
          <button @click="methods.clearFilters">清除</button>
          <button type="primary" @click="methods.saveFilters">确定</button>
        </div>
      </div>
    </uni-drawer>
  </ay-container>
</template>

<script lang="ts" setup>
const staticData = {
  // 缓存筛选条件key名
  fcn: 'filterCheckeds',
  // 全部选项的value值
  nullValue: '-1',
  payTypeGroups: [
    { label: '支付方式', type: 0, hasStatus: ['-1', '10'] },
    { label: '个人支付', type: 1, hasStatus: ['3'] },
    { label: '所属物流', type: 1, hasStatus: ['0', '1', '2'] },
  ],
}
const drawer = ref()
const data = ay.initData({
  /** 确定选中条件数量 */
  checkCount: 0,
  filters: [
    {
      label: '结算状态',
      value: 'settleStatus',
      items: func.convert.getCheckItem(config.common.settleStatus),
    },
    {
      label: '支付方式',
      value: 'payType',
      items: func.convert.getCheckItem(config.common.payTypes),
    },
    {
      label: '交易模式',
      value: 'tradeTypes',
      items: func.convert.getCheckItem(config.common.tradeType),
    },
  ] as any[],
  range: [],
  orderList: [] as 订单详情[],
  tags: [
    {
      field: 'allValue',
      title: '加气总额',
      unit: '（元）',
      value: '',
    },
    {
      field: 'allQty',
      title: '加气总量',
      unit: '（公斤）',
      value: '',
    },
    {
      field: 'count',
      title: '订单总数',
      unit: '（笔）',
      value: '',
    },
    {
      field: 'allPrefer',
      title: '优惠总额',
      unit: '（元）',
      value: '',
    },
  ],
})
const filtersView = computed(() => {
  const rv = [...data.filters]
  const payTypeIndex = rv.findIndex((f) => f.value === 'payType')
  const payTypeItem = rv[payTypeIndex]
  const groups = staticData.payTypeGroups.map((m) => {
    return {
      label: m.label,
      type: m.type,
      items: payTypeItem.items.filter((f) => m.hasStatus.includes(f.value)),
      target: payTypeItem,
    }
  })

  rv.splice(payTypeIndex, 1, ...groups)
  return rv
})
/** 选中的条件 */
const filterCheckeds = computed(() => {
  const fcs: Record<string, string[]> = {}
  data.filters.forEach((f) => {
    const curItems = f.items
      .filter((ff) => ff.checked && ff.value !== staticData.nullValue)
      .map((m) => m.value)
    if (curItems.length) {
      fcs[f.value] = curItems
    }
  })
  return fcs
})
/** 临时选中条件数量 */
const checkCount = computed(() =>
  Object.values(filterCheckeds.value)
    .map((m) => m.length + (m.includes(staticData.nullValue) ? -1 : 0))
    .reduce((a, b) => a + b, 0),
)
const methods = {
  stickChange(e) {
    console.log(e)
  },
  goDetail(od) {
    ay.goPage(config.pages.order_orderDetail, { params: od })
  },
  /** 从缓存 初始化查询条件选中状态 */
  getStoreFilterCheckeds() {
    return uni.getStorageSync(staticData.fcn) || {}
  },
  /** 从缓存 初始化查询条件选中状态 */
  initFiltersCheck() {
    const filterCheckeds: any = methods.getStoreFilterCheckeds()
    if (Object.keys(filterCheckeds).length) {
      data.filters.forEach((f) => {
        if (filterCheckeds[f.value]) {
          f.items.forEach((ff) => {
            ff.checked = filterCheckeds[f.value]?.includes(ff.value)
          })
        } else {
          f.items[0].checked = true
        }
      })
    }
  },
  /** 计算条件选中数量 */
  setCheckCount() {
    const filterCheckeds = methods.getStoreFilterCheckeds()
    if (filterCheckeds) {
      data.checkCount = Object.values<string[]>(filterCheckeds)
        .map((m) => m.length + (m.includes(staticData.nullValue) ? -1 : 0))
        .reduce((a, b) => a + b, 0)
    }
  },
  drawerChange(args) {
    // 打开抽屉初始化条件选择状态
    if (args) {
      methods.initFiltersCheck()
    } else {
      // 关闭抽屉计算选中数量

      methods.setCheckCount()
    }
  },
  saveFilters() {
    // 有选中的条件
    if (Object.keys(filterCheckeds.value).length) {
      uni.setStorageSync(staticData.fcn, filterCheckeds.value)
    } else {
      uni.removeStorageSync(staticData.fcn)
    }
    methods.closeFilters()
    methods.getOrderList()
  },
  clearFilters() {
    data.filters.forEach((f) => {
      f.items.forEach((ff) => {
        ff.checked = false
        if (ff.value === staticData.nullValue) {
          ff.checked = true
        }
      })
    })
  },
  filterCheck(fg, item) {
    // 点击全部
    const realfg = fg.target ? fg.target : fg
    if (item.value === staticData.nullValue) {
      realfg.items.forEach((f) => (f.checked = false))
      item.checked = true
    } else {
      item.checked = !item.checked

      realfg.items[0].checked = false
    }
  },
  getOrderList(cras = store.curPage.getDefAyContainerRefreshArgs()) {
    const paramFilters: Record<string, string> = {}
    const storeFilterCheckeds = methods.getStoreFilterCheckeds()
    Object.keys(storeFilterCheckeds).forEach(
      (f) => (paramFilters[f] = storeFilterCheckeds[f].toString()),
    )
    webapi.strategy
      .get_order_list<{ param: { gasstationId?: string } }>(
        {
          page: cras.page,
          size: cras.size,
          param: {
            startCreateDate: func.getDate(data.range[0]).format(enums.FormatType.YMD000),
            endCreateDate: func.getDate(data.range[1]).format(enums.FormatType.YMDEnd),
            ...paramFilters,
          },
        },
        { showLoading: !cras.isAdd },
      )
      .then((res) => {
        data.tags.forEach((f) => {
          f.value = res[f.field]
        })
        if (cras.isAdd) {
          data.orderList.push(...res.page.records)
        } else {
          data.orderList = res.page.records
        }
      })
  },
  changeDate(e) {
    methods.getOrderList()
  },
  showFilters() {
    drawer.value.open()
  },
  closeFilters() {
    drawer.value.close()
  },
}

ay.entrance((args) => {
  if (args.loadType === enums.LoadType.onLoad) {
    // 初始化日期范围
    const endDate = func.getDate(Date.now())
    data.range = [endDate.add(-30, 'day'), endDate]

    methods.setCheckCount()
  }
  methods.getOrderList(args.cras)
})
</script>

<style lang="scss" scoped>
.abs-right {
  position: absolute;
  right: $p-spac;
}
.f-item {
  box-sizing: border-box;
  width: 31%;
  &.isall {
    background: #fff;
  }
  &.checked {
    color: $p-color;
  }
}
.tags {
  > .tag {
    min-width: 20%;
    max-width: 25%;
    padding: $p-spacd2 0;
    background-color: #d5f8e9;
  }
  .odd {
    background-color: #d5e9fa;
  }
  // > div:nth-child(odd) {
  //   background-color: #d5e9fa;
  // }
  // > div:nth-child(even) {
  //   background-color: #d5f8e9;
  // }
}
</style>
