<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="110px">
            <el-form-item label="开票申请单号" prop="applicationNo">
              <el-input v-model="queryParams.applicationNo" placeholder="请输入开票申请单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="客户ID" prop="customerId">
              <el-input v-model="queryParams.customerId" placeholder="请输入客户ID" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->

            <el-form-item label="发票类型" prop="invoiceType">
              <el-select v-model="queryParams.invoiceType" placeholder="请选择发票类型" clearable>
                <el-option v-for="dict in invoice_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="发票抬头" prop="invoiceTitle">
              <el-input v-model="queryParams.invoiceTitle" placeholder="请输入发票抬头" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="申请状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择申请状态" clearable>
                <el-option v-for="dict in invoice_application_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['bill:invoiceApplication:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['bill:invoiceApplication:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['bill:invoiceApplication:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['bill:invoiceApplication:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="invoiceApplicationList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="开票申请单号" align="center" prop="applicationNo" />
        <el-table-column label="客户名称" align="center" prop="customerName" />
        <el-table-column label="发票类型" align="center" prop="invoiceType">
          <template #default="scope">
            <dict-tag :options="invoice_type" :value="scope.row.invoiceType" />
          </template>
        </el-table-column>
        <el-table-column label="发票抬头" align="center" prop="invoiceTitle" />
        <el-table-column label="纳税人识别号" align="center" prop="taxNumber" />
        <el-table-column label="注册地址" align="center" prop="regAddress" />
        <el-table-column label="注册电话" align="center" prop="regPhone" />
        <el-table-column label="开户银行" align="center" prop="bankName" />
        <el-table-column label="银行账号" align="center" prop="bankAccount" />
        <el-table-column label="申请开票金额" align="center" prop="applyAmount" />
        <el-table-column label="申请税额" align="center" prop="applyTaxAmount" />
        <el-table-column label="总金额" align="center" prop="totalAmount" />
        <el-table-column label="申请备注" align="center" prop="remark" />
        <el-table-column label="申请状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="invoice_application_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="审核人ID" align="center" prop="auditUserId" />
        <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核意见" align="center" prop="auditRemark" />

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['bill:invoiceApplication:edit']">编辑</el-button> -->
            <el-button link type="primary" icon="Edit" @click="handleAudit(scope.row)" v-hasPermi="['bill:invoiceApplication:edit']">审核</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['bill:invoiceApplication:remove']"
              >删除</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>
    <!-- 添加或修改开票申请单抽屉 -->
    <AddAndEditDrawer v-model="drawerVisible" :title="drawerTitle" :form-data="currentFormData" @success="handleDrawerSuccess" />

    <!-- 审核对话框 -->
    <el-dialog v-model="auditDialogVisible" title="审核开票申请" width="500px" append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" label-width="100px">
        <el-form-item label="审核结果" prop="status">
          <el-select v-model="auditForm.status" placeholder="请选择审核结果">
            <el-option v-for="dict in invoice_application_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditRemark">
          <el-input v-model="auditForm.auditRemark" type="textarea" :rows="4" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAuditSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="InvoiceApplication" lang="ts">
import { listInvoiceApplication, getInvoiceApplication, delInvoiceApplication, auditApplication } from '@/api/bill/invoiceApplication';
import AddAndEditDrawer from './invoiceApplyDrawer.vue';
import { InvoiceApplicationVO, InvoiceApplicationQuery, InvoiceApplicationForm } from '@/api/bill/invoiceApplication/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { invoice_application_status, invoice_type } = toRefs<any>(proxy?.useDict('invoice_application_status', 'invoice_type'));

const invoiceApplicationList = ref<InvoiceApplicationVO[]>([]);
const drawerVisible = ref(false);
const drawerTitle = ref('');
const currentFormData = ref<InvoiceApplicationForm>();
const auditDialogVisible = ref(false);
const auditForm = ref<InvoiceApplicationForm>({});
const auditFormRef = ref<ElFormInstance>();
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

const data = reactive<PageData<InvoiceApplicationForm, InvoiceApplicationQuery>>({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    applicationNo: undefined,
    customerId: undefined,
    customerName: undefined,
    invoiceType: undefined,
    invoiceTitle: undefined,
    taxNumber: undefined,
    regAddress: undefined,
    regPhone: undefined,
    bankName: undefined,
    bankAccount: undefined,
    receiverEmail: undefined,
    receiverPhone: undefined,
    applyAmount: undefined,
    applyTaxAmount: undefined,
    totalAmount: undefined,
    statementIds: undefined,
    status: undefined,
    auditUserId: undefined,
    auditTime: undefined,
    auditRemark: undefined,
    finalInvoiceId: undefined,
    invoiceCode: undefined,
    invoiceNumber: undefined,
    invoiceDate: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {}
});

const { queryParams } = toRefs(data);

/** 查询开票申请单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listInvoiceApplication(queryParams.value);
  invoiceApplicationList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 抽屉成功回调 */
const handleDrawerSuccess = () => {
  getList();
};

/** 审核按钮操作 */
const handleAudit = (row: InvoiceApplicationVO) => {
  auditForm.value = {
    id: row.id,
    status: undefined,
    auditRemark: ''
  };
  auditDialogVisible.value = true;
};

/** 审核提交 */
const handleAuditSubmit = async () => {
  if (!auditForm.value.status) {
    proxy?.$modal.msgWarning('请选择审核结果');
    return;
  }
  try {
    await auditApplication(auditForm.value);
    proxy?.$modal.msgSuccess('审核成功');
    auditDialogVisible.value = false;
    await getList();
  } catch (error) {
    console.error('审核失败:', error);
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: InvoiceApplicationVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  currentFormData.value = undefined;
  drawerTitle.value = '添加开票申请单';
  drawerVisible.value = true;
};

/** 修改按钮操作 */
const handleUpdate = async (row?: InvoiceApplicationVO) => {
  const _id = row?.id || ids.value[0];
  const res = await getInvoiceApplication(_id);
  currentFormData.value = res.data;
  drawerTitle.value = '修改开票申请单';
  drawerVisible.value = true;
};

/** 删除按钮操作 */
const handleDelete = async (row?: InvoiceApplicationVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除开票申请单编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delInvoiceApplication(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'bill/invoiceApplication/export',
    {
      ...queryParams.value
    },
    `invoiceApplication_${new Date().getTime()}.xlsx`
  );
};

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