<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" v-loading="loading" class="mb-[10px]">
        <el-card v-if="payForm.refundType === '1' || payForm.refundType === '2'" shadow="hover">
          <template #header>
            <span>暂收费信息</span>
          </template>
          <el-form ref="chargesFormRef" :model="chargesForm" :inline="true" label-width="130px" label-position="left">
            <!-- 隐藏信息 -->
            <el-form-item v-if="false" label="暂收费ID" prop="temporaryChargeId">
              <el-input v-model="chargesForm.temporaryChargeId" readonly />
            </el-form-item>
            <el-form-item label="管理机构" prop="manageCom">
              <el-select v-model="chargesForm.manageCom" readonly placeholder="请输入管理机构">
                <el-option v-for="dict in sys_managecom" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否委托专户" prop="isEntrust">
              <el-select v-model="chargesForm.isEntrust" readonly placeholder="是否委托专户" @change="isEntrustForm">
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="收款银行账号" prop="receivingBankAccount">
              <el-input v-model="chargesForm.receivingBankAccount" placeholder="请输入收款银行账号" maxlength="100" show-word-limit readonly />
            </el-form-item>
            <el-form-item label="客户账户名称" prop="payerName">
              <el-input v-model="chargesForm.payerName" placeholder="请输入客户账户名称" maxlength="100" show-word-limit readonly />
            </el-form-item>
            <el-form-item label="客户开户行" prop="payerBank">
              <el-select v-model="chargesForm.payerBank" readonly placeholder="请输入客户开户行">
                <el-option v-for="dict in sys_bank_code" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="客户银行账户" prop="payerBankAccount">
              <el-input v-model="chargesForm.payerBankAccount" placeholder="请输入客户银行账户" maxlength="50" show-word-limit readonly />
            </el-form-item>
            <el-form-item label="总金额" prop="amount">
              <el-input-number v-model="chargesForm.amount" placeholder="请输入总金额" :precision="2" readonly style="width: 230px" />
            </el-form-item>
            <el-form-item label="剩余未匹配金额" prop="matchingBalance">
              <el-input-number
                v-model="chargesForm.matchingBalance"
                placeholder="请输入剩余未匹配金额"
                :precision="2"
                readonly
                style="width: 230px"
              />
            </el-form-item>
            <el-form-item label="虚拟户编码" prop="virtualAccount" style="margin-left: 10px">
              <el-input v-model="chargesForm.virtualAccount" placeholder="请输入虚拟户编码" maxlength="6" show-word-limit readonly />
            </el-form-item>
            <el-form-item label="到账日期" prop="arrivalDate">
              <el-date-picker
                v-model="chargesForm.arrivalDate"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择过期时间"
                style="width: 240px"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="缴费方式" prop="paymentMethod">
              <el-select v-model="chargesForm.paymentMethod" readonly placeholder="请输入缴费方式">
                <el-option
                  v-for="dict in sys_pay_method.filter((dict) => dict.value !== '01')"
                  :key="dict.value"
                  :label="dict.value + '-' + dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="银行记账码" prop="reconciliationCode">
              <el-input v-model="chargesForm.reconciliationCode" placeholder="请输入银行记账码" maxlength="50" disabled show-word-limit readonly />
            </el-form-item>
            <el-form-item label="缴费项目" prop="chargItems">
              <el-input v-model="chargesForm.chargItems" placeholder="请输入缴费项目" readonly />
            </el-form-item>
            <el-form-item label="是否特殊收费" clearable prop="isSpec">
              <el-switch v-model="chargesForm.isSpec" readonly size="large" active-value="Y" inactive-value="N" active-text="是" inactive-text="否" />
            </el-form-item>
            <el-form-item v-if="chargesForm.isSpec === 'Y'" label="特殊收费类型" prop="specType" style="margin-left: 140px">
              <el-select v-model="chargesForm.specType" readonly placeholder="特殊收费类型">
                <el-option v-for="dict in bfs_spec_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-row>
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="chargesForm.remark"
                  :rows="4"
                  style="width: 440px"
                  type="textarea"
                  maxlength="500"
                  show-word-limit
                  placeholder="请输入备注信息"
                  readonly
                >
                </el-input>
              </el-form-item>
            </el-row>
          </el-form>
        </el-card>
        <el-card shadow="hover">
          <template #header>
            <span>退费申请信息</span>
          </template>
          <el-form ref="payFormRef" :model="payForm" :inline="true" label-width="130px" label-position="left">
            <el-form-item v-if="false" label="ID" prop="payablesId">
              <el-input v-model="payForm.payablesId" readonly />
            </el-form-item>
            <el-form-item v-if="payForm.refundType === '1' || payForm.refundType === '2'" label="申请人账号" prop="appLicant">
              <el-input v-model="payForm.appLicant" placeholder="申请人" maxlength="100" show-word-limit disabled />
            </el-form-item>
            <el-form-item label="来源系统" prop="fromSystem">
              <el-select v-model="payForm.fromSystem" disabled placeholder="来源系统">
                <el-option v-for="dict in sys_from_system" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="申请机构" prop="manageCom">
              <el-select v-model="payForm.manageCom" readonly placeholder="申请机构" disabled>
                <el-option v-for="dict in sys_managecom" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="业务应付号码" prop="businessPaymentNumber">
              <el-input v-model="payForm.businessPaymentNumber" placeholder="业务应付号码" show-word-limit disabled />
            </el-form-item>
            <el-form-item label="保单号" prop="policyNumber">
              <el-input v-model="payForm.policyNumber" placeholder="保单号" show-word-limit readonly />
            </el-form-item>
            <el-form-item label="业务类型" prop="businessType">
              <el-select v-model="payForm.businessType" disabled placeholder="业务类型">
                <el-option v-for="dict in bls_business_type" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="业务号码" prop="businessNumber">
              <el-input v-model="payForm.businessNumber" placeholder="业务号码" show-word-limit disabled />
            </el-form-item>
            <el-form-item label="申请日期" prop="payableDate">
              <el-date-picker
                v-model="payForm.payableDate"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择过期时间"
                style="width: 240px"
                disabled
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="退费类型" prop="refundType">
              <el-select v-model="payForm.refundType" readonly placeholder="退费类型" disabled>
                <el-option v-for="dict in bls_refund_type" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="付费方式" prop="paymentMethod">
              <el-select v-model="payForm.paymentMethod" placeholder="付费方式" @change="handlePaymentMethodChange">
                <el-option
                  v-for="dict in sys_pay_method"
                  :key="dict.value"
                  :label="dict.value + '-' + dict.label"
                  :value="dict.value"
                  :disabled="!['01', '02'].includes(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="对公/私标记" prop="privateFlag">
              <el-select v-model="payForm.privateFlag" readonly placeholder="对公/私标记" @change="handlePaymentMethodChange">
                <el-option v-for="dict in bls_private_flag" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="收款人名称" prop="payeeName">
              <el-input
                v-model="payForm.payeeName"
                placeholder="收款人名称"
                style="width: 640px"
                disabled
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="收款人开户行" prop="bankCode">
              <el-select v-model="payForm.bankCode" readonly disabled placeholder="收款人开户行">
                <el-option v-for="dict in sys_bank_code" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="银行账号" prop="bankAccount">
              <el-input v-model="payForm.bankAccount" placeholder="银行账号" disabled show-word-limit />
            </el-form-item>
            <el-form-item label="支出虚拟户" prop="virtualAccount">
              <el-input v-model="payForm.virtualAccount" placeholder="支出虚拟户" disabled show-word-limit />
            </el-form-item>
            <el-form-item label="缴费项目" prop="chargItems">
              <el-input v-model="payForm.chargItems" placeholder="缴费项目" show-word-limit disabled />
            </el-form-item>
            <el-form-item label="付费金额" prop="amount">
              <el-input v-model="payForm.amount" placeholder="付费金额" show-word-limit disabled />
            </el-form-item>
            <el-form-item label="电财数据标记" prop="electricData">
              <el-input v-model="payForm.electricData" placeholder="电财数据标记" show-word-limit disabled />
            </el-form-item>
            <el-button v-hasPermi="['bls:payables:update']" icon="Check" type="danger" :disabled="!saveEnabled" @click="handleSave"> 保存 </el-button>
          </el-form>
        </el-card>

        <el-card v-if="attachmentList && attachmentList.length" shadow="hover">
          <template #header>
            <span>附件列表</span>
          </template>
          <el-table :data="attachmentList" stripe border style="width: 100%">
            <el-table-column prop="originalFilename" label="附件名称" min-width="180" show-overflow-tooltip />
            <el-table-column label="操作" width="100" align="center">
              <template #default="{ row }">
                <!-- 下载按钮 -->
                <el-button link type="primary" @click="downloadAttachment(row)">下载</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-card>
          <el-form ref="formRef" :model="form" :inline="true" label-position="left" label-width="130px">
            <!--            <el-form-item label="审核结论" prop="auditResult">-->
            <!--              <el-select v-model="form.auditResult" clearable placeholder="请输入审核结论">-->
            <!--                <el-option v-for="dict in bls_payables_aduit" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <el-row>
              <el-form-item label="审核结论描述" prop="auditDescribe">
                <el-input v-model="form.auditDescribe" :rows="4" style="width: 440px" type="textarea" placeholder="请输入审核结论描述" clearable>
                </el-input>
              </el-form-item>
            </el-row>
            <el-form-item>
              <el-button v-hasPermi="['bls:payables:audit']" icon="Check" type="primary" @click="handleAuditPass">通 过</el-button>
              <el-button v-hasPermi="['bls:payables:audit']" icon="Check" type="primary" @click="handleAuditFail">不通过</el-button>
              <el-button icon="Check" type="primary" @click="handleClose">关闭</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
  </div>
