<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="900"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑分销订单记录' : '添加分销订单记录'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <!-- 订单基本信息 -->
      <a-divider orientation="left">
        <span style="color: #1890ff; font-weight: 600;">订单基本信息</span>
      </a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="买家用户ID" name="userId">
            <a-input-number
              :min="1"
              placeholder="请输入买家用户ID"
              v-model:value="form.userId"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="订单ID" name="orderId">
            <a-input-number
              :min="1"
              placeholder="请输入订单ID"
              v-model:value="form.orderId"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="订单总金额" name="orderPrice">
        <a-input-number
          :min="0"
          :precision="2"
          placeholder="请输入订单总金额（不含运费）"
          v-model:value="form.orderPrice"
          style="width: 300px"
        >
          <template #addonAfter>元</template>
        </a-input-number>
      </a-form-item>

      <!-- 分销商信息 -->
      <a-divider orientation="left">
        <span style="color: #1890ff; font-weight: 600;">分销商信息</span>
      </a-divider>

      <!-- 一级分销商 -->
      <div class="dealer-section">
        <h4 class="dealer-title">
          <a-tag color="red">一级分销商</a-tag>
        </h4>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户ID" name="firstUserId">
              <a-input-number
                :min="1"
                placeholder="请输入一级分销商用户ID"
                v-model:value="form.firstUserId"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="分销佣金" name="firstMoney">
              <a-input-number
                :min="0"
                :precision="2"
                placeholder="请输入一级分销佣金"
                v-model:value="form.firstMoney"
                style="width: 100%"
              >
                <template #addonAfter>元</template>
              </a-input-number>
            </a-form-item>
          </a-col>
        </a-row>
      </div>

      <!-- 二级分销商 -->
      <div class="dealer-section">
        <h4 class="dealer-title">
          <a-tag color="orange">二级分销商</a-tag>
        </h4>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户ID" name="secondUserId">
              <a-input-number
                :min="1"
                placeholder="请输入二级分销商用户ID"
                v-model:value="form.secondUserId"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="分销佣金" name="secondMoney">
              <a-input-number
                :min="0"
                :precision="2"
                placeholder="请输入二级分销佣金"
                v-model:value="form.secondMoney"
                style="width: 100%"
              >
                <template #addonAfter>元</template>
              </a-input-number>
            </a-form-item>
          </a-col>
        </a-row>
      </div>

      <!-- 三级分销商 -->
      <div class="dealer-section">
        <h4 class="dealer-title">
          <a-tag color="gold">三级分销商</a-tag>
        </h4>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户ID" name="thirdUserId">
              <a-input-number
                :min="1"
                placeholder="请输入三级分销商用户ID"
                v-model:value="form.thirdUserId"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="分销佣金" name="thirdMoney">
              <a-input-number
                :min="0"
                :precision="2"
                placeholder="请输入三级分销佣金"
                v-model:value="form.thirdMoney"
                style="width: 100%"
              >
                <template #addonAfter>元</template>
              </a-input-number>
            </a-form-item>
          </a-col>
        </a-row>
      </div>

      <!-- 状态信息 -->
      <a-divider orientation="left">
        <span style="color: #1890ff; font-weight: 600;">状态信息</span>
      </a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="订单状态" name="isInvalid">
            <a-radio-group v-model:value="form.isInvalid">
              <a-radio :value="0">有效</a-radio>
              <a-radio :value="1">失效</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="结算状态" name="isSettled">
            <a-radio-group v-model:value="form.isSettled">
              <a-radio :value="0">未结算</a-radio>
              <a-radio :value="1">已结算</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="结算时间" name="settleTime" v-if="form.isSettled === 1">
        <a-date-picker
          v-model:value="form.settleTime"
          show-time
          placeholder="请选择结算时间"
          style="width: 300px"
        />
      </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 dayjs from 'dayjs';
  import { assignObject, uuid } from 'ele-admin-pro';
  import { addShopDealerOrder, updateShopDealerOrder } from '@/api/shop/shopDealerOrder';
  import { ShopDealerOrder } from '@/api/shop/shopDealerOrder/model';
  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 { FileRecord } from '@/api/system/file/model';

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

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: ShopDealerOrder | 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 form = reactive<ShopDealerOrder>({
    id: undefined,
    userId: undefined,
    orderId: undefined,
    orderPrice: undefined,
    firstUserId: undefined,
    secondUserId: undefined,
    thirdUserId: undefined,
    firstMoney: undefined,
    secondMoney: undefined,
    thirdMoney: undefined,
    isInvalid: 0,
    isSettled: 0,
    settleTime: undefined,
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined
  });

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

  // 表单验证规则
  const rules = reactive({
    userId: [
      {
        required: true,
        message: '请输入买家用户ID',
        trigger: 'blur'
      }
    ],
    orderId: [
      {
        required: true,
        message: '请输入订单ID',
        trigger: 'blur'
      }
    ],
    orderPrice: [
      {
        required: true,
        message: '请输入订单总金额',
        trigger: 'blur'
      }
    ],
    firstUserId: [
      {
        validator: (rule: any, value: any) => {
          if (form.firstMoney && !value) {
            return Promise.reject('设置了一级佣金必须填写一级分销商用户ID');
          }
          return Promise.resolve();
        },
        trigger: 'blur'
      }
    ],
    firstMoney: [
      {
        validator: (rule: any, value: any) => {
          if (form.firstUserId && !value) {
            return Promise.reject('设置了一级分销商必须填写一级佣金');
          }
          return Promise.resolve();
        },
        trigger: 'blur'
      }
    ],
    secondUserId: [
      {
        validator: (rule: any, value: any) => {
          if (form.secondMoney && !value) {
            return Promise.reject('设置了二级佣金必须填写二级分销商用户ID');
          }
          return Promise.resolve();
        },
        trigger: 'blur'
      }
    ],
    secondMoney: [
      {
        validator: (rule: any, value: any) => {
          if (form.secondUserId && !value) {
            return Promise.reject('设置了二级分销商必须填写二级佣金');
          }
          return Promise.resolve();
        },
        trigger: 'blur'
      }
    ],
    thirdUserId: [
      {
        validator: (rule: any, value: any) => {
          if (form.thirdMoney && !value) {
            return Promise.reject('设置了三级佣金必须填写三级分销商用户ID');
          }
          return Promise.resolve();
        },
        trigger: 'blur'
      }
    ],
    thirdMoney: [
      {
        validator: (rule: any, value: any) => {
          if (form.thirdUserId && !value) {
            return Promise.reject('设置了三级分销商必须填写三级佣金');
          }
          return Promise.resolve();
        },
        trigger: 'blur'
      }
    ]
  });



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

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form
        };
        const saveOrUpdate = isUpdate.value ? updateShopDealerOrder : addShopDealerOrder;
        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.settleTime) {
            form.settleTime = dayjs(props.data.settleTime);
          }
          isUpdate.value = true;
        } else {
          // 重置为默认值
          Object.assign(form, {
            id: undefined,
            userId: undefined,
            orderId: undefined,
            orderPrice: undefined,
            firstUserId: undefined,
            secondUserId: undefined,
            thirdUserId: undefined,
            firstMoney: undefined,
            secondMoney: undefined,
            thirdMoney: undefined,
            isInvalid: 0,
            isSettled: 0,
            settleTime: undefined
          });
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>

<style lang="less" scoped>
.dealer-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
  border-left: 3px solid #1890ff;

  .dealer-title {
    margin: 0 0 16px 0;
    font-size: 14px;
    font-weight: 600;
    color: #333;

    .ant-tag {
      margin-right: 8px;
    }
  }
}

:deep(.ant-divider-horizontal.ant-divider-with-text-left) {
  margin: 24px 0 16px 0;

  .ant-divider-inner-text {
    padding: 0 16px 0 0;
  }
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-input-number) {
  width: 100%;
}
</style>
