<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :title="isUpdate ? '编辑时段' : '添加时段'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-spin :spinning="loading">
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="
          styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }
        "
        :wrapper-col="
          styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
        "
      >
        <a-form-item label="时段" name="timePeriod">
          <a-time-picker
            v-model:value="form.timePeriod1"
            format="HH:mm"
            valueFormat="HH:mm"
          />
          -
          <a-time-picker
            v-model:value="form.timePeriod2"
            format="HH:mm"
            valueFormat="HH:mm"
          />
        </a-form-item>
        <a-form-item label="价格" name="price">
          <a-input-number
            allow-clear
            placeholder="请输入价格"
            style="width: 200px"
            v-model:value="form.price"
          />
        </a-form-item>
        <!--      <a-form-item label="每日不同价格" name="prices">-->
        <!--        <a-input-number-->
        <!--          allow-clear-->
        <!--          style="width: 200px"-->
        <!--          placeholder="请输入每日不同价格"-->
        <!--          v-model:value="form.prices"-->
        <!--        />-->
        <!--      </a-form-item>-->
        <a-form-item label="半场价格" name="halfPrice">
          <a-input-number
            allow-clear
            style="width: 200px"
            placeholder="请输入半场价格"
            v-model:value="form.halfPrice"
          />
        </a-form-item>
        <!--      <a-form-item label="每日不同半场价格" name="halfPrices">-->
        <!--        <a-input-number-->
        <!--          allow-clear-->
        <!--          style="width: 200px"-->
        <!--          placeholder="请输入每日不同半场价格"-->
        <!--          v-model:value="form.halfPrices"-->
        <!--        />-->
        <!--      </a-form-item>-->
        <a-form-item label="儿童价" name="childrenPrice">
          <a-input-number
            allow-clear
            style="width: 200px"
            placeholder="请输入儿童价"
            v-model:value="form.childrenPrice"
          />
        </a-form-item>
        <a-form-item label="星期选择" name="week">
          <a-select
            v-model:value="form.week"
            :options="weekOptions"
            mode="tags"
            placeholder="星期选择"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="排序" name="sortNumber">
          <a-input-number
            :min="0"
            :max="9999"
            class="ele-fluid"
            placeholder="请输入排序号"
            v-model:value="form.sortNumber"
          />
        </a-form-item>
        <a-form-item label="是否关闭" name="isStatus">
          <a-radio-group v-model:value="form.isStatus">
            <a-radio :value="1">开启</a-radio>
            <a-radio :value="2">关闭</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="是否免费" name="isFree">
          <a-radio-group v-model:value="form.isFree">
            <a-radio :value="1">免费</a-radio>
            <a-radio :value="2">收费</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="备注" name="comments">
          <a-textarea
            :rows="4"
            :maxlength="200"
            placeholder="请输入描述"
            v-model:value="form.comments"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject } from 'ele-admin-pro';
  import { addPeriod, updatePeriod } from '@/api/booking/period';
  import { Period } from '@/api/booking/period/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { FormInstance, RuleObject } from 'ant-design-vue/es/form';
  import { Merchant } from '@/api/shop/merchant/model';

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 商户ID
    merchantId?: number;
    // 商户信息
    merchant?: Merchant | null;
    // 修改回显的数据
    data?: Period | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);
  const weekOptions = ref([
    { label: '星期一', value: '1' },
    { label: '星期二', value: '2' },
    { label: '星期三', value: '3' },
    { label: '星期四', value: '4' },
    { label: '星期五', value: '5' },
    { label: '星期六', value: '6' },
    { label: '星期日', value: '7' }
  ]);

  // 用户信息
  const form = reactive<Period>({
    periodId: undefined,
    timePeriod: '',
    timePeriod1: undefined,
    timePeriod2: undefined,
    price: 0,
    prices: '',
    halfPrice: 0,
    halfPrices: '',
    childrenPrice: 0,
    week: undefined,
    sortNumber: 0,
    merchantId: 0,
    isStatus: 1,
    isFree: 2,
    startTime: '',
    comments: '',
    status: 0
  });

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    period: [
      {
        required: true,
        type: 'string',
        message: '请填写时段,如红色、L码、远峰蓝、原色钛金属等',
        trigger: 'blur'
      }
    ],
    timePeriod: [
      {
        required: true,
        type: 'string',
        message: '请选择时段',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: string) => {
          if (form.timePeriod1 == undefined || form.timePeriod2 == undefined) {
            return Promise.reject('请选择时段' + value);
          }
          return Promise.resolve();
        }
      }
    ]
  });

  const { resetFields } = useForm(form, rules);

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        form.merchantId = props.merchantId;
        if (!form.merchantId || form.merchantId == 0) {
          return;
        }
        form.week = JSON.stringify(form.week);
        form.prices = JSON.stringify(form.prices);
        form.halfPrices = JSON.stringify(form.halfPrices);
        form.timePeriod = `${form.timePeriod1} - ${form.timePeriod2}`;
        form.startTime = `${form.timePeriod1?.replace(':', '')}`;
        const formData = {
          ...form
        };
        const saveOrUpdate = isUpdate.value ? updatePeriod : addPeriod;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignObject(form, props.data);
          if (props.data.timePeriod) {
            const strings = props.data.timePeriod.split('-');
            form.timePeriod1 = strings[0].replace(' ', '');
            form.timePeriod2 = strings[1].replace(' ', '');
          }
          if (props.data.week) {
            form.week = JSON.parse(props.data.week);
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>