</template>
<script setup name="PayAblesAduitDetail" lang="ts">
import { auditPayables, getPayAduitDetail, savePayAduitDetail } from '@/api/bls/payables';
import { RouteLocationNormalized } from 'vue-router';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));
const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'));
const { sys_from_system } = toRefs<any>(proxy?.useDict('sys_from_system'));
const { bls_refund_type } = toRefs<any>(proxy?.useDict('bls_refund_type'));
const { sys_bank_code } = toRefs<any>(proxy?.useDict('sys_bank_code'));
const { sys_pay_method } = toRefs<any>(proxy?.useDict('sys_pay_method'));
const { bfs_spec_type } = toRefs<any>(proxy?.useDict('bfs_spec_type'));
const { bls_business_type } = toRefs<any>(proxy?.useDict('bls_business_type'));
const { bls_private_flag } = toRefs<any>(proxy?.useDict('bls_private_flag'));
// 1. 添加响应式变量存储附件列表
const attachmentList = ref<TempRefundAttachment[]>([]);

const loading = ref(true);
const showSearch = ref(true);
const payForm = ref({});
const chargesForm = ref({});
const form = ref({});
const payFormRef = ref<ElFormInstance>();
const chargesFormRef = ref<ElFormInstance>();

// 新增响应式变量
const saveEnabled = ref(false); // 保存按钮状态
const originalPaymentMethod = ref(''); // 原始付费方式
const originalPrivateFlag = ref(''); // 原始对公/私标记


