<template>
  <div class="app-container">
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryRef" class="custom-search-form">
        <div class="search-row">
          <div class="search-item">
            <span class="search-label">联系人</span>
            <el-input v-model="queryParams.contactPerson" placeholder="请输入联系人" clearable style="width: 250px;" />
          </div>
          <div class="search-item">
            <span class="search-label">电话</span>
            <el-input v-model="queryParams.telephone" placeholder="请输入电话" clearable style="width: 220px;" />
          </div>
          <div class="search-item">
            <span class="search-label">到期日期</span>
            <el-date-picker v-model="queryParams.dueDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择" style="width: 220px;" />
          </div>
          <div class="search-item">
            <span class="search-label">是否欠款</span>
            <el-select v-model="queryParams.izArrears" placeholder="请选择" clearable style="width: 220px;">
               <el-option label="是" :value="1" />
               <el-option label="否" :value="0" />
            </el-select>
          </div>
        </div>
        <div class="search-btns">
          <el-button icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
        </div>
      </el-form>
    </el-card>

    <div class="table-heading">应收账款信息列表</div>

    <el-card shadow="never" class="table-card">
      <el-table v-loading="loading" :data="dataList" border class="standard-table" size="small">
        <el-table-column label="产品名称" align="center" prop="productName" min-width="180" show-overflow-tooltip />
        <el-table-column label="开票日期" align="center" prop="invoiceDate" width="110">
          <template #default="scope">
            {{ formatDate(scope.row.invoiceDate) }}
          </template>
        </el-table-column>
        <el-table-column label="发票号码" align="center" prop="invoiceNumber" width="180" show-overflow-tooltip />
        <el-table-column label="发票金额" align="center" prop="invoiceAmount" width="120" sortable />
        <el-table-column label="账单周期" align="center" prop="billingCycle" width="100">
          <template #default="scope">
            {{ scope.row.billingCycle ? scope.row.billingCycle + '天' : '' }}
          </template>
        </el-table-column>
        <el-table-column label="到期日期" align="center" prop="dueDate" width="110">
          <template #default="scope">
            {{ formatDate(scope.row.dueDate) }}
          </template>
        </el-table-column>
        <el-table-column label="逾期天数" align="center" prop="overdueDays" width="90" />
        <el-table-column label="已付金额" align="center" prop="paidAmount" width="120" />
        <el-table-column label="是否欠款" align="center" prop="izArrears" width="90">
          <template #default="scope">
             <el-tag :type="scope.row.izArrears === 1 ? 'danger' : 'success'" plain>{{ scope.row.izArrears === 1 ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="逾期余额" align="center" prop="overdueBalance" width="120" />
        <el-table-column label="单位名称" align="center" prop="companyName" min-width="200" show-overflow-tooltip />
        <el-table-column label="联系人" align="center" width="110">
          <template #default="scope">
            {{ scope.row.contactPersonName || scope.row.contactPerson }}
          </template>
        </el-table-column>
        <el-table-column label="电话" align="center" prop="telephone" width="130" />
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </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="title" v-model="open" width="800px" append-to-body @closed="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" style="padding: 10px 0;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称：" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票日期：" prop="invoiceDate">
               <el-date-picker v-model="form.invoiceDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发票号码：" prop="invoiceNumber">
              <el-input v-model="form.invoiceNumber" placeholder="请输入发票号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票金额：" prop="invoiceAmount">
              <el-input-number v-model="form.invoiceAmount" :precision="2" :min="0" placeholder="请输入发票金额" style="width: 100%" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账单周期：" prop="billingCycle">
              <el-input-number v-model="form.billingCycle" :min="0" placeholder="请输入天数" style="width: 100%" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到期日期：" prop="dueDate">
              <el-date-picker v-model="form.dueDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="逾期天数：" prop="overdueDays">
              <el-input-number v-model="form.overdueDays" :min="0" placeholder="请输入逾期天数" style="width: 100%" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已付金额：" prop="paidAmount">
              <el-input-number v-model="form.paidAmount" :precision="2" :min="0" placeholder="请输入已付金额" style="width: 100%" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否欠款：" prop="izArrears">
              <el-radio-group v-model="form.izArrears">
                <el-radio :value="1">是</el-radio>
                <el-radio :value="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="逾期余额：" prop="overdueBalance">
              <el-input-number v-model="form.overdueBalance" :precision="2" :min="0" placeholder="请输入逾期余额" style="width: 100%" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位名称：" prop="companyName">
              <el-input v-model="form.companyName" placeholder="请输入单位名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人：" prop="contactPerson">
              <el-select v-model="form.contactPerson" placeholder="请选择联系人" style="width: 100%" filterable>
                <el-option v-for="item in userOptions" :key="item.staffId || item.userId"
                  :label="item.staffName || item.nickName" :value="item.staffName || item.nickName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
             <el-form-item label="电话：" prop="telephone">
               <el-input v-model="form.telephone" placeholder="请输入电话" />
             </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确认</el-button>
          <el-button @click="open = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AccountsReceivable">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { listAccountsReceivable, addAccountsReceivable, updateAccountsReceivable, delAccountsReceivable } from '@/api/saleManage/accountsReceivable/index';
import { listComStaff } from "@/api/system/comStaff/index";

const proxy = getCurrentInstance().proxy;

const loading = ref(false);
const total = ref(0);
const dataList = ref([]);
const open = ref(false);
const title = ref('');
const formRef = ref(null);
const userOptions = ref([]);

/** 查询参数 */
const queryParams = reactive({
  pageNum: 1, pageSize: 10,
  contactPerson: undefined, telephone: undefined, dueDate: undefined, izArrears: undefined
});

/** 初始表单数据 */
const initFormData = () => ({
  id: undefined,
  productName: '',
  invoiceDate: '',
  invoiceNumber: '',
  invoiceAmount: undefined,
  billingCycle: undefined,
  dueDate: '',
  overdueDays: undefined,
  paidAmount: undefined,
  izArrears: 0,
  overdueBalance: undefined,
  companyName: '',
  contactPerson: '',
  telephone: ''
});

const form = ref(initFormData());

/** 表单校验规则 */
const rules = {
  productName: [{ required: true, message: "产品名称不能为空", trigger: "blur" }],
  invoiceNumber: [{ required: true, message: "发票号码不能为空", trigger: "blur" }],
  invoiceAmount: [{ required: true, message: "发票金额不能为空", trigger: "blur" }],
  companyName: [{ required: true, message: "单位名称不能为空", trigger: "blur" }],
  contactPerson: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
  telephone: [{ required: true, message: "电话不能为空", trigger: "blur" }]
};

/** 日期格式化 */
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  return dateStr.substring(0, 10);
};

/** 获取列表数据 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listAccountsReceivable(queryParams);
    dataList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (err) {
    console.error('获取应收账款列表失败', err);
    dataList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

/** 搜索 */
const handleQuery = () => { queryParams.pageNum = 1; getList(); };

/** 重置搜索 */
const resetQuery = () => { proxy.resetForm("queryRef"); handleQuery(); };

/** 新增 */
const handleAdd = () => {
  form.value = initFormData();
  title.value = "新增应收账款";
  open.value = true;
};

/** 编辑 */
const handleEdit = (row) => {
  form.value = { ...row };
  title.value = "编辑应收账款";
  open.value = true;
};

/** 重置表单 */
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

/** 提交表单 */
const submitForm = () => {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (valid) {
      try {
        if (form.value.id) {
          await updateAccountsReceivable(form.value);
          proxy.$modal.msgSuccess("修改成功");
        } else {
          await addAccountsReceivable(form.value);
          proxy.$modal.msgSuccess("新增成功");
        }
        open.value = false;
        getList();
      } catch (err) {
        console.error('保存应收账款失败', err);
      }
    }
  });
};

