<script setup lang="ts">
import { reactive, ref, computed, inject, watch, onMounted } from 'vue';
import { VXETable, VxeGridInstance, VxeGridProps, VxeGridEvents } from 'vxe-table';
import dayjs from 'dayjs';
import isoWeek from 'dayjs/plugin/isoWeek';
import { useRouter, useRoute } from 'vue-router';
import {
  getDayTaskData,
  postCreateDayData,
  postCreateWeekData,
  postCreateMonthData, getMonthTaskData, getWeekTaskData, postUpdateDayData
} from '/@/views/reportManage/dataCenter/api';

dayjs.extend(isoWeek);

const router = useRouter();
const route = useRoute();
const dateType = <string>route.query.dateType;

//日期选择
const dailyEntryTime = ref(dayjs().format('YYYY-MM-DD'));
const dailyTime = ref(dayjs().subtract(1, 'day').format('YYYY-MM-DD'));

const weeklyEntryTime = ref<string | null>(null);
const weeklySalesTime = ref<string | null>(null);
const weeklyAdTime = ref<string | null>(null);

const entryStartDate = ref<string>('');
const entryEndDate = ref<string>('');
const salesStartDate = ref<string>('');
const salesEndDate = ref<string>('');
const adStartDate = ref<string>('');
const adEndDate = ref<string>('');

const monthlyEntryTime = ref(null);
const startDate = ref(null);
const endDate = ref(null);

const shortcuts = [
  {
    text: '今天',
    value: new Date(),
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: '最近七天',
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
      return date;
    },
  },
];

function handleDayChange(event) {
  const $dailyEntryTime = dailyEntryTime.value;
  if ($dailyEntryTime) {
    const dailyTimeValue = new Date($dailyEntryTime);
    dailyTimeValue.setDate(dailyTimeValue.getDate());
    dailyTime.value = dailyTimeValue.toISOString().split('T')[0];
  } else {
    dailyTime.value = '';
  }
}

const handleWeekChange = () => {
  if (weeklyEntryTime.value) {
    entryStartDate.value = dayjs(weeklyEntryTime.value).startOf('isoWeek').format('YYYY-MM-DD');
    entryEndDate.value = dayjs(weeklyEntryTime.value).endOf('isoWeek').format('YYYY-MM-DD');

    weeklySalesTime.value = weeklyEntryTime.value;
    salesStartDate.value = entryStartDate.value;
    salesEndDate.value = entryEndDate.value;

    const adDate = dayjs(weeklyEntryTime.value).subtract(7, 'day');
    weeklyAdTime.value = adDate.format('YYYY-WW');
    adStartDate.value = adDate.startOf('isoWeek').format('YYYY-MM-DD');
    adEndDate.value = adDate.endOf('isoWeek').format('YYYY-MM-DD');
  }
};

const entryFormat = computed(() => `${entryStartDate.value} to ${entryEndDate.value}`);
const salesFormat = computed(() => `${salesStartDate.value} to ${salesEndDate.value}`);
const adFormat = computed(() => `${adStartDate.value} to ${adEndDate.value}`);

watch(weeklyEntryTime, handleWeekChange
);

const handleMonthChange = (value) => {
  if (value) {
    const date = new Date(value);
    const year = date.getFullYear();
    const month = date.getMonth() + 1; // getMonth() 返回值为 0-11，需要加 1
    const lastDay = new Date(year, month, 0).getDate();
    startDate.value = `${year}-${String(month).padStart(2, '0')}-01`;
    endDate.value = `${year}-${String(month).padStart(2, '0')}-${lastDay}`;
  } else {
    startDate.value = null;
    endDate.value = null;
  }
};
const monthlyEntryFormat = computed(() => `${startDate.value} to ${endDate.value}`);

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now();
};

