<template>
  <!-- 新增/编辑发票抽屉 -->
  <el-drawer v-model="drawer.visible" size="75%" direction="rtl" :before-close="handleDrawerClose" :close-on-click-modal="true">
    <template #header>
      <div class="drawer-header">
        <span class="order-title">{{ drawer.title }}</span>
      </div>
    </template>

    <div class="drawer-content">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <!-- 基本信息 -->
        <el-divider content-position="left">
          <span style="color: #409eff; font-weight: 600">基本信息</span>
        </el-divider>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="客户名称" prop="customerId">
              <el-select
                v-model="form.customerId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入客户名称"
                :remote-method="remoteSearchCustomer"
                :loading="customerLoading"
                clearable
                style="width: 100%"
                @change="handleCustomerChange"
              >
                <el-option v-for="item in customerOptions" :key="item.id" :label="item.customerName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开票金额" prop="invoiceAmount">
              <el-input v-model="form.invoiceAmount" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开票日期" prop="invoiceTime">
              <el-date-picker v-model="form.invoiceTime" type="date" placeholder="请选择开票日期" style="width: 100%" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 账单列表 -->
        <el-divider content-position="left">
          <span style="color: #409eff; font-weight: 600">账单列表</span>
        </el-divider>
        <div class="table-actions" style="margin-bottom: 15px">
          <el-button type="primary" icon="Plus" @click="handleSelectStatement">选择对账单</el-button>
        </div>

        <el-table :data="form.detailList" border style="width: 100%; margin-bottom: 20px">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="statementOrderNo" label="对账单编号" min-width="150" align="center" />
          <el-table-column prop="statementAmount" label="对账金额" min-width="120" align="center" />
          <el-table-column prop="orderNo" label="订单编号" min-width="150" align="center" />
          <el-table-column prop="orderAmount" label="金额" min-width="120" align="center" />
          <el-table-column prop="orderTime" label="下单日期" min-width="120" align="center" />
          <el-table-column prop="userName" label="下单人" min-width="100" align="center" />
          <el-table-column prop="userDept" label="部门" min-width="120" align="center" />
        </el-table>

        <!-- 商品清单 -->
        <el-divider content-position="left">
          <span style="color: #409eff; font-weight: 600">商品清单</span>
        </el-divider>

        <el-table :data="pagedProductList" border style="width: 100%; margin-bottom: 20px">
          <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center"
            :index="(index) => (productPage.pageNum - 1) * productPage.pageSize + index + 1"
          />
          <el-table-column prop="orderNo" label="订单编号" min-width="120" align="center" />
          <el-table-column prop="productNo" label="商品编号" min-width="120" align="center" />
          <el-table-column prop="itemName" label="商品名称" min-width="180" align="center" />
          <el-table-column prop="unitName" label="单位" align="center" />
          <el-table-column prop="quantity" label="数量" align="center" />
          <el-table-column prop="unitPrice" label="单价" align="center">
            <template #default="scope">
              {{ scope.row.unitPrice ? Number(scope.row.unitPrice).toFixed(2) : '0.00' }}
            </template>
          </el-table-column>
          <el-table-column label="小计" align="center">
            <template #default="scope">
              {{ (Number(scope.row.quantity || 0) * Number(scope.row.unitPrice || 0)).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-if="form.productList && form.productList.length > 0"
          v-model:current-page="productPage.pageNum"
          v-model:page-size="productPage.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumpers"
          :total="productPage.total"
          @size-change="handleProductSizeChange"
          @current-change="handleProductCurrentChange"
          style="margin-top: 15px"
        />

        <!-- 发票列表 -->
        <el-divider content-position="left">
          <span style="color: #409eff; font-weight: 600">发票列表</span>
        </el-divider>

        <div class="table-actions" style="margin-bottom: 15px">
          <el-button type="primary" icon="Plus" @click="handleAddInvoice">新增发票</el-button>
        </div>

        <!-- 发票表格 -->
        <el-table :data="invoiceList" border style="width: 100%; margin-bottom: 20px">
          <el-table-column prop="invoiceType" label="发票类型" min-width="120" align="center">
            <template #default="scope">
              <dict-tag :options="invoice_type" :value="scope.row.invoiceType" />
            </template>
          </el-table-column>
          <el-table-column prop="invoiceDate" label="开票日期" min-width="120" align="center" />
          <el-table-column prop="invoiceCode" label="发票代码" min-width="150" align="center" />
          <el-table-column prop="invoiceAmount" label="发票金额" min-width="120" align="center">
            <template #default="scope">
              {{ Number(scope.row.invoiceAmount || 0).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center" />
          <el-table-column label="操作" width="150" align="center">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleEditInvoice(scope.row, scope.$index)">编辑</el-button>
              <el-button link type="danger" size="small" @click="handleDeleteInvoice(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleDrawerClose(() => (drawer.visible = false))">取消</el-button>
        <el-button type="primary" :loading="buttonLoading" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 对账单选择抽屉 -->
  <StatementOrderDrawer ref="statementOrderDrawerRef" @success="handleStatementSelected" />

  <!-- 文件选择器 -->
  <FileSelector v-model="fileSelectorVisible" :multiple="true" :allowed-types="[1, 2, 3, 4, 5]" title="选择发票附件" @confirm="handleFileSelected" />

  <!-- 新增发票对话框 -->
  <AddInvoiceDialog ref="addInvoiceDialogRef" @success="handleInvoiceAdded" />
</template>

<script setup name="InvoiceAddDrawer" lang="ts">
import { addStatementInvoice, updateStatementInvoice } from '@/api/bill/statementInvoice';
import { StatementInvoiceForm } from '@/api/bill/statementInvoice/types';
import { getListBycustomerName } from '@/api/customer/customerFile/customerInfo';
import { CustomerInfoVO } from '@/api/customer/customerFile/customerInfo/types';
import { StatementOrderVO } from '@/api/bill/statementOrder/types';
import StatementOrderDrawer from './statementOrderDrawer.vue';
import FileSelector from '@/components/FileSelector/index.vue';
import AddInvoiceDialog from './addInvoiceDialog.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { invoice_type } = toRefs<any>(proxy?.useDict('invoice_type'));
const initFormData: StatementInvoiceForm = {
  id: undefined,
  statementInvoiceNo: undefined,
  customerId: undefined,
  customerNo: undefined,
  customerName: undefined,
  invoiceAmount: undefined,
  invoiceStatus: undefined,
  invoiceTime: undefined,
  rejectRemark: undefined,
  remark: undefined,
  detailList: [],
  productList: [],
  invoiceList: []
};

const formRef = ref<ElFormInstance>();
const buttonLoading = ref(false);
const form = ref<StatementInvoiceForm>({ ...initFormData });

const rules = reactive({
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  invoiceTime: [{ required: true, message: '请选择开票日期', trigger: 'change' }]
} as any);

const fileList = ref<any[]>([]);

const productPage = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

const drawer = reactive<DialogOption>({
  visible: false,
  title: '新增发票'
});

const isEdit = ref(false);

const customerLoading = ref(false);
const customerOptions = ref<CustomerInfoVO[]>([]);
const statementOrderDrawerRef = ref<any>();
const fileSelectorVisible = ref(false);
const addInvoiceDialogRef = ref<any>();
const currentSelectedStatements = ref<StatementOrderVO[]>([]);
const invoiceList = ref<any[]>([]); // 发票列表
const editingInvoiceIndex = ref<number>(-1);

/** 计算当前页的商品列表 */
const pagedProductList = computed(() => {
  const start = (productPage.pageNum - 1) * productPage.pageSize;
  const end = start + productPage.pageSize;
  return form.value.productList?.slice(start, end) || [];
});

/** 打开新增/编辑发票抽屉 */
const open = (id?: string | number, data?: StatementInvoiceForm) => {
  reset();

  if (id && data) {
    // 编辑模式
    isEdit.value = true;
    drawer.title = '编辑发票';
    Object.assign(form.value, data);

    // 将客户信息添加到下拉选项中，以便回显
    if (data.customerId && data.customerName) {
      customerOptions.value = [
        {
          id: data.customerId,
          customerName: data.customerName,
          customerNo: data.customerNo || ''
        } as CustomerInfoVO
      ];
    }

    // 解析附件地址并回显附件列表
    if (data.annexAddress) {
      const urls = data.annexAddress.split(',').filter((url) => url.trim());
      fileList.value = urls.map((url, index) => {
        const fileName = url.split('/').pop() || `附件${index + 1}`;
        return {
          name: fileName,
          url: url.trim(),
          id: undefined
        };
      });
    }

    // 设置商品列表分页总数
    if (data.productList && data.productList.length > 0) {
      productPage.total = data.productList.length;
    }

    // 回显发票列表
    if (data.invoiceList && data.invoiceList.length > 0) {
      invoiceList.value = data.invoiceList;
    }
  } else {
    // 新增模式
    isEdit.value = false;
    drawer.title = '新增发票';
  }

  drawer.visible = true;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  fileList.value = [];
  invoiceList.value = [];
  editingInvoiceIndex.value = -1;
  productPage.pageNum = 1;
  productPage.pageSize = 10;
  productPage.total = 0;
  customerOptions.value = [];
  currentSelectedStatements.value = [];
  formRef.value?.clearValidate();
};

/** 远程搜索客户 */
const remoteSearchCustomer = async (query: string) => {
  if (query) {
    customerLoading.value = true;
    try {
      const res = await getListBycustomerName(query);
      customerOptions.value = res.data || [];
    } catch (error) {
      console.error('搜索客户失败:', error);
    } finally {
      customerLoading.value = false;
    }
  } else {
    customerOptions.value = [];
  }
};

/** 客户变更 */
const handleCustomerChange = (value: string | number) => {
  const selectedCustomer = customerOptions.value.find((customer) => customer.id === value);
  if (selectedCustomer) {
    form.value.customerId = selectedCustomer.id;
    form.value.customerNo = selectedCustomer.customerNo;
    form.value.customerName = selectedCustomer.customerName;

    // 清空之前选择的对账单和商品
    form.value.detailList = [];
    form.value.productList = [];
    form.value.invoiceAmount = undefined;
    productPage.total = 0;
    currentSelectedStatements.value = [];
  }
};

/** 选择对账单 */
const handleSelectStatement = () => {
  if (!form.value.customerId) {
    proxy?.$modal.msgWarning('请先选择客户');
    return;
  }

  // 使用nextTick确保组件已挂载
  nextTick(() => {
    if (statementOrderDrawerRef.value && typeof statementOrderDrawerRef.value.open === 'function') {
      statementOrderDrawerRef.value.open(form.value.customerId, currentSelectedStatements.value);
    } else {
      console.error('对账单抽屉组件未正确加载');
    }
  });
};

/** 对账单选择成功回调 */
const handleStatementSelected = (data: any) => {
  const { statements, details, products } = data;

  if (statements && statements.length > 0) {
    let totalAmount = 0;

    // 保存当前选中的对账单
    currentSelectedStatements.value = statements;

    // 清空现有数据
    form.value.detailList = [];
    form.value.productList = [];

    // 填充发票明细
    if (details && details.length > 0) {
      form.value.detailList = details.map((detail: any) => ({
        statementOrderId: detail.statementOrderId,
        statementOrderNo: detail.statementOrderNo || '',
        statementAmount: detail.statementAmount || 0,
        orderId: detail.orderId || '',
        orderNo: detail.orderNo || '',
        orderAmount: detail.amount || 0,
        signingDate: detail.signingDate || '',
        orderTime: detail.orderTime || '',
        userDept: detail.userDept || '',
        userName: detail.userName || ''
      }));

      // 计算总金额
      totalAmount = details.reduce((sum: number, detail: any) => sum + Number(detail.amount || 0), 0);
    }

    // 设置开票金额
    form.value.invoiceAmount = totalAmount;

    // 直接使用传递过来的产品列表
    if (products && products.length > 0) {
      form.value.productList = products;
      productPage.total = products.length;
    }
  }
};

/** 打开文件选择器 */
const handleOpenFileSelector = () => {
  fileSelectorVisible.value = true;
};

/** 文件选择完成 */
const handleFileSelected = (files: any[]) => {
  if (files && files.length > 0) {
    files.forEach((file) => {
      fileList.value.push({
        name: file.fileName || file.name,
        url: file.fileUrl || file.url,
        id: file.id
      });
    });
    form.value.annexAddress = fileList.value.map((f) => f.url || f.name).join(',');
  }
  fileSelectorVisible.value = false;
};

/** 删除文件 */
const handleRemoveFile = (index: number) => {
  fileList.value.splice(index, 1);
  form.value.annexAddress = fileList.value.map((f) => f.url || f.name).join(',');
};

/** 下载文件 */
const handleDownloadFile = async (file: any) => {
  if (!file.url) {
    proxy?.$modal.msgWarning('文件地址不存在');
    return;
  }

  try {
    const response = await fetch(file.url);
    const blob = await response.blob();
    const blobUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = blobUrl;
    link.download = file.name || '附件';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(blobUrl);
  } catch (error) {
    console.error('下载失败:', error);
    const link = document.createElement('a');
    link.href = file.url;
    link.download = file.name || '附件';
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
};

/** 预览文件 */
const handlePreviewFile = (file: any) => {
  if (!file.url) {
    proxy?.$modal.msgWarning('文件地址不存在');
    return;
  }
  window.open(file.url, '_blank');
};

/** 产品分页大小改变 */
const handleProductSizeChange = (val: number) => {
  productPage.pageSize = val;
};

/** 产品分页页码改变 */
const handleProductCurrentChange = (val: number) => {
  productPage.pageNum = val;
};

/** 新增发票 */
const handleAddInvoice = () => {
  editingInvoiceIndex.value = -1;
  addInvoiceDialogRef.value?.open({
    invoiceCompanyName: form.value.customerName
  });
};

/** 发票添加成功 */
const handleInvoiceAdded = (invoiceData: any) => {
  // 编辑：更新当前行；新增：追加
  if (editingInvoiceIndex.value >= 0 && editingInvoiceIndex.value < invoiceList.value.length) {
    const prev = invoiceList.value[editingInvoiceIndex.value] || {};
    invoiceList.value.splice(editingInvoiceIndex.value, 1, {
      ...prev,
      ...invoiceData,
      id: prev.id
    });
  } else {
    invoiceList.value.push({
      ...invoiceData,
      id: invoiceData?.id ?? Date.now()
    });
  }
  editingInvoiceIndex.value = -1;
};

/** 编辑发票 */
const handleEditInvoice = (invoice: any, index: number) => {
  editingInvoiceIndex.value = index;
  addInvoiceDialogRef.value?.open({
    ...invoice,
    invoiceCompanyName: invoice?.invoiceCompanyName ?? invoice?.invoiceCompany ?? invoice?.companyName ?? invoice?.company ?? form.value.customerName
  });
};

/** 删除发票 */
const handleDeleteInvoice = (index: number) => {
  proxy?.$modal
    .confirm('确认删除该发票吗？')
    .then(() => {
      invoiceList.value.splice(index, 1);
      proxy?.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
};

/** 提交表单 */
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 组装发票列表数据
        form.value.invoiceList = invoiceList.value;

        if (isEdit.value) {
          await updateStatementInvoice(form.value);
          proxy?.$modal.msgSuccess('修改成功');
        } else {
          await addStatementInvoice(form.value);
          proxy?.$modal.msgSuccess('新增成功');
        }
        drawer.visible = false;
        emit('success');
      } catch (error) {
        console.error(error);
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 关闭抽屉前的回调 */
const handleDrawerClose = (done: () => void) => {
  if (buttonLoading.value) {
    return;
  }
  done();
  reset();
};

const emit = defineEmits(['success']);

defineExpose({
  open
});
</script>

<style scoped lang="scss">
.drawer-header {
  display: flex;
  align-items: center;
  gap: 10px;

  .order-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.drawer-content {
  padding: 0 20px 20px;
  height: calc(100% - 60px);
  overflow-y: auto;
}

.empty-data {
  text-align: center;
  padding: 20px 0;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
