<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="提现单号" prop="withdrawalSn">
              <el-input v-model="queryParams.withdrawalSn" placeholder="请输入提现单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="打款状态" prop="pendStatus">
              <el-select v-model="queryParams.pendStatus" placeholder="请选择打款状态" clearable>
                <el-option v-for="dict in pend_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="提交时间" prop="submitTimeRange">
              <el-date-picker
                v-model="queryParams.submitTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:withdrawalOrders:add']"> 提现 </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:withdrawalOrders:edit']"-->
          <!--              >修改-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:withdrawalOrders:remove']"-->
          <!--              >删除-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:withdrawalOrders:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="withdrawalOrdersList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <!--        <el-table-column label="主键ID" align="center" prop="id" v-if="true" />-->
        <el-table-column label="提现单号" width="120" align="center" prop="withdrawalSn" />
        <!--        <el-table-column label="代理ID" align="center" prop="agentId" />-->
        <!--        <el-table-column label="代理名称" align="center" prop="agentName" />-->
        <el-table-column label="账户类型" align="center" prop="accountType" />
        <el-table-column label="打款账号" width="120" align="center" prop="payoutAccount" />
        <el-table-column label="账户实名" align="center" prop="accountName" />
        <el-table-column label="提现金额" align="center" prop="amount" />
        <el-table-column label="提交时间" align="center" prop="submitTime" width="180"></el-table-column>
        <!--        <el-table-column label="手续费" align="center" prop="fee" />-->
        <!--        <el-table-column label="实际打款金额" align="center" prop="actualAmount" />-->
        <el-table-column label="打款状态" align="center" prop="pendStatus">
          <template #default="scope">
            <dict-tag :options="pend_status" :value="scope.row.pendStatus" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="打款接口" align="center" prop="payoutGateway" />-->
        <el-table-column label="打款接口信息" width="120" align="center" prop="gatewayResponse" />
        <!-- <el-table-column label="提交时间" align="center" prop="submitTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.submitTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="打款时间" align="center" prop="payoutTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.payoutTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="操作员ID" align="center" prop="operatorId" />-->
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:withdrawalOrders:edit']"></el-button>
            </el-tooltip> -->
            <el-button
              v-if="scope.row.pendStatus !== '2' && scope.row.pendStatus !== '4'"
              link
              type="warning"
              @click="handleWithdraw(scope.row)"
              v-hasPermi="['system:withdrawalOrders:withdraw']"
            >撤回</el-button>
            <span v-else>-</span>
            <!-- <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:withdrawalOrders:remove']"
              ></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改提现申请记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="withdrawalOrdersFormRef" :model="form" :rules="rules" label-width="0px">
        <div class="withdrawal-form">
          <!-- 余额显示 -->
          <div class="balance-section">
            <div class="balance-info">
              <span class="balance-label">账户利余可提现金额：</span>
              <span class="balance-amount">{{ availableBalance }} 元</span>
              <el-button type="text" class="withdraw-all-btn" @click="withdrawAll">全部提现</el-button>
            </div>
          </div>

          <!-- 提现金额输入 -->
          <div class="amount-section">
            <el-form-item prop="amount">
              <el-input v-model.number="form.amount" placeholder="请输入提现金额" class="amount-input" size="large" type="number" />
            </el-form-item>
            <div class="amount-tips">
              <span class="tip-text">* 最低提现金额100元，每月1~10提现，当月16日到账。</span>
            </div>
          </div>

          <!-- 提现方式选择 -->
          <div class="payment-method-section">
            <div class="method-label">提现方式</div>
            <el-form-item prop="accountType">
              <div class="method-options">
                <div class="method-option" :class="{ active: form.accountType === 'wechat' }" @click="selectPaymentMethod('wechat')">
                  <i class="icon-wechat"></i>
                  <span>微信</span>
                </div>
                <div class="method-option" :class="{ active: form.accountType === 'alipay' }" @click="selectPaymentMethod('alipay')">
                  <i class="icon-alipay"></i>
                  <span>支付宝</span>
                </div>
              </div>
            </el-form-item>
          </div>

          <!-- 账户信息 -->
          <div class="account-section">
            <div class="account-item">
              <label class="account-label">
                <span class="required">*</span>
                <span>姓名</span>
              </label>
              <el-form-item prop="accountName">
                <el-input v-model="form.accountName" placeholder="输入真实的姓名" class="account-input" />
              </el-form-item>
            </div>

            <div class="account-item">
              <label class="account-label">
                <span class="required">*</span>
                <span>账号</span>
              </label>
              <el-form-item prop="payoutAccount">
                <el-input
                  v-model="form.payoutAccount"
                  :placeholder="form.accountType === 'wechat' ? '输入正确的微信账号' : '输入正确的支付宝账号'"
                  class="account-input"
                />
              </el-form-item>
            </div>

            <!-- 管理员编辑时显示状态选择 -->
            <div v-if="form.id" class="account-item">
              <label class="account-label">
                <span>打款状态</span>
              </label>
              <el-form-item prop="pendStatus">
                <el-select v-model="form.pendStatus" placeholder="请选择打款状态" class="account-input">
                  <el-option v-for="dict in pend_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </div>

            <div v-if="form.id" class="account-item">
              <label class="account-label">
                <span>账户状态</span>
              </label>
              <el-form-item prop="status">
                <el-select v-model="form.status" placeholder="请选择账户状态" class="account-input">
                  <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </div>

            <!-- 备注字段 -->
            <div v-if="form.id" class="account-item">
              <label class="account-label">
                <span>备注</span>
              </label>
              <el-form-item prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" class="account-input" type="textarea" :rows="3" />
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel" size="large">取 消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm" size="large">提 交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="WithdrawalOrders" lang="ts">
import {
  listWithdrawalOrders,
  getWithdrawalOrders,
  delWithdrawalOrders,
  addWithdrawalOrders,
  updateWithdrawalOrders,
  changeOrderStatus
} from '@/api/agent/withdrawalOrders';
import { WithdrawalOrdersVO, WithdrawalOrdersQuery, WithdrawalOrdersForm } from '@/api/agent/withdrawalOrders/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { sys_normal_disable, pend_status } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'pend_status'));

