<template>
  <div class="invoice-manage-container">
    <div class="page-title"><i class="title-bar"></i><span>发票管理</span></div>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input v-model="queryParams.keyword" placeholder="搜索" style="width: 200px" clearable>
        <template #prefix
          ><el-icon><Search /></el-icon
        ></template>
      </el-input>
      <el-select v-model="queryParams.searchType" placeholder="账户名称" style="width: 120px">
        <el-option label="账户名称" value="accountName" />
        <el-option label="发票抬头" value="invoiceTitle" />
        <el-option label="纳税人识别号" value="taxNo" />
      </el-select>
      <div class="search-right"><el-button type="danger" @click="handleAdd">新增开票信息</el-button></div>
    </div>
    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%" :resizable="false">
      <el-table-column prop="bankName" label="开户银行" width="140" show-overflow-tooltip :resizable="false" />
      <el-table-column prop="bankAccount" label="开户账户" width="140" :resizable="false" />
      <el-table-column prop="taxId" label="纳税人识别号" width="160" :resizable="false" />
      <el-table-column prop="address" label="地址" min-width="140" show-overflow-tooltip :resizable="false" />
      <el-table-column prop="phone" label="电话" width="120" :resizable="false" />
      <el-table-column label="操作" width="120" fixed="right" :resizable="false">
        <template #default="{ row }">
          <div style="display: flex; gap: 8px; justify-content: center">
            <el-button type="primary" link @click="handleEdit(row)">修改</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-wrap">
      <span class="total-text">共计 {{ total }} 条</span>
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="prev, pager, next, sizes, jumper"
        @size-change="handleQuery"
        @current-change="handleQuery"
      />
    </div>
    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="550px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="发票抬头" prop="invoiceTitle"
          ><el-input v-model="form.invoiceTitle" placeholder="请输入发票抬头" disabled
        /></el-form-item>
        <el-form-item label="纳税人识别号" prop="taxNo"><el-input v-model="form.taxNo" placeholder="请输入纳税人识别号" /></el-form-item>
        <el-form-item label="开户银行" prop="bankName">
          <el-select v-model="form.bankName" placeholder="请选择开户银行" clearable filterable style="width: 100%">
            <el-option v-for="bank in bankList" :key="bank.id" :label="bank.bnName" :value="bank.bnName" />
          </el-select>
        </el-form-item>
        <el-form-item label="开户账户" prop="bankAccount"><el-input v-model="form.bankAccount" placeholder="请输入开户账户" /></el-form-item>
        <el-form-item label="地址" prop="address"><el-input v-model="form.address" placeholder="请输入地址" /></el-form-item>
        <el-form-item label="电话" prop="phone"><el-input v-model="form.phone" placeholder="请输入电话" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Phone, Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getEnterpriseInfo } from '@/api/pc/enterprise';
import { getInvoiceList, addInvoice, updateInvoice, deleteInvoice } from '@/api/pc/enterprise';
import { getBankList } from '@/api/pc/bank/bank';

const dialogVisible = ref(false);
const dialogTitle = ref('新增开票信息');
const formRef = ref();
const editingId = ref<number | null>(null);
const total = ref(0);
const invoiceTopic = ref('');

const queryParams = reactive({ pageNum: 1, pageSize: 10, keyword: '', searchType: 'accountName' });
const form = reactive({ invoiceTitle: '', taxNo: '', bankName: '', bankAccount: '', address: '', phone: '', bankId: null, bankCode: '' });
const rules = {
  // invoiceTitle: [{ required: true, message: '请输入发票抬头', trigger: 'blur' }],
  taxNo: [{ required: true, message: '请输入纳税人识别号', trigger: 'blur' }],
  bankName: [{ required: true, message: '请输入开户银行', trigger: 'blur' }],
  bankAccount: [{ required: true, message: '请输入开户账户', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }]
};

const tableData = ref([]);
const bankList = ref([]);

// 加载银行列表
const loadBankList = async () => {
  try {
    const res = await getBankList();
    if (res.code === 200) {
      bankList.value = res.rows || [];
    }
  } catch (error) {
    console.error('加载银行列表失败:', error);
  }
};

// 加载发票列表
const loadInvoiceList = async () => {
  try {
    const res = await getInvoiceList(queryParams);
    if (res.code === 200) {
      tableData.value = res.rows || [];
      total.value = res.total || 0;
    }
  } catch (error) {
    console.error('加载发票列表失败:', error);
    ElMessage.error('加载发票列表失败');
  }
};
// 加载企业信息
const loadEnterpriseInfo = async () => {
  try {
    const res = await getEnterpriseInfo();
    if (res.code === 200 && res.data) {
      const data = res.data;
      invoiceTopic.value = data.invoiceTop;
    }
  } catch (error) {
    console.error('加载企业信息失败:', error);
    ElMessage.error('加载企业信息失败');
  }
};

onMounted(() => {
  loadInvoiceList();
  loadBankList();
});
const handleQuery = () => {
  loadInvoiceList();
};
const resetForm = () => {
  form.invoiceTitle = '';
  form.taxNo = '';
  form.bankName = '';
  form.bankAccount = '';
  form.address = '';
  form.phone = '';
  form.bankId = null;
  form.bankCode = '';
  editingId.value = null;
};
const handleAdd = () => {
  resetForm();
  dialogTitle.value = '新增开票信息';
  form.invoiceTitle = invoiceTopic.value || '';
  dialogVisible.value = true;
};
const handleEdit = (row: any) => {
  editingId.value = row.id;
  form.invoiceTitle = invoiceTopic.value || '';
  form.taxNo = row.taxId;
  form.bankName = row.bankName;
  form.bankAccount = row.bankAccount;
  form.address = row.address;
  form.phone = row.phone;
  form.bankId = row.bankId;
  form.bankCode = row.bankCode || '';
  dialogTitle.value = '编辑开票信息';
  dialogVisible.value = true;
};
const handleSave = async () => {
  const valid = await formRef.value?.validate();
  if (!valid) return;
  try {
    const data: any = {
      taxId: form.taxNo,
      bankName: form.bankName,
      bankAccount: form.bankAccount,
      address: form.address,
      phone: form.phone,
      bankId: form.bankId || 0,
      bankCode: form.bankCode || 'DEFAULT'
    };
    console.log('发送的数据:', data);
    if (editingId.value) {
      data.id = editingId.value;
      await updateInvoice(data);
    } else {
      await addInvoice(data);
    }
    ElMessage.success(editingId.value ? '修改成功' : '新增成功');
    dialogVisible.value = false;
    loadInvoiceList();
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('操作失败');
  }
};
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该开票信息吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(
    async () => {
      try {
        await deleteInvoice([row.id]);
        ElMessage.success('删除成功');
        loadInvoiceList();
      } catch (error) {
        ElMessage.error('删除失败');
      }
    }
  );
};
onMounted(() => {
  loadEnterpriseInfo();
});
</script>

<style scoped lang="scss">
.invoice-manage-container {
  padding: 20px;
  background: #fff;
  min-height: 100%;
  flex: 1;
}
.page-title {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
}
.title-bar {
  display: inline-block;
  width: 3px;
  height: 16px;
  background: #e60012;
  border-radius: 2px;
}
.search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
  .search-right {
    flex: 1;
    display: flex;
    justify-content: flex-end;
  }
}
.pagination-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  .total-text {
    font-size: 14px;
    color: #666;
  }
}
</style>