/** 删除 */
const handleDelete = (row) => {
  proxy.$modal.confirm(`确认删除该条应收账款记录吗？`).then(async () => {
    try {
      await delAccountsReceivable(row.id);
      proxy.$modal.msgSuccess("删除成功");
      getList();
    } catch (err) {
      console.error('删除应收账款失败', err);
    }
  });
};

/** 获取用户列表 */
const getUserList = () => {
  listComStaff({ pageSize: 1000 }).then(res => {
    userOptions.value = res.rows || res.data || [];
  });
};

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

<style scoped lang="scss">
.app-container { padding: 20px; background-color: #f7f9fb; min-height: calc(100vh - 84px); }

.search-card { 
  margin-bottom: 10px; border: none; background: #fff; border-radius: 8px; padding: 10px 0;
}

.custom-search-form {
  padding: 0 10px;
}

.search-row {
  display: flex; flex-wrap: wrap; gap: 45px; align-items: center; margin-bottom: 20px;
}

.search-item {
  display: flex; align-items: center; gap: 12px;
  .search-label { font-size: 14px; color: #333; white-space: nowrap; }
  :deep(.el-input__wrapper), :deep(.el-select__wrapper) {
    box-shadow: 0 0 0 1px #e4e7ed inset;
    &:hover { box-shadow: 0 0 0 1px #409eff inset; }
  }
}

.search-btns { 
  display: flex; gap: 12px; justify-content: flex-start; align-items: center;
  :deep(.el-button) {
    height: 32px; padding: 0 16px; font-weight: 500; border-radius: 4px;
  }
  :deep(.el-button--default) {
    color: #333; border-color: #dcdfe6;
    &:hover { border-color: #409eff; color: #409eff; }
  }
  :deep(.el-button--primary) {
    background-color: #409eff; border-color: #409eff; color: #fff !important;
    &:hover { background-color: #66b1ff; border-color: #66b1ff; color: #fff !important; }
  }
}

.table-heading {
  font-size: 14px; font-weight: 400; color: var(--el-text-color-primary); padding: 0 4px; margin: 12px 0 16px;
}

.table-card { border: none; }
.standard-table {
  :deep(th.el-table__cell) { background-color: var(--el-fill-color-light) !important; color: var(--el-text-color-regular); font-weight: 600; font-size: 13px; }
  :deep(td.el-table__cell) { font-size: 13px; color: var(--el-text-color-primary); }
}

.dialog-footer { display: flex; justify-content: flex-end; gap: 15px; }

:deep(.el-radio-group) {
  display: flex;
  gap: 30px;
}
</style>