//表格
const dayColumns = [
  {field: 'task', title: 'ID', width: 50},
  {field: 'platformNumber', title: '平台编号'},
  {field: 'platformName', title: '平台名称'},
  {field: 'country', title: '国家'},
  {field: 'brandName', title: '品牌'},

  {field: 'sales', title: '销售额', editRender: {}, slots: {edit: 'sales_edit'}},
  {field: 'ad_sales', title: '广告销售额', editRender: {}, slots: {edit: 'ad_sales_edit'}},
  {field: 'ad_cost', title: '广告花费', editRender: {}, slots: {edit: 'ad_cost_edit'}},
  {title: '操作', width: 300, slots: {default: 'operate'}},
];
const weekColumns = [
  {field: 'task', title: 'ID', width: 50},
  {field: 'platformNumber', title: '平台编号',},
  {field: 'platformName', title: '平台名称'},
  {field: 'country', title: '国家'},
  {field: 'brandName', title: '品牌'},

  {field: 'sales', title: '销售额',editRender: {}, slots: {edit: 'sales_edit'}},
  {field: 'total_sales_current_monthly', title: '当月累计销售额',editRender: {}, slots: {edit: 'total_sales_current_monthly_edit'}},
  {field: 'ad_sales', title: '广告销售额',editRender: {},slots: {edit: 'ad_sales_edit'}},
  { field: 'ad_cost', title: '广告花费', editRender: {}, slots: { edit: 'ad_cost_edit' } },
  { field: 'impression', title: '广告曝光', editRender: {}, slots: { edit: 'impression_edit' } },
  { field: 'ad_click', title: '广告点击', editRender: {}, slots: { edit: 'ad_click_edit' } },
  { field: 'ad_order', title: '广告订单', editRender: {}, slots: { edit: 'ad_order_edit' } },
  { field: 'money_by_amazon', title: 'Amazon回款金额', editRender: {}, slots: { edit: 'money_by_amazon_edit' } },
  { field: 'money_by_other', title: 'Other回款金额', editRender: {}, slots: { edit: 'money_by_other_edit' } },
  { field: 'session', title: '流量', editRender: {}, slots: { edit: 'session_edit' } },
  { field: 'order', title: '转化', editRender: {}, slots: { edit: 'order_edit' } },
  { field: 'availableSalesDay', title: '当前存货可售天', editRender: {}, slots: { edit: 'availableSalesDay_edit' } },
  { field: 'intransitInventory', title: '当前在途库存', editRender: {}, slots: { edit: 'intransitInventory_edit' } },
  { field: 'overseasStorage', title: '当前海外仓库存', editRender: {}, slots: { edit: 'overseasStorage_edit' } },
  { field: 'refundRate', title: '最近90天平台退货率', editRender: {}, slots: { edit: 'refundRate_edit' } },
  {title: '操作', width: 150, slots: {default: 'operate'}},
];
const monthColumns = [
  {type: 'seq', title: 'ID', width: 50},
  {field: 'platformName', title: '平台名称'},
  {field: 'country', title: '国家'},
  {field: 'brandName', title: '品牌'},

  {field: 'sales', title: '销售额',editRender: {}, slots: {edit: 'sales_edit'}},
  {field: 'ad_sales', title: '广告销售额',editRender: {},slots: {edit: 'ad_sales_edit'}},
  { field: 'ad_cost', title: '广告花费', editRender: {}, slots: { edit: 'ad_cost_edit' } },
  { field: 'impression', title: '广告曝光', editRender: {}, slots: { edit: 'impression_edit' } },
  { field: 'ad_click', title: '广告点击', editRender: {}, slots: { edit: 'ad_click_edit' } },
  { field: 'ad_order', title: '广告订单', editRender: {}, slots: { edit: 'ad_order_edit' } },
  {title: '操作', width: 300, slots: {default: 'operate'}},
];

const dayData = [];
const weekData = [];
const monthData = [];

interface RowVO {
  task: number;
  sales: number;
  ad_sales: number;
  ad_cost: number;

  total_sales_current_monthly: number;
  impression: number;
  ad_click: number;
  ad_order: number;
  money_by_amazon: number;
  money_by_other: number;
  session: string;
  order: string;
  availableSalesDay: number;
  intransitInventory: number;
  overseasStorage: number;
  refundRate: number;
}

const xGrid = ref<VxeGridInstance<RowVO>>();
const gridOptions = reactive({
  border: false,
  height: 600,
  align: null,
  round: true,
  loading: false,
  columnConfig: {
    resizable: true
  },
  pagerConfig: {
    enabled: true,
    total: 20,
    currentPage: 1,
    pageSize: 10,
    pageSizes: [10, 20, 30],
  },
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true,
  },
  day: {
    columns: dayColumns,
    data: dayData
  },
  week: {
    columns: weekColumns,
    data: weekData
  },
  month: {
    columns: monthColumns,
    data: monthData
  }
});

function fetchCurrentTaskData() {
  if (dateType === 'day') {
    fetchDayTaskData();
  } else if (dateType === 'week') {
    fetchWeekTaskData();
  } else if (dateType === 'month') {
    fetchMonthTaskData();
  }
}

const gridEvents = {
  pageChange({currentPage, pageSize}) {
    if (gridOptions.pagerConfig) {
      gridOptions.pagerConfig.currentPage = currentPage;
      gridOptions.pagerConfig.pageSize = pageSize;
    }
    fetchCurrentTaskData();
  }
};

