<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="900"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑分销商用户' : '添加分销商用户'"
    :body-style="{ paddingBottom: '28px', maxHeight: '70vh', overflowY: 'auto' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      layout="horizontal"
    >
      <!-- 基本信息 -->
      <a-divider orientation="left">基本信息</a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="用户ID"
            name="userId"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-input-number
              :min="1"
              placeholder="请输入用户ID"
              v-model:value="form.userId"
              style="width: 100%"
              :disabled="isUpdate"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="姓名"
            name="realName"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-input
              allow-clear
              placeholder="请输入真实姓名"
              v-model:value="form.realName"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="手机号"
            name="mobile"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-input
              allow-clear
              placeholder="请输入手机号"
              v-model:value="form.mobile"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="支付密码"
            name="payPassword"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-input-password
              allow-clear
              placeholder="请输入支付密码"
              v-model:value="form.payPassword"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 佣金信息 -->
      <a-divider orientation="left">佣金信息</a-divider>

      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item
            label="可提现佣金"
            name="money"
            :label-col="{ span: 12 }"
            :wrapper-col="{ span: 12 }"
          >
            <a-input-number
              :min="0"
              :precision="2"
              placeholder="0.00"
              v-model:value="form.money"
              style="width: 100%"
            >
              <template #addonAfter>元</template>
            </a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="冻结佣金"
            name="freezeMoney"
            :label-col="{ span: 12 }"
            :wrapper-col="{ span: 12 }"
          >
            <a-input-number
              :min="0"
              :precision="2"
              placeholder="0.00"
              v-model:value="form.freezeMoney"
              style="width: 100%"
            >
              <template #addonAfter>元</template>
            </a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="累计提现"
            name="totalMoney"
            :label-col="{ span: 12 }"
            :wrapper-col="{ span: 12 }"
          >
            <a-input-number
              :min="0"
              :precision="2"
              placeholder="0.00"
              v-model:value="form.totalMoney"
              style="width: 100%"
              :disabled="true"
            >
              <template #addonAfter>元</template>
            </a-input-number>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 推荐关系 -->
      <a-divider orientation="left">推荐关系</a-divider>

      <a-form-item label="推荐人" name="refereeId">
        <a-input-group compact>
          <a-input-number
            :min="1"
            placeholder="请输入推荐人用户ID"
            v-model:value="form.refereeId"
            style="width: calc(100% - 80px)"
          />
          <a-button type="primary" @click="selectReferee">选择</a-button>
        </a-input-group>
      </a-form-item>
      <!-- 团队信息 -->
      <a-divider orientation="left">团队信息</a-divider>

      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item
            label="一级成员"
            name="firstNum"
            :label-col="{ span: 12 }"
            :wrapper-col="{ span: 12 }"
          >
            <a-input-number
              :min="0"
              placeholder="0"
              v-model:value="form.firstNum"
              style="width: 100%"
              :disabled="true"
            >
              <template #addonAfter>人</template>
            </a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="二级成员"
            name="secondNum"
            :label-col="{ span: 12 }"
            :wrapper-col="{ span: 12 }"
          >
            <a-input-number
              :min="0"
              placeholder="0"
              v-model:value="form.secondNum"
              style="width: 100%"
              :disabled="true"
            >
              <template #addonAfter>人</template>
            </a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="三级成员"
            name="thirdNum"
            :label-col="{ span: 12 }"
            :wrapper-col="{ span: 12 }"
          >
            <a-input-number
              :min="0"
              placeholder="0"
              v-model:value="form.thirdNum"
              style="width: 100%"
              :disabled="true"
            >
              <template #addonAfter>人</template>
            </a-input-number>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 其他设置 -->
      <a-divider orientation="left">其他设置</a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="专属二维码"
            name="qrcode"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-input-group compact>
              <a-input
                placeholder="系统自动生成"
                v-model:value="form.qrcode"
                style="width: calc(100% - 80px)"
                :disabled="true"
              />
              <a-button type="primary" @click="generateQrcode">生成</a-button>
            </a-input-group>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="账户状态"
            name="isDelete"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-radio-group v-model:value="form.isDelete">
              <a-radio :value="0">正常</a-radio>
              <a-radio :value="1">已删除</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
    </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 { addShopDealerUser, updateShopDealerUser } from '@/api/shop/shopDealerUser';
  import { ShopDealerUser } from '@/api/shop/shopDealerUser/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?: ShopDealerUser | 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<ShopDealerUser>({
    id: undefined,
    userId: undefined,
    realName: undefined,
    mobile: undefined,
    payPassword: undefined,
    money: undefined,
    freezeMoney: undefined,
    totalMoney: undefined,
    refereeId: undefined,
    firstNum: undefined,
    secondNum: undefined,
    thirdNum: undefined,
    qrcode: undefined,
    isDelete: undefined,
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined,
    shopDealerUserId: undefined,
    shopDealerUserName: '',
    status: 0,
    comments: '',
    sortNumber: 100
  });

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

  // 表单验证规则
  const rules = reactive({
    userId: [
      {
        required: true,
        message: '请输入用户ID',
        trigger: 'blur'
      }
    ],
    realName: [
      {
        required: true,
        message: '请输入真实姓名',
        trigger: 'blur'
      },
      {
        min: 2,
        max: 20,
        message: '姓名长度应在2-20个字符之间',
        trigger: 'blur'
      }
    ],
    mobile: [
      {
        required: true,
        message: '请输入手机号',
        trigger: 'blur'
      },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入正确的手机号格式',
        trigger: 'blur'
      }
    ],
    money: [
      {
        type: 'number',
        min: 0,
        message: '可提现佣金不能小于0',
        trigger: 'blur'
      }
    ],
    freezeMoney: [
      {
        type: 'number',
        min: 0,
        message: '冻结佣金不能小于0',
        trigger: 'blur'
      }
    ]
  });

  const chooseImage = (data: FileRecord) => {
    images.value.push({
      uid: data.id,
      url: data.path,
      status: 'done'
    });
    form.image = data.path;
  };

  const onDeleteItem = (index: number) => {
    images.value.splice(index, 1);
    form.image = '';
  };

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

  /* 选择推荐人 */
  const selectReferee = () => {
    message.info('推荐人选择功能待开发');
    // 这里可以打开用户选择器
  };

  /* 生成二维码 */
  const generateQrcode = () => {
    if (!form.userId) {
      message.error('请先填写用户ID');
      return;
    }

    // 生成二维码逻辑
    const qrcode = `DEALER_${form.userId}_${Date.now()}`;
    form.qrcode = qrcode;
    message.success('二维码生成成功');
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;

        // 数据处理
        const formData = {
          ...form
        };

        // 确保数值类型正确
        if (formData.userId) formData.userId = Number(formData.userId);
        if (formData.refereeId) formData.refereeId = Number(formData.refereeId);
        if (formData.money !== undefined) formData.money = Number(formData.money);
        if (formData.freezeMoney !== undefined) formData.freezeMoney = Number(formData.freezeMoney);
        if (formData.totalMoney !== undefined) formData.totalMoney = Number(formData.totalMoney);
        if (formData.firstNum !== undefined) formData.firstNum = Number(formData.firstNum);
        if (formData.secondNum !== undefined) formData.secondNum = Number(formData.secondNum);
        if (formData.thirdNum !== undefined) formData.thirdNum = Number(formData.thirdNum);
        if (formData.isDelete !== undefined) formData.isDelete = Number(formData.isDelete);

        console.log('提交的数据:', formData);

        const saveOrUpdate = isUpdate.value ? updateShopDealerUser : addShopDealerUser;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg || '操作成功');
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            console.error('保存失败:', e);
            message.error(e.message || '操作失败');
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        images.value = [];
        if (props.data) {
          assignObject(form, props.data);
          if(props.data.image){
            images.value.push({
              uid: uuid(),
              url: props.data.image,
              status: 'done'
            })
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>

<style lang="less" scoped>
:deep(.ant-form-item-label) {
  text-align: left !important;
}

:deep(.ant-form-item-label > label) {
  text-align: left !important;
}

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

  .ant-divider-inner-text {
    color: #1890ff;
    font-weight: 600;
  }
}

:deep(.ant-input-group-addon) {
  padding: 0 8px;
}

:deep(.ant-input-number-disabled) {
  background-color: #f5f5f5;
  color: #999;
}
</style>
