<template>
  <div class="e-dialog">
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="20%" :draggable="draggable">
      <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="auto">
        <el-form-item label="人员姓名:" prop="realName">
          <el-input v-model="realNames" type="textarea" :rows="5" :disabled="true" />
        </el-form-item>
        <el-form-item label="操作钱包:" prop="bagCode">
          <el-select v-model="formData.bagCode" placeholder="请选择">
            <el-option v-for="dict in CARDBAGTYPE" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="receiptMoney">
          <template #label>
            操作金额:
            <el-tooltip placement="right-end">
              <template #content>
                {{ balanceInfo }}
              </template>
              <el-icon>
                <question-filled />
              </el-icon>
            </el-tooltip>
          </template>
          <el-input v-model="formData.receiptMoney" />
        </el-form-item>
        <el-form-item prop="payStyle">
          <template #label>
            资金来源:
            <el-tooltip placement="right-end">
              <template #content>
                {{ payStyleInfo }}
              </template>
              <el-icon>
                <question-filled />
              </el-icon>
            </el-tooltip>
          </template>
          <el-select v-model="formData.payStyle" placeholder="请选择">
            <el-option v-for="dict in PAYSTYLE" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="command == 'batchRecharge'" label="管理费" prop="commission">
          <template #label>
            管理费:
            <el-tooltip content="设置成收取时，将根据卡类的管理费标准收取管理费" placement="right-end">
              <el-icon>
                <question-filled />
              </el-icon>
            </el-tooltip>
          </template>
          <el-radio-group v-model="formData.takeCommission">
            <el-radio value="0">不收取</el-radio>
            <el-radio value="1">收取</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="formLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BatchRechargeFormRef" lang="ts">
import * as api from '@/api/payment/bag';
import { PtBagForm } from '@/api/payment/bag/types';
import { useI18n } from 'vue-i18n';
import { QuestionFilled } from '@element-plus/icons-vue';
import { CreditTypeEnum } from '@/enums/payments/CreditTypeEnum';
import { BalanceUpdateEnum } from '@/enums/payments/BalanceUpdateEnum';
import Decimal from 'decimal.js';
import useUserStore from '@/store/modules/user';

defineOptions({ name: 'BatchRechargeFormRef' });