// 监听付费方式变化
const handlePaymentMethodChange = () => {
  saveEnabled.value = originalPaymentMethod.value !== payForm.value.paymentMethod || originalPrivateFlag.value !== payForm.value.privateFlag;
};

// 保存付费方式
const handleSave = async () => {
  if (!saveEnabled.value) return;

  try {
    const res = await savePayAduitDetail(payForm.value);

    if (res.code === 200) {
      proxy?.$modal.msgSuccess('付费方式更新成功');
      // 更新原始值引用
      originalPaymentMethod.value = payForm.value.paymentMethod;
      originalPrivateFlag.value = payForm.value.privateFlag;
      saveEnabled.value = false;
    }
  } catch (error) {

  }
};

const loadingPage = async (payablesId: string) => {
  loading.value = true;
  try {
    const res = await getPayAduitDetail({ payablesId });
    if (res.code === 200) {
      Object.assign(payForm.value, res.data.payData);
      Object.assign(chargesForm.value, res.data.chargesData);
      originalPaymentMethod.value = payForm.value.paymentMethod;
      originalPrivateFlag.value = payForm.value.privateFlag;
      // ↓↓↓ 新增代码：处理附件列表 ↓↓↓
      if (res.data.attachementList) {
        // 确保是数组且不为空
        attachmentList.value = Array.isArray(res.data.attachementList) ? res.data.attachementList : [];
      } else {
        attachmentList.value = [];
      }
      // ↑↑↑ 新增代码：处理附件列表 ↑↑↑
    }
  } catch (error) {

  } finally {
    loading.value = false;
  }
};
// 3. 添加附件下载方法
const downloadAttachment = (attachment: TempRefundAttachment) => {
  // 1. 添加验证逻辑：打印ossObjectKey值,调试好，删掉

  // 2. 修复参数引用错误（原代码错用函数名代替参数名）
  if (attachment.ossObjectKey) {
    proxy?.$download.oss(attachment.ossObjectKey); // ✅ 正确取用参数属性
  } else {

    proxy?.$modal.msgError('附件暂不可下载，请联系管理员');
  }
};
const handleAuditPass = async () => {
  await proxy.$modal.confirm('确定要 审核通过 本次申请吗？若修改付费方式，请点击《保存》！审核通过后会直接推送资金系统');
  loading.value = true;
  const data = {
    ids: [payForm.value.payablesId],
    auditResult: 'Y'
  };
  try {
    const res = await auditPayables(data);
    if (res.code === 200) {
      proxy.$modal.msgSuccess('审核成功');
      handleClose();
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

const handleAuditFail = async () => {
  await proxy.$modal.confirm('确定要 拒绝 本次申请吗？返回业务系统失败原因为本次录入的审核结论描述');
  loading.value = true;
  const data = {
    ids: [payForm.value.payablesId],
    auditResult: 'N',
    auditDescribe: form.value.auditDescribe
  };
  try {
    const res = await auditPayables(data);
    if (res.code === 200) {
      proxy.$modal.msgSuccess('审核成功');
      handleClose();
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

/** 关闭按钮 */
const handleClose = () => {
  const obj: RouteLocationNormalized = {
    fullPath: '',
    hash: '',
    matched: [],
    payForm: {},
    chargesForm: {},
    form: {},
    path: '/bls/pay/PayablesAduit'
  };
  proxy?.$tab.closeOpenPage(obj);
};

onMounted(() => {
  const route = useRoute();
  const payablesId = route.query.payablesId;
  if (payablesId) {
    loadingPage(typeof payablesId === 'string' ? payablesId : payablesId.toString());
  } else {
    loading.value = false;
    proxy.$modal.msgError('参数接收失败，请检查路由参数');
  }
});
</script>

<style scoped lang="scss"></style>
