<!-- 编辑弹窗 -->
<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-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="flowType">
            <a-select
              v-model:value="form.flowType"
              placeholder="请选择资金流动类型"
            >
              <a-select-option :value="10">
                <div class="flow-type-option">
                  <a-tag color="success">佣金收入</a-tag>
                  <span>获得分销佣金</span>
                </div>
              </a-select-option>
              <a-select-option :value="20">
                <div class="flow-type-option">
                  <a-tag color="warning">提现支出</a-tag>
                  <span>申请提现</span>
                </div>
              </a-select-option>
              <a-select-option :value="30">
                <div class="flow-type-option">
                  <a-tag color="error">转账支出</a-tag>
                  <span>转账给他人</span>
                </div>
              </a-select-option>
              <a-select-option :value="40">
                <div class="flow-type-option">
                  <a-tag color="processing">转账收入</a-tag>
                  <span>收到转账</span>
                </div>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="金额" name="money">
            <a-input-number
              :min="0"
              :precision="2"
              placeholder="请输入金额"
              v-model:value="form.money"
              style="width: 100%"
            >
              <template #addonAfter>元</template>
            </a-input-number>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="流动描述" name="comments">
        <a-textarea
          v-model:value="form.comments"
          placeholder="请输入资金流动描述"
          :rows="3"
          :maxlength="200"
          show-count
        />
      </a-form-item>

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

      <a-form-item
        label="对方用户ID"
        name="toUserId"
        v-if="form.flowType === 30 || form.flowType === 40"
      >
        <a-input-number
          :min="1"
          placeholder="请输入对方用户ID"
          v-model:value="form.toUserId"
          style="width: 300px"
        />
        <span style="margin-left: 12px; color: #999; font-size: 12px">
          转账相关操作需要填写对方用户ID
        </span>
      </a-form-item>

      <!-- 金额预览 -->
      <div class="amount-preview" v-if="form.money && form.flowType">
        <a-alert
          :type="getAmountAlertType()"
          :message="getAmountPreviewText()"
          show-icon
          style="margin-top: 16px"
        />
      </div>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, uuid } from 'ele-admin-pro';
  import {
    addShopDealerCapital,
    updateShopDealerCapital
  } from '@/api/shop/shopDealerCapital';
  import { ShopDealerCapital } from '@/api/shop/shopDealerCapital/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?: ShopDealerCapital | 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<ShopDealerCapital>({
    id: undefined,
    userId: undefined,
    orderId: undefined,
    flowType: undefined,
    money: undefined,
    comments: '',
    toUserId: 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'
      }
    ],
    flowType: [
      {
        required: true,
        message: '请选择资金流动类型',
        trigger: 'change'
      }
    ],
    money: [
      {
        required: true,
        message: '请输入金额',
        trigger: 'blur'
      },
      {
        validator: (rule: any, value: any) => {
          if (value && value <= 0) {
            return Promise.reject('金额必须大于0');
          }
          return Promise.resolve();
        },
        trigger: 'blur'
      }
    ],
    comments: [
      {
        required: true,
        message: '请输入流动描述',
        trigger: 'blur'
      },
      {
        min: 2,
        max: 200,
        message: '描述长度应在2-200个字符之间',
        trigger: 'blur'
      }
    ],
    toUserId: [
      {
        validator: (rule: any, value: any) => {
          if ((form.flowType === 30 || form.flowType === 40) && !value) {
            return Promise.reject('转账操作必须填写对方用户ID');
          }
          return Promise.resolve();
        },
        trigger: 'blur'
      }
    ]
  });

  /* 获取金额预览提示类型 */
  const getAmountAlertType = () => {
    if (!form.flowType) return 'info';

    switch (form.flowType) {
      case 10: // 佣金收入
      case 40: // 转账收入
        return 'success';
      case 20: // 提现支出
      case 30: // 转账支出
        return 'warning';
      default:
        return 'info';
    }
  };

  /* 获取金额预览文本 */
  const getAmountPreviewText = () => {
    if (!form.money || !form.flowType) return '';

    const amount = parseFloat(form.money.toString()).toFixed(2);
    const flowTypeMap = {
      10: '佣金收入',
      20: '提现支出',
      30: '转账支出',
      40: '转账收入'
    };

    const flowTypeName = flowTypeMap[form.flowType] || '未知类型';
    const symbol = form.flowType === 10 || form.flowType === 40 ? '+' : '-';

    return `${flowTypeName}：${symbol}¥${amount}`;
  };

  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
          ? updateShopDealerCapital
          : addShopDealerCapital;
        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);
          isUpdate.value = true;
        } else {
          // 重置为默认值
          Object.assign(form, {
            id: undefined,
            userId: undefined,
            orderId: undefined,
            flowType: undefined,
            money: undefined,
            comments: '',
            toUserId: undefined,
            tenantId: undefined,
            createTime: undefined,
            updateTime: undefined
          });
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>

<style lang="less" scoped>
  .flow-type-option {
    display: flex;
    align-items: center;

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

    span {
      color: #666;
      font-size: 12px;
    }
  }

  .amount-preview {
    :deep(.ant-alert) {
      .ant-alert-message {
        font-weight: 600;
        font-size: 14px;
      }
    }
  }

  :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-select-selection-item) {
    display: flex;
    align-items: center;
  }

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