// 获取表格数据
async function fetchTaskData(apiFunction) {
  try {
    const resp = await apiFunction({
      page: gridOptions.pagerConfig.currentPage,
      limit: gridOptions.pagerConfig.pageSize,
    });
    gridOptions[dateType].data = resp.data;
    console.log('resp', resp.data);
    gridOptions.pagerConfig.total = resp.total;
  } catch (error) {
    console.error('Error fetching task data:', error);
  }
}
async function fetchDayTaskData() {
  await fetchTaskData(getDayTaskData);
}

async function fetchWeekTaskData() {
  await fetchTaskData(getWeekTaskData);
}

async function fetchMonthTaskData() {
  await fetchTaskData(getMonthTaskData);
}
//创建日数据
async function createDayData(row: RowVO) {
  const body = {
    sales: row.sales,
    ad_sales: row.ad_sales,
    ad_cost: row.ad_cost,
    enter_datetime: dailyEntryTime.value,
    data_datetime: dailyTime.value,
    task: row.task,
  };
  try {
    const resp = await postCreateDayData(body);
    if (resp.code === 2000) {
      await fetchDayTaskData();
      await VXETable.modal.message({
        content: '创建成功',
        status: 'success',
      });
    }
  } catch (e) {
    await VXETable.modal.message({content: '创建失败',});
  }
}
//创建周数据
async function createWeekData(row: RowVO) {
  const body = {
    sales:row.sales,
    total_sales_current_monthly:row.total_sales_current_monthly,
    ad_sales:row.ad_sales,
    ad_cost:row.ad_cost,
    impression:row.impression,
    ad_click:row.ad_click,
    ad_order:row.ad_order,
    money_by_amazon:row.money_by_amazon,
    money_by_other:row.money_by_other,
    session:row.session,
    order:row.order,
    availableSalesDay:row.availableSalesDay,
    intransitInventory:row.intransitInventory,
    overseasStorage:row.overseasStorage,
    refundRate:row.refundRate,
    sales_start_time:salesStartDate.value,
    sales_end_time:salesEndDate.value,
    ad_start_time:adStartDate.value,
    ad_end_time:adEndDate.value,
    enter_start_datetime:entryStartDate.value,
    enter_end_datetime:entryEndDate.value,
    task:row.task,
  };
  try {
    const resp = await postCreateWeekData(body);
    console.log(body);
    if (resp.code === 2000) {
      await fetchWeekTaskData();
      await VXETable.modal.message({
        content: '创建成功',
        status: 'success',
      });
    }
  } catch (e) {
    await VXETable.modal.message({content: '创建失败',});
  }
}
//创建月数据
async function createMonthData(row: RowVO) {
  const body = {
    sales:row.sales,
    ad_sales:row.ad_sales,
    ad_cost:row.ad_cost,
    impression:row.impression,
    ad_click:row.ad_click,
    ad_order:row.ad_order,
    data_start_time:startDate.value,
    data_end_time:endDate.value,
    enter_start_time:startDate.value,
    enter_end_time:endDate.value,
    task:row.task,
  };
  try {
    const resp = await postCreateMonthData(body);
    console.log(body);
    if (resp.code === 2000) {
      await fetchMonthTaskData();
      await VXETable.modal.message({
        content: '创建成功',
        status: 'success',
      });
    }
  } catch (e) {
    await VXETable.modal.message({content: '创建失败',});
  }
}

const saveRowEvent = async (row: RowVO) => {
  const $grid = xGrid.value;
  if ($grid) {
    await $grid.clearEdit();
    gridOptions.loading = true;
    if (dateType === 'day') {
      await createDayData(row);
    } else if (dateType === 'week') {
      await createWeekData(row);
    } else if (dateType === 'month') {
      await createMonthData(row);
    }
    // 模拟异步保存
    setTimeout(() => {
      gridOptions.loading = false;
    }, 300);
  }
};

// 更新日数据
async function updateDayData(row: RowVO) {
  const $grid = xGrid.value;
  if ($grid) {
    const body = {
    id: row.id,
    sales: row.sales,
    ad_sales: row.ad_sales,
    ad_cost: row.ad_cost,
    enter_datetime: dailyEntryTime.value,
    data_datetime: dailyTime.value,
    task: row.task,
  };
    console.log(body);
  try {
    const resp = await postUpdateDayData(body);
    if (resp.code === 2000) {
      await fetchDayTaskData();
      await VXETable.modal.message({
        content: '更新成功',
        status: 'success',
      });
    }
  } catch (error) {
    console.log('error:', error);
  }
  }
}
//更新周数据
async function updateWeekData(row: RowVO) {
}
//更新月数据
async function updateMonthData(row: RowVO) {
}
const editRowEvent = async (row: any) => {
  const $grid = xGrid.value;
  if ($grid) {
    await $grid.clearEdit();
    await updateDayData(row)
    gridOptions.loading = true;
    // 模拟异步保存
    setTimeout(() => {
      gridOptions.loading = false;
    }, 300);
  }
};