/** 接收父组件传入属性 */
//const props = defineProps({resetName})

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 国际化
const { t } = useI18n();
/** 当前页面引用的数据字典 */
const { PAYSTYLE, CARDBAGTYPE } = toRefs<any>(proxy?.useDict('PAYSTYLE', 'CARDBAGTYPE'));
// 对话框
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 窗体是否可以拖动
const draggable = ref(true);
// 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formLoading = ref(false);
// 表单的类型：create - 新增；update - 修改
const formType = ref('');
// 操作类型
const command = ref('');
// 当前登录用户Id
const operationId = useUserStore().userId;
// 当前登录用户姓名
const operatorName = useUserStore().realName;
// 表单引用
const formRef = ref<ElFormInstance>();
// 表单数据
const formData = ref<PtBagForm>({
  userId: undefined,
  bagId: undefined,
  bagCode: undefined,
  balance: new Decimal(0.0),
  payStyle: '1',
  takeCommission: '0',
  receiptMoney: new Decimal(0.0),
  afterAmount: new Decimal(0.0),
  creditType: undefined,
  operationMode: undefined,
  cardId: undefined,
  cardTypeId: undefined,
  operatorId: operationId,
  operatorName: operatorName
});
// 表单校验规则
const formRules = reactive({
  bagCode: [{ required: true, message: '操作钱包不能为空', trigger: 'blur' }],
  balance: [
    { required: true, message: '操作金额不能为空', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/, message: '操作金额只能为正整数', trigger: 'blur' }
  ],
  payStyle: [{ required: true, message: '资金来源不能为空', trigger: 'blur' }]
});
// 选择的账户Id
const userIds = ref<Array<string | number>>();
// 选择的账户姓名
const realNames = ref<Array<string | number>>();
// 操作金额提示
const balanceInfo = ref('');
// 资金来源提示
const payStyleInfo = ref('');
/** 当前组件方法 */
// 窗体打开事件
const open = async (cmd: string, ids?: Array<string | number>, names?: Array<string>) => {
  dialog.visible = true;
  dialog.title = t('action.' + cmd);
  formType.value = 'edit';
  command.value = cmd;
  userIds.value = ids;
  realNames.value = names;
  resetForm();
  setBalanceInfo(cmd);
  setFundingInfo(cmd);
};
// 设置操作金额的提示信息
const setBalanceInfo = (cmd: string) => {
  switch (cmd) {
    case 'batchRecharge':
      balanceInfo.value = '钱包现有余额加上操作金额';
      break;
    case 'batchRefund':
      balanceInfo.value = '钱包现有余额减去操作金额，如余额不足则减至余额为0';
      break;
    case 'batchBalance':
      balanceInfo.value = '直接设置钱包余额为指定值';
      break;
  }
};
// 设置资金来源的提示信息
const setFundingInfo = (cmd: string) => {
  switch (cmd) {
    case 'batchRecharge':
    case 'batchBalance':
      payStyleInfo.value = '指支付方的付款方式';
      break;
    case 'batchRefund':
      payStyleInfo.value = '指收款方的收款方式';
      break;
  }
};
/** 表单重置 */
const resetForm = () => {
  formData.value = {
    userId: undefined,
    bagId: undefined,
    bagCode: undefined,
    balance: new Decimal(0.0),
    payStyle: '1',
    takeCommission: '0',
    receiptMoney: new Decimal(0.0),
    afterAmount: new Decimal(0.0),
    creditType: undefined,
    operationMode: undefined,
    cardId: undefined,
    cardTypeId: undefined,
    operatorId: operationId,
    operatorName: operatorName
  };
  formRef.value?.resetFields();
};
/** 传回给父组件的属性与方法 */
// 提供 open 方法，用于打开弹窗
defineExpose({ open });

/** 触发父组件的事件 */
// 定义 success 事件，用于操作成功后的回调
const emit = defineEmits(['success']);
// 提交按钮
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return;
  const valid = await formRef.value?.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as PtBagForm;
    switch (command.value) {
      case 'batchRecharge':
        data.creditType = CreditTypeEnum.RECHARGE;
        data.operationMode = BalanceUpdateEnum.RECHARGE;
        await api.batchRechargePtBag(data, userIds.value);
        break;
      case 'batchBalance':
        data.creditType = CreditTypeEnum.RECHARGE;
        data.operationMode = BalanceUpdateEnum.RECOVER;
        await api.batchRecoverPtBag(data, userIds.value);
        break;
      case 'batchRefund':
        data.creditType = CreditTypeEnum.REFUND;
        data.operationMode = BalanceUpdateEnum.REFUND;
        await api.batchRefundPtBag(data, userIds.value);
        break;
    }
    dialog.visible = false;
    // 发送操作成功的事件
    emit('success');
  } finally {
    formLoading.value = false;
  }
};

/** 初始化 */
onMounted(() => {});
</script>
<style scoped>
.e-dialog {
  .slide-fade-enter-active {
    transition: all 0.3s ease;
  }

  .slide-fade-leave-active {
    transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
  }

  .slide-fade-enter,
  .slide-fade-leave-to {
    opacity: 0;
  }
}
:deep() .el-dialog {
  border-radius: 10px;
}

:deep() .el-dialog__body {
  padding: 1px 1px !important;
  max-height: 90vh !important;
}

:deep() .el-dialog__header {
  background: #1d78d5;
  border-radius: 6px 6px 5px 5px;
}

:deep() .el-dialog__title {
  color: white;
  margin-top: 1px;
}

:deep() .el-dialog__headerbtn .el-dialog__close {
  color: white !important;
  top: 15px;
  right: 10px;
}

:deep() .el-overlay .el-overlay-dialog .el-dialog .el-dialog__body {
  padding: 1px !important;
}
</style>
