<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="600"
    :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="styleResponsive ? { md: 5, sm: 6, xs: 24 } : { flex: '100px' }"
      :wrapper-col="
        styleResponsive ? { md: 18, sm: 17, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="所属门店" name="storeId">
        <a-select
          placeholder="请选择门店"
          v-model:value="form.storeId"
          show-search
          :filter-option="filterStoreOption"
        >
          <a-select-option v-for="store in storeList" :key="store.id" :value="store.id" :label="store.name">
            {{ store.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="角色类型" name="roleType">
        <a-radio-group v-model:value="form.roleType">
          <a-radio :value="1">门店经理</a-radio>
          <a-radio :value="2">店员</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="手机号" name="phone">
        <a-input-search
          placeholder="请输入手机号"
          v-model:value="form.phone"
          @search="onSearchByPhone"
          @pressEnter="onSearchByPhone"
          enter-button="查询用户"
        />
      </a-form-item>

      <a-form-item label="关联用户" v-if="linkedUser">
        <a-card size="small" class="linked-user-card">
          <a-space>
            <a-avatar :src="linkedUser.avatar" :size="40">
              <template #icon><UserOutlined /></template>
            </a-avatar>
            <div>
              <div class="linked-user-name">
                {{ linkedUser.realName || linkedUser.nickname || '未知用户' }}
              </div>
              <div class="linked-user-phone">{{ linkedUser.phone }}</div>
            </div>
          </a-space>
        </a-card>
      </a-form-item>

      <a-form-item label="姓名" name="name">
        <a-input
          placeholder="请输入姓名"
          v-model:value="form.name"
        />
      </a-form-item>

      <a-form-item label="头像" name="image">
        <SelectFile
            :placeholder="'请选择封面图'"
            :limit="1"
            :data="images"
            @done="chooseImage"
            @del="onDeleteImage"
        />
      </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="status">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="0">正常</a-radio>
          <a-radio :value="1">禁用</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="备注" name="comments">
        <a-textarea
          :rows="3"
          :maxlength="200"
          placeholder="请输入备注"
          v-model:value="form.comments"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, computed } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, uuid } from 'ele-admin-pro';
  import { addShopStoreUser, updateShopStoreUser, getUserByPhone, ROLE_TYPE_OPTIONS, STATUS_OPTIONS } from '@/api/shop/shopStoreUser';
  import { listShopStore } from '@/api/shop/shopStore';
  import { ShopStoreUser } from '@/api/shop/shopStoreUser/model';
  import { ShopStore } from '@/api/shop/shopStore/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';
  import { UserOutlined } from '@ant-design/icons-vue';

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

  const props = defineProps<{
    visible: boolean;
    data?: ShopStoreUser | 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 storeList = ref<ShopStore[]>([]);
  // 关联的用户信息
  const linkedUser = ref<any>(null);

  // 表单数据
  const form = reactive<ShopStoreUser>({
    id: undefined,
    storeId: undefined,
    userId: undefined,
    name: '',
    phone: '',
    image: '',
    roleType: 2,  // 默认店员
    status: 0,     // 默认正常
    comments: '',
    sortNumber: 100
  });

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

  // 表单验证规则
  const rules = reactive({
    storeId: [
      { required: true, type: 'number', message: '请选择门店', trigger: 'change' }
    ],
    roleType: [
      { required: true, type: 'number', message: '请选择角色类型', trigger: 'change' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    name: [
      { required: true, message: '请输入姓名', trigger: 'blur' }
    ]
  });

  // 删除封面图
  const onDeleteImage = (index: number) => {
    images.value.splice(index, 1);
    form.productImage = '';
  };

  // 加载门店列表
  const loadStoreList = async () => {
    try {
      const list = await listShopStore({ status: 0 });
      storeList.value = list || [];
    } catch (e) {
      console.error('加载门店列表失败', e);
    }
  };

  // 门店搜索过滤
  const filterStoreOption = (input: string, option: any) => {
    const label = option.label || option.children?.[0]?.text || '';
    return label.toLowerCase().includes(input.toLowerCase());
  };

  // 根据手机号查询用户
  const onSearchByPhone = async () => {
    if (!form.phone) {
      message.warning('请输入手机号');
      return;
    }
    if (!/^1[3-9]\d{9}$/.test(form.phone)) {
      message.warning('手机号格式不正确');
      return;
    }
    try {
      const user = await getUserByPhone(form.phone);
      linkedUser.value = user;
      form.userId = user.userId;
      // 自动填充姓名
      if (!form.name && (user.realName || user.nickname)) {
        form.name = user.realName || user.nickname || '';
      }
      // 自动填充头像
      if (!form.image && user.avatar) {
        form.image = user.avatar;
        images.value = [{
          uid: uuid(),
          url: user.avatar,
          status: 'done'
        }];
      }
      message.success('用户查询成功');
    } catch (e: any) {
      linkedUser.value = null;
      form.userId = undefined;
      message.info(e.message || '未找到该手机号对应的用户');
    }
  };

  // 图片选择完成
  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 save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = { ...form };
        const saveOrUpdate = isUpdate.value ? updateShopStoreUser : addShopStoreUser;
        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) {
        // 每次打开弹窗都加载门店列表
        loadStoreList();
        images.value = [];
        linkedUser.value = null;

        if (props.data) {
          // 编辑模式
          assignObject(form, props.data);
          isUpdate.value = true;

          if (props.data.image) {
            images.value = [{
              uid: uuid(),
              url: props.data.image,
              status: 'done'
            }];
          }

          // 如果有用户ID，尝试获取用户信息
          if (props.data.phone) {
            linkedUser.value = {
              phone: props.data.phone,
              avatar: props.data.avatar || props.data.image,
              realName: props.data.name,
              nickname: props.data.nickname
            };
          }
        } else {
          // 新增模式
          isUpdate.value = false;
          resetFields();
          form.roleType = 2;
          form.status = 0;
          form.sortNumber = 100;
        }
      }
    },
    { immediate: true }
  );
</script>

<style scoped>
.linked-user-card {
  background: #f5f5f5;
  border-color: #d9d9d9;
}

.linked-user-name {
  font-weight: 500;
  color: #333;
}

.linked-user-phone {
  font-size: 12px;
  color: #999;
}
</style>