const currentGridOptions = computed(() => {
  const selectedGridOptions = gridOptions[dateType] || gridOptions['day'];
  return {
    ...gridOptions,
    ...selectedGridOptions
  };
});

onMounted(() => {
  fetchCurrentTaskData();
});
</script>

<template>
  <div>
    <el-card class="custom-card-style flex gap-1.5 justify-between my-1.5 mx-2">
      <div class="demo-date-picker" v-if="dateType === 'day'">
        <div class="block">
          <span class="demonstration">日录入数据时间:</span>
          <el-date-picker
              v-model="dailyEntryTime"
              type="Date"
              :disabled-date="disabledDate"
              :shortcuts="shortcuts"
              @change="handleDayChange"
          />
        </div>
        <div class="block">
          <span class="demonstration">日数据时间:</span>
          <el-date-picker
              v-model="dailyTime"
              type="Date"
              :shortcuts="shortcuts"
              disabled
          />
        </div>
      </div>
      <div class="demo-date-picker" v-if="dateType === 'week'">
        <div class="block">
          <span class="demonstration">周录入数据时间:</span>
          <el-date-picker
              v-model="weeklyEntryTime"
              type="week"
              :format="entryFormat"
              placeholder="选择一周"
              :disabled-date="disabledDate"
              @change="handleWeekChange
"
          />
        </div>
        <div class="block">
          <span class="demonstration">周销售数据时间:</span>
          <el-date-picker
              v-model="weeklySalesTime"
              type="week"
              :format="salesFormat"
              placeholder="选择一周"
              disabled
          />
        </div>
        <div class="block">
          <span class="demonstration">周广告数据时间:</span>
          <el-date-picker
              v-model="weeklyAdTime"
              type="week"
              :format="adFormat"
              placeholder="选择一周"
              disabled
          />
        </div>
      </div>
      <div class="demo-date-picker" v-if="dateType === 'month'">
        <div class="block">
          <span class="demonstration">月录入数据时间:</span>
          <el-date-picker
              v-model="monthlyEntryTime"
              type="month"
              :format="monthlyEntryFormat"
              placeholder="选择月份"
              @change="handleMonthChange"
              :disabled-date="disabledDate"
          />
        </div>
      </div>
    </el-card>
  </div>
  <el-card class="mx-2">
    <div style="position: relative">
      <vxe-grid ref="xGrid" v-bind="currentGridOptions" v-on="gridEvents">
        <template #operate="{ row }">
          <vxe-button content="创建" @click="saveRowEvent(row)"></vxe-button>
          <vxe-button content="更新" @click="editRowEvent(row)"></vxe-button>
        </template>
        <template #sales_edit="{ row }">
          <vxe-input v-model="row.sales"></vxe-input>
        </template>
        <template #ad_sales_edit="{ row }">
          <vxe-input v-model="row.ad_sales"></vxe-input>
        </template>
        <template #ad_cost_edit="{ row }">
          <vxe-input v-model="row.ad_cost"></vxe-input>
        </template>
        <template #total_sales_current_monthly_edit="{ row }">
          <vxe-input v-model="row.total_sales_current_monthly"></vxe-input>
        </template>
        <template #impression_edit="{ row }">
          <vxe-input v-model="row.impression"></vxe-input>
        </template>
        <template #ad_click_edit="{ row }">
          <vxe-input v-model="row.ad_click"></vxe-input>
        </template>
        <template #ad_order_edit="{ row }">
          <vxe-input v-model="row.ad_order"></vxe-input>
        </template>
        <template #money_by_amazon_edit="{ row }">
          <vxe-input v-model="row.money_by_amazon"></vxe-input>
        </template>
        <template #money_by_other_edit="{ row }">
          <vxe-input v-model="row.money_by_other"></vxe-input>
        </template>
        <template #session_edit="{ row }">
          <vxe-input v-model="row.session"></vxe-input>
        </template>
        <template #order_edit="{ row }">
          <vxe-input v-model="row.order"></vxe-input>
        </template>
        <template #availableSalesDay_edit="{ row }">
          <vxe-input v-model="row.availableSalesDay"></vxe-input>
        </template>
        <template #intransitInventory_edit="{ row }">
          <vxe-input v-model="row.intransitInventory"></vxe-input>
        </template>
        <template #overseasStorage_edit="{ row }">
          <vxe-input v-model="row.overseasStorage"></vxe-input>
        </template>
        <template #refundRate_edit="{ row }">
          <vxe-input v-model="row.refundRate"></vxe-input>
        </template>

      </vxe-grid>
    </div>
  </el-card>
</template>

<style scoped>
.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin: 10px;
}

.vxe-grid {
  border-radius: 10px;
  margin-bottom: 10px;
}
</style>
