<template>
  <a-card
    class="w-full relative"
    :bordered="false"
    :body-style="{ padding: '16px' }"
  >
    <a-spin :spinning="spinning">
      <div class="flex leading-7 mb-6">
        <div class="w-[202px] text-gray-500">选择场馆：</div>
        <div class="list">
          <a-radio-group v-model:value="where.merchantId" button-style="solid">
            <a-radio-button
              v-for="(item, index) in category"
              :key="index"
              :value="item.merchantId"
              @click="onMerchant(item)"
              >{{ item.merchantName }}</a-radio-button
            >
          </a-radio-group>
        </div>
      </div>

      <div class="flex leading-7 mb-6">
        <div class="w-[138px] text-gray-500">预定日期：</div>
        <div class="list">
          <a-radio-group v-model:value="where.dateTime" button-style="solid">
            <a-radio-button
              v-for="(item, index) in next7day"
              :key="index"
              :value="item.dateTime"
              >{{ item.label }}</a-radio-button
            >
          </a-radio-group>
        </div>
      </div>
      <!--      <div class="flex leading-7 mb-6">-->
      <!--        <div class="w-[138px] text-gray-500">选择时段：</div>-->
      <!--        <div class="list">-->
      <!--          <a-radio-group v-model:value="where.timePeriod">-->
      <!--            <a-radio-button-->
      <!--              v-for="(item, index) in periods"-->
      <!--              :key="index"-->
      <!--              :value="item.merchantId"-->
      <!--              @click="onMerchant(item)"-->
      <!--              >{{ item.timePeriod }}</a-radio-button-->
      <!--            >-->
      <!--          </a-radio-group>-->
      <!--        </div>-->
      <!--      </div>-->
      <div class="flex leading-7 mb-6">
        <div class="w-[138px] text-gray-500">选择场地：</div>
        <div class="list flex-1">
          <template v-for="(item, index) in periodList" :key="index">
            <div class="time-period leading-7 text-gray-500 mb-2">
              <a-tag color="blue">
                <template #icon>
                  <ClockCircleOutlined />
                </template>
                {{ item.timePeriod }}</a-tag
              >
            </div>
            <div class="field-list flex flex-wrap mb-2">
              <a-button
                class="w-[140px]"
                v-for="(field, fieldIndex) in item.fieldList"
                :key="fieldIndex"
                :disabled="field.sold"
                @click="add(field, item.timePeriod)"
              >
                <div class="flex justify-between">
                  <text>{{ field.fieldName }}</text>
                  <text>￥{{ item.price }}</text>
                </div>
              </a-button>
            </div>
          </template>
          <!--          <div class="h-20 flex items-center m-auto w-full justify-center">-->
          <!--            <a-pagination-->
          <!--              v-model:current="page"-->
          <!--              :total="count"-->
          <!--              show-less-items-->
          <!--              @change="reload"-->
          <!--            />-->
          <!--          </div>-->
        </div>
      </div>
    </a-spin>
    <!-- 编辑弹窗 -->
    <SpecForm
      v-model:visible="showSpecForm"
      :data="current"
      @done="addSpecField"
    />
  </a-card>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import {
    ShoppingCartOutlined,
    ClockCircleOutlined
  } from '@ant-design/icons-vue';
  import SpecForm from './specForm.vue';
  import { useRouter } from 'vue-router';
  import { message } from 'ant-design-vue';
  import { User } from '@/api/system/user/model';
  import { listMerchant } from '@/api/shop/merchant';
  import { getNext7day, getServerTime } from '@/api/layout';
  import { getWeek } from '@/utils/common';
  import { listPeriod, pagePeriod } from '@/api/booking/period';
  import { Period, PeriodParam } from '@/api/booking/period/model';
  import { Merchant } from '@/api/shop/merchant/model';
  import { Field } from '@/api/booking/field/model';
  import { addCashier } from '@/api/shop/cashier';

  const { currentRoute } = useRouter();

  withDefaults(
    defineProps<{
      value?: string;
      placeholder?: string;
      loginUser?: User;
    }>(),
    {
      placeholder: undefined
    }
  );

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'reload'): void;
  }>();

  // 搜索表单
  const where = reactive<PeriodParam>({
    merchantId: undefined,
    merchantName: undefined,
    dateTime: undefined,
    week: undefined,
    half: 0,
    isStatus: 0,
    startTime: undefined,
    timePeriod: undefined
  });

  // 加载中状态
  const spinning = ref<boolean>(true);
  // 当前编辑数据
  const current = ref<Field | null>(null);
  const form = ref<Field>({});
  const category = ref<Merchant[]>([]);
  const periods = ref<Period[]>([]);
  const periodList = ref<Period[] | null>();
  const specs = ref<string>();
  const showSpecForm = ref<boolean>(false);
  const next7day = ref<any[]>();

  /* 打开编辑弹窗 */
  const openSpecForm = (row?: Field) => {
    current.value = row ?? null;
    showSpecForm.value = true;
  };

  const add = (row?: Field, timePeriod?: string) => {
    if (row?.merchantId == 3028) {
      form.value = row;
      form.value.cartNum = 1;
      openSpecForm(row);
      return false;
    }
    console.log(row);
    addCashier({
      goodsId: row?.fieldId,
      name: `${where.merchantName} ${row?.fieldName}`,
      price: row?.price,
      spec: `${where.dateTime} ${getWeek(where.week)} ${timePeriod}`,
      cartNum: 1,
      isNew: true,
      selected: true,
      merchantId: row?.merchantId
    })
      .then((res) => {
        console.log(res);
        emit('reload');
      })
      .catch(() => {
        message.error('该场地已有人预定');
      });
  };

  const addSpecField = () => {
    emit('reload');
  };

  const onMerchant = (e) => {
    where.merchantId = e.merchantId;
    reload();
  };

  const reload = async () => {
    spinning.value = true;
    await getNext7day().then((list) => {
      next7day.value = list.map((d: any, i) => {
        if (where.dateTime == undefined) {
          where.dateTime = d.dateTime;
        }
        if (where.week == undefined) {
          where.week = d.week;
        }
        d.label = `${getWeek(d.week)}(${d.date})`;
        return d;
      });
    });
    await listMerchant({}).then((list) => {
      category.value = list;
      if (where.merchantId == undefined) {
        where.merchantId = list[0].merchantId;
        where.merchantName = list[0].merchantName;
      }
    });
    await getServerTime().then((res) => {
      if (where.merchantId != 3028) {
        where.startTime = res.hourMinute;
      }
    });
    // await pagePeriod({ merchantId: where.merchantId }).then((res) => {
    //   if (res?.list) {
    //     periods.value = res.list;
    //   }
    // });
    await listPeriod(where)
      .then((list) => {
        periodList.value = list;
      })
      .catch(() => {
        periodList.value = [];
      })
      .finally(() => {
        spinning.value = false;
      });
  };

  reload();

  watch(currentRoute, () => {}, { immediate: true });
</script>

<script lang="ts">
  export default {
    name: 'PeriodField'
  };
</script>
