<template>
  <div class="e-dialog">
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="50%" :draggable="draggable">
      <div class="panel">
        <h4 class="panel-title">{{ labelInfo }}</h4>
        <el-form ref="formAccountRef" :model="accountFormData" label-width="auto">
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名" prop="realName">
                <el-input v-model="accountFormData.realName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门" prop="deptName">
                <el-input v-model="accountFormData.deptName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="卡片类型" prop="cardTypeName">
                <el-input v-model="accountFormData.cardTypeName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="有效期" prop="lifespan">
                <el-input v-model="accountFormData.lifespan" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="auto">
          <el-row>
            <el-col :span="12">
              <el-form-item label="操作钱包" prop="bagCode">
                <el-select v-model="formData.bagCode" placeholder="请选择" @change="handleSelectBag">
                  <el-option v-for="dict in CARDBAGTYPE" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="钱包余额" prop="balance">
                <el-input v-model="formData.balance" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="操作金额" prop="receiptMoney">
                <el-input v-model="formData.receiptMoney" @blur="calculateAfterAmount" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="操作后余额" prop="afterAmount">
                <el-input v-model="formData.afterAmount" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="payStyle">
                <template #label>
                  资金来源:
                  <el-tooltip placement="right-end">
                    <template #content>
                      {{ fundingInfo }}
                    </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-col>
            <el-col :span="12">
              <el-form-item v-show="command == 'recharge'" label="管理费" prop="takeCommission">
                <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-col>
          </el-row>
        </el-form>
      </div>
      <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="RechargeForm" lang="ts">
// 模块导入
import api from '@/api/payment/account';
import { PtBagForm, PtBagVO } from '@/api/payment/bag/types';
import { rechargePtBag, refundPtBag } from '@/api/payment/bag';
import { PtUserAccountForm } from '@/api/payment/account/types';
import { useI18n } from 'vue-i18n';
import { QuestionFilled } from '@element-plus/icons-vue';
import Decimal from 'decimal.js';
import { CreditTypeEnum } from '@/enums/payments/CreditTypeEnum';
import { BalanceUpdateEnum } from '@/enums/payments/BalanceUpdateEnum';
import useUserStore from '@/store/modules/user';

