<template>
  <div>
    <div>
      <el-button size="small" @click="handleAddRow">新增时间段</el-button>
      <el-button size="small" @click="handleSave">保存</el-button>
    </div>
    <div></div>
    <vxe-grid v-bind="gridOptions" style="margin-top: 10px"></vxe-grid>
  </div>
</template>

<script setup lang="tsx">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { VxeGrid, VxeColumn, VxeTablePropTypes, VxeTableInstance, VxeGridProps } from 'vxe-table';
import 'vxe-table/lib/style.css';
import { ANY_OBJECT } from '@/types/generic';
import { DialogProp } from '@/components/Dialog/types';
import { TourismProjectController } from '@/api/generated';
import { cloneDeep } from 'lodash';
import dayjs from 'dayjs';

const props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
    id?: ANY_OBJECT;
    saveOnSubmit?: boolean;
    rowData?: ANY_OBJECT;
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    subPage: 0,
    id: undefined,
    saveOnSubmit: true,
    rowData: undefined,
    dialog: undefined,
  },
);

const defaultRowData = {
  dateRange: null,
  adultPrice: null,
  childrenPrice: null,
};

const gridOptions = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  rowConfig: {
    height: 40,
  },
  editConfig: {
    trigger: 'click',
    mode: 'cell',
  },
  columns: [
    {
      type: 'seq',
      width: 80,
      title: '序号',
    },
    {
      field: 'departureDate',
      title: '时间段',
      editRender: {},
      slots: {
        edit({ row }) {
          return (
            <el-date-picker
              v-model={row.dateRange}
              editable={false}
              clearable={false}
              type="daterange"
              value-format="YYYY-MM-DD"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              disabled-date={d => dayjs(d).isBefore(dayjs(), 'day')}
            ></el-date-picker>
          );
        },
        default({ row }) {
          if (!Array.isArray(row.dateRange) || row.dateRange.length < 2) {
            return '-- 至 --';
          }
          return `${row.dateRange[0]} 至 ${row.dateRange[1]}`;
        },
      },
    },
    {
      field: 'adultPrice',
      width: 150,
      editRender: {},
      title: '成人价格（元/人）',
      slots: {
        edit({ row }) {
          return (
            <el-input-number
              v-model={row.adultPrice}
              size="small"
              placeholder="请输入成人价格"
            ></el-input-number>
          );
        },
      },
    },
    {
      field: 'childrenPrice',
      width: 150,
      editRender: {},
      title: '儿童价格（元/人）',
      slots: {
        edit({ row }) {
          return (
            <el-input-number
              v-model={row.childrenPrice}
              size="small"
              placeholder="请输入儿童价格"
            ></el-input-number>
          );
        },
      },
    },
    {
      width: 100,
      title: '操作',
      slots: {
        default({ row, rowIndex }) {
          return (
            <el-button size="small" onClick={() => handleDeleteRow(rowIndex)}>
              删除
            </el-button>
          );
        },
      },
    },
  ],
  data: [],
});

function handleAddRow() {
  gridOptions.data.push(cloneDeep(defaultRowData));
}

function handleDeleteRow(rowIndex) {
  gridOptions.data.splice(rowIndex, 1);
}

async function handleSave() {
  for (let i = 0; i < gridOptions.data.length; i++) {
    let row = gridOptions.data[i];
    if (!Array.isArray(row.dateRange) || row.dateRange.length < 2) {
      ElMessage.warning('时间段不能为空');
      return;
    }
    if (row.adultPrice === null) {
      ElMessage.warning('成人价格不能为空');
      return;
    }
    if (row.childrenPrice === null) {
      ElMessage.warning('儿童价格不能为空');
      return;
    }
  }

  try {
    await TourismProjectController.updateDatePrice({
      projectId: props.id,
      dateRangesPriceVoList: gridOptions.data,
    });
    ElMessage.success('保存成功');
    if (props.dialog) {
      props.dialog.cancel();
    }
  } catch (error) {}
}

onMounted(() => {
  formInit();
});

async function formInit() {
  try {
    const res = await TourismProjectController.viewDatePrice({
      projectId: props.id,
    });
    const data = res.data;
    gridOptions.data = cloneDeep(data);
  } catch (error) {}
}
</script>
