<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">发票详情</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="statementInvoiceNo">
              <el-input v-model="form.statementInvoiceNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开票状态：" prop="invoiceStatus">
              <dict-tag :options="invoice_status" :value="form.invoiceStatus" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="伙伴商名称：" prop="customerName">
              <el-input v-model="form.customerName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <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"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

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

        <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>

        <el-table :data="form.invoiceList" border style="width: 100%; margin-bottom: 20px">
          <el-table-column type="index" label="序号" width="80" align="center" />
          <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="160" align="center">
            <template #default="scope">
              <el-button type="primary" link @click="handleDownloadFile(scope.row)">查看附件</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="handleDrawerClose(() => (drawer.visible = false))">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup name="InvoiceDetailDrawer" lang="ts">
import { StatementInvoiceForm } from '@/api/bill/statementInvoice/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { invoice_type, invoice_status } = toRefs<any>(proxy?.useDict('invoice_type', 'invoice_status'));
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: []
};

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 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) {
    // 查看模式
    drawer.title = '发票详情';
    Object.assign(form.value, data);

    // 解析附件地址并回显附件列表
    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;
    }
  }

  drawer.visible = true;
};

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

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

  try {
    const response = await fetch(file.invoiceAnnex);
    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.invoiceAnnex;
    link.download = file.name || '附件';
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
};

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

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

/** 关闭抽屉前的回调 */
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>
