<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" :label-width="formLabelWidth" v-loading="loading"
        :element-loading-text="t('common.loading')">
        <el-form-item :label="t('modules.user.userPhone')" prop="phoneNo">
          <el-input v-model="form.model.phoneNo" :placeholder="t('form.inputUserPhone')"></el-input>
        </el-form-item>
        <el-form-item :label="t('modules.user.username')" prop="name">
          <el-input v-model="form.model.name" :placeholder="t('form.inputUsername')"></el-input>
        </el-form-item>

        <el-form-item :label="t('modules.user.userAvatar')" prop="headPic">
          <sa-upload-image v-model="form.model.headPic" :max-count="1" :accept="['jpg', 'png']" :max-size="5"
            :direct-upload="true" :size="100" field5 :placeholder="t('form.uploadUserAvatar')" />
        </el-form-item>

        <el-form-item :label="t('modules.user.paymentBank')" prop="bank">
          <el-input v-model="form.model.bank" :placeholder="t('form.inputPaymentBank')"></el-input>
        </el-form-item>

        <el-form-item :label="t('modules.user.accountName')" prop="bankAccountName">
          <el-input v-model="form.model.bankAccountName" :placeholder="t('form.inputAccountName')"></el-input>
        </el-form-item>

        <el-form-item :label="t('modules.user.paymentAccount')" prop="bankAccount">
          <el-input v-model="form.model.bankAccount" :placeholder="t('form.inputPaymentAccount')"></el-input>
        </el-form-item>

        <!-- 权限设置 -->
        <el-form-item :label="t('modules.user.loginPermission')" prop="hasLogin">
          <el-switch v-model="form.model.hasLogin" :active-value="1" :inactive-value="2"
            :active-text="t('common.allow') + t('modules.user.login')"
            :inactive-text="t('common.forbid') + t('modules.user.login')" inline-prompt />
        </el-form-item>

        <el-form-item :label="t('modules.user.orderPermission')" prop="hasOrder">
          <el-switch v-model="form.model.hasOrder" :active-value="1" :inactive-value="2"
            :active-text="t('common.allow') + t('modules.user.order')"
            :inactive-text="t('common.forbid') + t('modules.user.order')" inline-prompt />
        </el-form-item>

        <el-form-item :label="t('modules.user.withdrawPermission')" prop="hasWithdraw">
          <el-switch v-model="form.model.hasWithdraw" :active-value="1" :inactive-value="2"
            :active-text="t('common.allow') + t('modules.user.withdraw')"
            :inactive-text="t('common.forbid') + t('modules.user.withdraw')" inline-prompt />
        </el-form-item>

        <el-form-item :label="t('common.memo')" prop="memo">
          <el-input v-model="form.model.memo" type="textarea" :rows="4" maxlength="100" show-word-limit
            :placeholder="t('form.inputMemo')"></el-input>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button v-if="modal.params.type == 'add'" type="primary" @click="confirm">{{ t('common.save') }}</el-button>
      <el-button v-if="modal.params.type == 'edit'" type="primary" @click="confirm">{{ t('common.update') }}</el-button>
    </el-footer>
  </el-container>
</template>
<script setup>
import { cloneDeep } from 'lodash';
import { onMounted, reactive, ref, unref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useFormConfig } from '@/hooks/useFormConfig';
import { api } from '../user.service';
import { ElMessage } from 'element-plus';

const { t } = useI18n();
const { formLabelWidth } = useFormConfig({ enWidth: '180px' });
const emit = defineEmits(['modalCallBack']);
const props = defineProps({
  modal: {
    type: Object,
  },
});
// 添加 编辑 form
let formRef = ref(null);
const form = reactive({
  model: {
    name: '',
    phoneNo: '',
    headPic: [],
    bank: '',
    bankAccountName: '',
    bankAccount: '',
    hasLogin: 1, // 登录权限：1是 2否
    hasOrder: 1, // 下单权限：1是 2否
    hasWithdraw: 1, // 提现权限：1是 2否
    memo: '',
  },
  rules: {
    // name: [{ required: true, message: '请填写用户昵称', trigger: 'blur' }],
    phoneNo: [{ required: true, message: '请填写手机号', trigger: 'blur' }],
    // headPic: [{ required: true, message: '请上传用户头像', trigger: 'change' }],
    hasLogin: [{ required: true, message: '请设置登录权限', trigger: 'change' }],
    hasOrder: [{ required: true, message: '请设置下单权限', trigger: 'change' }],
    hasWithdraw: [{ required: true, message: '请设置提现权限', trigger: 'change' }],
    memo: [{ max: 100, message: '备注不能超过100字', trigger: 'blur' }],
  },
});
const loading = ref(false);
// 获取详情
async function getDetail(id) {
  loading.value = true;
  const { code, data } = await api.list.userDetail(id);
  if (code == 200) {
    // 处理头像数据
    if (data.headPic) {
      form.model.headPic = Array.isArray(data.headPic) ? data.headPic : [data.headPic];
    }
    // 其他字段直接赋值
    Object.keys(form.model).forEach((key) => {
      if (key !== 'headPic' && data[key] !== undefined) {
        form.model[key] = data[key];
      }
    });
  }
  loading.value = false;
}

// 表单关闭时提交
async function confirm() {
  unref(formRef).validate(async (valid) => {
    if (!valid) return;
    let submitForm = cloneDeep(form.model);

    // 处理头像数据 - 只提交第一张图片的URL
    if (submitForm.headPic && submitForm.headPic.length > 0) {
      submitForm.headPic = submitForm.headPic[0];
    } else {
      submitForm.headPic = '';
    }

    const { code } =
      props.modal.params.type == 'add'
        ? await api.list.add(submitForm)
        : await api.list.edit({ id: props.modal.params.id, ...submitForm });
    if (code == '200') {
      ElMessage.success(t('message.saveSuccess'));
      emit('modalCallBack', { event: 'confirm' });
    }
  });
}
async function init() {
  if (props.modal.params.id) {
    await getDetail(props.modal.params.id);
  }
}
onMounted(() => {
  init();
});
</script>

<style lang="scss" scoped>
.el-form {
  max-width: 600px;

  .el-checkbox-group {
    .el-checkbox {
      margin-right: 15px;
    }
  }
}
</style>