const withdrawalOrdersList = ref<WithdrawalOrdersVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const availableBalance = ref(5000.0); // 模拟余额数据

const queryFormRef = ref<ElFormInstance>();
const withdrawalOrdersFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: WithdrawalOrdersForm = {
  id: undefined,
  accountType: 'wechat', // 默认选中微信
  payoutAccount: undefined,
  accountName: undefined,
  amount: undefined,
  pendStatus: pend_status.value?.[0]?.value || '待打款', // 使用字典数据的第一个值或默认值
  payoutTime: undefined,
  status: sys_normal_disable.value?.[0]?.value || '0', // 使用字典数据的第一个值或默认值
  remark: undefined
};
const data = reactive<PageData<WithdrawalOrdersForm, WithdrawalOrdersQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    withdrawalSn: undefined,
    pendStatus: undefined,
    submitTimeRange: undefined,
    params: {}
  } as any,
  rules: {
    accountName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    payoutAccount: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
    amount: [
      { required: true, message: '提现金额不能为空', trigger: 'blur' },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (value && (isNaN(value) || parseFloat(value) < 100)) {
            callback(new Error('最低提现金额100元'));
          } else if (value && parseFloat(value) > availableBalance.value) {
            callback(new Error('提现金额不能超过可用余额'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    accountType: [{ required: true, message: '请选择提现方式', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询提现申请记录列表 */
const getList = async () => {
  loading.value = true;

  // 处理时间范围参数
  const params = { ...queryParams.value } as any;
  if (params.submitTimeRange && params.submitTimeRange.length === 2) {
    params.submitTimeStart = params.submitTimeRange[0];
    params.submitTimeEnd = params.submitTimeRange[1];
  }
  delete params.submitTimeRange;

  const res = await listWithdrawalOrders(params);
  withdrawalOrdersList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  withdrawalOrdersFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: WithdrawalOrdersVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '提现';
};

/** 选择支付方式 */
const selectPaymentMethod = (method: string) => {
  form.value.accountType = method;
  // 清空账号输入
  form.value.payoutAccount = undefined;
};

/** 全部提现 */
const withdrawAll = () => {
  form.value.amount = Number(availableBalance.value);
};

/** 修改按钮操作 */
const handleUpdate = async (row?: WithdrawalOrdersVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getWithdrawalOrders(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改提现申请记录';
};

/** 提交按钮 */
const submitForm = () => {
  withdrawalOrdersFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 确保金额是数字类型
        const formData = {
          ...form.value,
          amount: Number(form.value.amount)
        };

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

        if (form.value.id) {
          const result = await updateWithdrawalOrders(formData);
          console.log('更新结果:', result);
        } else {
          const result = await addWithdrawalOrders(formData);
          console.log('新增结果:', result);
        }
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        await getList();
      } catch (error: any) {
        console.error('提交失败:', error);
        proxy?.$modal.msgError('提交失败: ' + (error?.response?.data?.msg || error?.message || '未知错误'));
      } finally {
        buttonLoading.value = false;
      }
    } else {
      console.log('表单验证失败');
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: WithdrawalOrdersVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除提现申请记录编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delWithdrawalOrders(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 撤回按钮操作 */
const handleWithdraw = async (row: WithdrawalOrdersVO) => {
  try {
    await proxy?.$modal.confirm('是否确认撤回提现申请记录编号为"' + row.withdrawalSn + '"的数据项？');

    const changeData = {
      id: row.id,
      accountType: row.accountType,
      payoutAccount: row.payoutAccount,
      accountName: row.accountName,
      amount: Number(row.amount),
      pendStatus: '4', // 撤回时固定发送"已退回"状态（字典值4）
      remark: '用户撤回申请'
    };

    console.log('撤回数据:', changeData);

    const result = await changeOrderStatus(changeData);
    console.log('撤回结果:', result);

    proxy?.$modal.msgSuccess('撤回成功');
    await getList();
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('撤回失败:', error);
      proxy?.$modal.msgError('撤回失败: ' + (error?.response?.data?.msg || error?.message || '未知错误'));
    }
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'order/withdrawalOrders/export',
    {
      ...queryParams.value
    },
    `withdrawalOrders_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.withdrawal-form {
  padding: 20px 0;
}

.balance-section {
  margin-bottom: 30px;
  text-align: center;
}

.balance-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.balance-label {
  font-size: 16px;
  color: #666;
}

.balance-amount {
  font-size: 24px;
  font-weight: bold;
  color: #ff9500;
}

.withdraw-all-btn {
  color: #ff9500;
  font-size: 14px;
  padding: 0;
  text-decoration: underline;
}

.amount-section {
  margin-bottom: 30px;
}

.amount-input {
  margin-bottom: 10px;
}

.amount-input :deep(.el-input__inner) {
  font-size: 18px;
  text-align: center;
  height: 60px;
  line-height: 60px;
}

.amount-tips {
  text-align: center;
}

.tip-text {
  color: #ff9500;
  font-size: 12px;
}

.payment-method-section {
  margin-bottom: 30px;
}

.method-label {
  font-size: 16px;
  color: #333;
  margin-bottom: 15px;
}

.method-options {
  display: flex;
  gap: 20px;
}

.method-option {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 15px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 16px;
}

.method-option.active {
  border-color: #ff9500;
  background-color: #fff7e6;
  color: #ff9500;
}

.method-option:hover {
  border-color: #ff9500;
}

.icon-wechat::before {
  content: '📱';
  font-size: 20px;
  color: #07c160;
}

.method-option.active .icon-wechat::before {
  color: #ff9500;
}

.icon-alipay::before {
  content: '💳';
  font-size: 20px;
  color: #1677ff;
}

.method-option.active .icon-alipay::before {
  color: #ff9500;
}

.account-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.account-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.account-label {
  font-size: 14px;
  color: #333;
  display: flex;
  align-items: center;
  gap: 4px;
}

.required {
  color: #f56c6c;
  font-size: 14px;
}

.account-input :deep(.el-input__inner) {
  height: 45px;
  line-height: 45px;
}

.account-input :deep(.el-select) {
  width: 100%;
}

.account-input :deep(.el-select .el-input__inner) {
  height: 45px;
  line-height: 45px;
}

.account-input :deep(.el-textarea__inner) {
  min-height: 80px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding-top: 20px;
}

.dialog-footer .el-button {
  min-width: 120px;
  height: 45px;
}
</style>
