<script setup lang="tsx">
import { computed, ref } from 'vue';
import { NButton, NImage } from 'naive-ui';
import dayjs from 'dayjs';
// import { fetchGetStoreList } from '@/service/api/xsb-manage/store-info';
import { fetchList, fetchPriceList } from '@/service/api/goods-center/scenic-goods';
import { commonExport } from '@/utils/common';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import ButtonIcon from '@/components/custom/button-icon.vue';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
const productNo = ref();
let travelDate = dayjs().format('YYYY-MM-DD');
const priceObj = ref<
  Record<
    string,
    {
      settlementPrice: number | string;
      salePrice: number | string;
      ticketAvailability: number | string;
    }
  >
>({});
const columns: NaiveUI.TableColumn<Api.goods.ShopSku>[] = [
  {
    key: 'productNo',
    title: '产品编号',
    align: 'center',
    width: 100
  },
  {
    key: 'productName',
    title: '产品名称',
    align: 'center',
    width: 200
  },
  {
    key: 'mobile',
    title: '产品图片',
    align: 'center',
    width: 100,
    render: row => {
      return <NImage src={row.img} width="100" height="100" />;
    }
  },
  {
    key: 'viewName',
    title: '景区名称',
    align: 'center',
    width: 100
  },
  {
    key: 'receiveTime',
    title: '业务类型',
    align: 'center',
    width: 100,
    render: () => {
      return '景区门票';
    }
  },
  {
    key: 'price',
    title: '价格',
    align: 'center',
    width: 70,
    render: row => {
      return (
        <ButtonIcon
          text
          type="primary"
          onClick={() => handlePrice(row.productNo)}
          icon="material-symbols:calendar-month-rounded"
          tooltip-content="价格"
        />
      );
    }
  },
  {
    key: 'state',
    title: '状态',
    align: 'center',
    width: 100,
    render: row => {
      return row.state == 1 ? '下架' : '上架';
    }
  },
  {
    key: 'updateTime',
    title: '更新时间',
    align: 'center',
    width: 120
  }
];

const [registerTable, { getTableData, getSeachForm, setTableLoading }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        label: '产品编号',
        component: 'NInput',
        field: 'productNo'
      },
      {
        label: '产品名称',
        component: 'NInput',
        field: 'productName'
      },
      {
        label: '景区名称',
        component: 'NInput',
        field: 'viewName'
      },
      {
        label: '状态',
        component: 'NSelect',
        field: 'state',
        componentProps: {
          options: [
            { label: '上架', value: '0' },
            { label: '下架', value: '1' }
          ]
        }
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'skuId',
    title: '领取列表',
    showAddButton: false,
    scrollX: 1800,
    fieldMapToTime: [['createTime', ['receiveStartTime', 'receiveEndTime']]]
  }
});

const [registerModalPrice, { openModal, setModalLoading }] = useModal({
  title: '价格',
  width: 800,
  height: 700,
  showFooter: false
});

const tableData = computed(() => {
  return getTableData();
});

async function handleExport() {
  setTableLoading(true);
  try {
    await commonExport('/smqjh-pms/api/scenery/prod/export', getSeachForm(), '景区产品.xlsx');
  } finally {
    setTableLoading(false);
  }
}

async function handlePrice(no: any) {
  productNo.value = no;
  openModal();
  setModalLoading(true);
  const { data } = await fetchPriceList({ travelDate, productNo: productNo.value });
  console.log(data);
  priceObj.value = {};
  data.ticketPrices.forEach((item: any) => {
    priceObj.value[item.date] = {
      settlementPrice: item.settlementPrice,
      salePrice: item.salePrice,
      ticketAvailability: item.ticketAvailability
    };
  });

  setModalLoading(false);
}

function panelChange(date: any) {
  console.log('panelChange', date.year, date.month);
  travelDate = `${date.year}-${date.month < 10 ? `0${date.month}` : date.month}-01`;
  handlePrice(productNo.value);
}

function getColorName(state: any) {
  if (state == '充足') {
    return { text: 'blue', bg: '#B4E8F4' };
  } else if (state == '紧张') {
    return { text: 'orange', bg: '#F6DFB1' };
  }

  return { text: 'green', bg: '#FCC9C9' };
}

function isDateDisabled(timestamp: any) {
  if (dayjs(timestamp).add(1, 'day').isBefore(dayjs())) {
    return true;
  }
  return false;
}
</script>

<template>
  <LayoutTable>
    <ZTable :columns="columns" :show-table-action="false" :api="fetchList" @register="registerTable">
      <template #prefix="{ loading }">
        <NSpace>
          <NButton size="small" :disabled="tableData.length == 0" :loading="loading" @click="handleExport">
            导出全部
          </NButton>
        </NSpace>
      </template>
    </ZTable>

    <BasicModal @register="registerModalPrice">
      <NCalendar v-slot="{ year, month, date }" :is-date-disabled="isDateDisabled" @panel-change="panelChange">
        <div
          v-if="priceObj[dayjs(`${year}-${month}-${date}`).format('YYYY-MM-DD')]"
          class="h-full flex flex-col justify-between"
        >
          <div class="mt-10px text-12px">
            <div>结算价： {{ priceObj[dayjs(`${year}-${month}-${date}`).format('YYYY-MM-DD')]?.settlementPrice }}</div>
            <div>零售价： {{ priceObj[dayjs(`${year}-${month}-${date}`).format('YYYY-MM-DD')]?.salePrice }}</div>
          </div>
          <div
            class="mb-2px text-center"
            :style="{
              backgroundColor: getColorName(
                priceObj[dayjs(`${year}-${month}-${date}`).format('YYYY-MM-DD')]?.ticketAvailability
              ).bg,
              color: getColorName(priceObj[dayjs(`${year}-${month}-${date}`).format('YYYY-MM-DD')]?.ticketAvailability)
                .text
            }"
          >
            {{ priceObj[dayjs(`${year}-${month}-${date}`).format('YYYY-MM-DD')]?.ticketAvailability }}
          </div>
        </div>
      </NCalendar>
    </BasicModal>
  </LayoutTable>
</template>

<style scoped></style>
