<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '选择场地' : '选择场地'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    {{ form }}
    <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="goodsName">
        {{ form.name }}
      </a-form-item>
      <a-form-item label="价格" name="price">
        <div class="text-red-500">￥{{ formatNumber(form.price) }}</div>
      </a-form-item>
      <a-form-item
        label="购买数量"
        name="cartNum"
        v-if="data.merchantId == 3028"
      >
        <a-input-number
          :min="1"
          :max="9999"
          placeholder="请输入排序号"
          v-model:value="form.cartNum"
          @pressEnter="save"
        />
      </a-form-item>
      <a-form-item v-if="form.specs === 1" label="规格" name="spec">
        <template v-for="(item, index) in form?.goodsSpecValue" :key="index">
          <div class="flex flex-col">
            <span class="font-bold leading-8 text-gray-400">{{
              item.value
            }}</span>
            <a-radio-group v-model:value="form.goodsSpecValue[index].spec">
              <template v-for="(v, i) in item.detail" :key="i">
                <a-radio-button :value="v">{{ v }}</a-radio-button>
              </template>
            </a-radio-group>
          </div>
        </template>
      </a-form-item>
      <a-form-item v-if="data.merchantId == 3028" label="规格" name="spec">
        <template v-for="(item, index) in form?.goodsSpecValue" :key="index">
          <div class="flex flex-col">
            <span class="font-bold leading-8 text-gray-400">{{
              item.value
            }}</span>
            <a-radio-group v-model:value="form.goodsSpecValue[index].spec">
              <template v-for="(v, i) in item.detail" :key="i">
                <a-radio-button :value="v">{{ v }}</a-radio-button>
              </template>
            </a-radio-group>
          </div>
        </template>
      </a-form-item>
    </a-form>
  </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 { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { Cashier } from '@/api/shop/cashier/model';
  import { formatNumber } from 'ele-admin-pro/es';
  import { addCashier, updateCashier } from '@/api/shop/cashier';
  import { Field } from '@/api/booking/field/model';

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

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 类型 0服务 1订单
    type?: number;
    // 修改回显的数据
    data?: Field | null;
  }>();

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

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);
  const images = ref<ItemType[]>([]);
  const spec = ref<string>();

  // 用户信息
  const form = reactive<Cashier>({
    // ID
    id: undefined,
    // 类型 0商城 1外卖
    type: undefined,
    // 唯一标识
    code: undefined,
    // 商品ID
    goodsId: undefined,
    // 商品名称
    goodsName: undefined,
    // 商品封面图
    image: undefined,
    // 商品规格
    spec: undefined,
    // 商品价格
    price: undefined,
    // 商品数量
    cartNum: undefined,
    // 单商品合计
    totalPrice: undefined,
    // 0 = 未购买 1 = 已购买
    isPay: undefined,
    // 是否为立即购买
    isNew: undefined,
    // 是否选中
    selected: undefined,
    // 商户ID
    merchantId: undefined,
    // 用户ID
    userId: undefined,
    // 收银员ID
    cashierId: undefined,
    // 收银单分组ID
    groupId: undefined,
    // 租户id
    tenantId: undefined,
    // 创建时间
    createTime: undefined,
    // 修改时间
    updateTime: undefined,
    // 是否多规格
    specs: undefined,
    // 商品规格数据
    goodsSpecValue: []
  });

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

  // 表单验证规则
  const rules = reactive({});

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

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        if (form.specs === 1) {
          const text = form.goodsSpecValue.map((d) => d.spec).join(',');
          if (text === ',') {
            message.error('请选择规格');
            return false;
          }
          spec.value = text;
        }
        console.log('>>>>>3');
        const formData = {
          ...form,
          goodsId: props.data?.fieldId,
          name: props.data?.fieldName,
          spec: spec.value
        };
        const saveOrUpdate = isUpdate.value ? updateCashier : addCashier;
        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) {
        images.value = [];
        spec.value = '';
        isUpdate.value = !!props.data?.fieldId;
        if (props.type) {
          form.type = props.type;
        }
        if (props.data) {
          assignObject(form, props.data);
          form.name = props.data.fieldName;
          form.cartNum = 1;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