// 接收父组件传入属性
// const props = defineProps({});
defineOptions({ name: 'RechargeForm' });
// 当前组件属性
const route = useRoute();
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);
// 是否加载遮罩层
const formLoading = ref(true);
// 表单的类型：create - 新增；update - 修改
const formType = ref('');
// 操作类型
const command = ref('');
// 标签信息
const labelInfo = ref('');
// 表单引用
const formRef = ref<ElFormInstance>();
// 当前登录用户Id
const operationId = useUserStore().userId;
// 当前登录用户姓名
const operatorName = useUserStore().realName;
// 表单引用
const formAccountRef = ref<ElFormInstance>();
// 表单数据
const formData = ref<PtBagForm>({
  userId: undefined,
  bagId: undefined,
  bagCode: undefined,
  balance: new Decimal(0.0),
  takeCommission: '0',
  receiptMoney: new Decimal(0.0),
  afterAmount: new Decimal(0.0),
  creditType: undefined,
  operationMode: undefined,
  cardId: undefined,
  cardTypeId: undefined,
  payStyle: '1',
  operatorId: operationId,
  operatorName: operatorName
});
// 表单校验规则
const formRules = reactive({
  bagCode: [{ required: true, message: '操作钱包不能为空', trigger: 'blur' }],
  receiptMoney: [
    { required: true, message: '操作金额不能为空', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '操作金额只能为两位小数的数字', trigger: 'blur' }
  ],
  funding: [{ required: true, message: '资金来源不能为空', trigger: 'blur' }]
});
// 选择的账户Id
const userIds = ref<string | number>();
// 选择的账户姓名
const realNames = ref();
// 操作金额提示
const balanceInfo = ref();
// 资金来源提示
const fundingInfo = ref();
// 收支类型
const creditType = ref();
const total = ref(0);
const accountFormData = ref<PtUserAccountForm>({
  realName: undefined,
  userNumb: '',
  deptName: '',
  cardTypeName: '',
  lifespan: '',
  userId: undefined
});
const bags = ref<PtBagVO[]>([]);
/** 当前组件方法 */
// 窗体打开事件
const open = async (cmd: string, id?: string | number, name?: string) => {
  dialog.visible = true;
  dialog.title = t('action.' + cmd);
  formType.value = 'edit';
  command.value = cmd;
  userIds.value = id;
  realNames.value = name;

  setBalanceInfo(cmd);
  setFundingInfo(cmd);
  resetForm();
  await getList(id);
};
// 设置操作金额的提示信息
const setBalanceInfo = (cmd: string) => {
  switch (cmd) {
    case 'recharge':
      labelInfo.value = '充值信息';
      balanceInfo.value = '钱包现有余额加上操作金额';
      creditType.value = '113';
      break;
    case 'refund':
      labelInfo.value = '退款信息';
      balanceInfo.value = '钱包现有余额减去操作金额，如余额不足则减至余额为0';
      creditType.value = '114';
      break;
  }
};
// 设置资金来源的提示信息
const setFundingInfo = (cmd: string) => {
  switch (cmd) {
    case 'recharge':
      fundingInfo.value = '指支付方的付款方式';
      break;
    case 'refund':
      fundingInfo.value = '指收款方的收款方式';
      break;
  }
};
// 钱包下拉选择事件
const handleSelectBag = (val?: string | number) => {
  const bag: PtBagVO = bags.value.find((p) => p.bagCode == val);
  formData.value.balance = bag.balance;
  if (command.value === 'refund') {
    // 一般退款是将账户的钱全部退还给持卡人，所以此处默认是退所有的余额
    formData.value.receiptMoney = bag.balance;
  }
  calculateAfterAmount();
};
/** 表单重置 */
const resetForm = () => {
  formData.value = {
    userId: userIds.value,
    bagId: undefined,
    bagCode: undefined,
    balance: new Decimal(0.0),
    takeCommission: '0',
    receiptMoney: new Decimal(0.0),
    afterAmount: new Decimal(0.0),
    creditType: undefined,
    operationMode: undefined,
    cardId: undefined,
    cardTypeId: undefined,
    payStyle: '1',
    operatorId: operationId,
    operatorName: operatorName
  };
  formRef.value?.resetFields();
};
// 计算充值/退款后的卡余
const calculateAfterAmount = () => {
  const openAmount = new Decimal(formData.value.receiptMoney);
  const oldBalance = new Decimal(formData.value.balance);
  if (command.value === 'recharge') {
    formData.value.afterAmount = oldBalance.add(openAmount);
  } else {
    formData.value.afterAmount = oldBalance.cmp(openAmount) === 1 ? oldBalance.sub(openAmount) : new Decimal(0.0);
  }
};
/** 传回给父组件的属性与方法 */
// 提供 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;
    data.userId = accountFormData.value.userId;
    data.cardTypeId = accountFormData.value.cardType;
    if (command.value === 'recharge') {
      data.creditType = CreditTypeEnum.RECHARGE;
      data.operationMode = BalanceUpdateEnum.RECHARGE;
      await rechargePtBag(data);
    } else {
      data.creditType = CreditTypeEnum.REFUND;
      data.operationMode = BalanceUpdateEnum.REFUND;
      await refundPtBag(data);
    }
    dialog.visible = false;
    // 发送操作成功的事件
    emit('success');
  } finally {
    formLoading.value = false;
  }
};

const getList = async (userId: string | number) => {
  formLoading.value = true;
  const res = await api.getAccountBag(userId as string);
  Object.assign(accountFormData.value, res.data.account);
  Object.assign(bags.value, res.data.bags);
  total.value = bags.value.length;
  formLoading.value = false;
};
/** 关闭按钮 */
</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>
