<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="100px">
            <el-form-item label="申请编号" prop="invoiceCode">
              <el-input v-model="queryParams.invoiceCode" placeholder="请输入申请编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目号" prop="projectCode">
              <el-input v-model="queryParams.projectCode" placeholder="请输入项目号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目类型" prop="invoiceCategory">
              <el-select v-model="queryParams.invoiceCategory" placeholder="请选择项目类型" clearable @keyup.enter="handleQuery">
                <el-option v-for="dict in invoice_category" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="提前开票标识" prop="earlyFlag">
              <el-select v-model="queryParams.earlyFlag" placeholder="请选择提前开票标识" clearable @keyup.enter="handleQuery">
                <el-option v-for="dict in early_flag" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-form-item label="开票状态" prop="invoiceStatus">
                <el-select v-model="queryParams.invoiceStatus" placeholder="请选择开票状态" clearable @keyup.enter="handleQuery">
                  <el-option v-for="dict in invoice_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <!--              <el-form-item label="流程状态" prop="flowStatus">-->
              <!--                <el-select v-model="queryParams.flowStatus" placeholder="请选择流程状态" clearable @keyup.enter="handleQuery">-->
              <!--                  <el-option v-for="dict in wf_business_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>-->
              <!--                </el-select>-->
              <!--              </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="['oa/erp:finInvoiceInfo:add']"> 新增 </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oa/erp:finInvoiceInfo:edit']"-->
          <!--              >修改-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oa/erp:finInvoiceInfo:remove']"
            >删除
          </el-button>
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:finInvoiceInfo:export']">导出 </el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="finInvoiceInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="申请编号" align="center" prop="invoiceCode" min-width="150" show-overflow-tooltip />
        <el-table-column label="项目号" align="center" prop="projectCode" v-if="columns[9].visible" min-width="120" show-overflow-tooltip />
        <el-table-column label="项目名称" align="center" prop="projectName" v-if="columns[10].visible" min-width="160" show-overflow-tooltip />
        <el-table-column label="项目类型" align="center" prop="invoiceCategory" v-if="columns[15].visible" min-width="110">
          <template #default="scope">
            <dict-tag :options="invoice_category" :value="scope.row.invoiceCategory" />
          </template>
        </el-table-column>
        <el-table-column label="提前开票标识" align="center" prop="earlyFlag" v-if="columns[3].visible" min-width="120">
          <template #default="scope">
            <dict-tag :options="early_flag" :value="scope.row.earlyFlag" />
          </template>
        </el-table-column>

        <el-table-column label="本次开具金额" align="center" prop="issueAmount" v-if="columns[5].visible" min-width="120" />
        <el-table-column label="本次开具比例" align="center" prop="issuancePercentage" v-if="columns[6].visible" min-width="108" />

        <el-table-column label="验收日期" align="center" prop="acceptanceDate" min-width="168" v-if="columns[11].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.acceptanceDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发货日期" align="center" prop="deliveryDate" min-width="168" v-if="columns[12].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>

        <el-table-column label="合同总价" align="center" prop="totalPrice" v-if="columns[17].visible" min-width="120" />
        <el-table-column label="客户名称" align="center" prop="customerName" v-if="columns[19].visible" min-width="140" show-overflow-tooltip />
        <el-table-column label="累计回款金额" align="center" prop="returnedMoney" v-if="columns[21].visible" min-width="120" />
        <el-table-column label="累计回款比例" align="center" prop="returnedRate" v-if="columns[22].visible" min-width="120" />
        <el-table-column label="流程状态" align="center" prop="flowStatus" v-if="columns[26].visible" width="100">
          <template #default="scope">
            <dict-tag :options="wf_business_status" :value="scope.row.flowStatus" />
          </template>
        </el-table-column>
        <el-table-column label="开票状态" align="center" prop="invoiceStatus" v-if="columns[27].visible" width="100">
          <template #default="scope">
            <dict-tag :options="invoice_status" :value="scope.row.invoiceStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="120" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top" v-if="scope.row.invoiceStatus !== INVOICE_STATUS.DRAFT">
              <el-button
                link
                type="primary"
                size="small"
                icon="DocumentChecked"
                @click="handleUpdate(scope.row, 'view')"
                v-hasPermi="['oa:erp/budgetInfo:view']"
              >
              </el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button
                link
                size="small"
                type="primary"
                icon="Edit"
                v-if="scope.row.invoiceStatus === INVOICE_STATUS.DRAFT"
                @click="handleUpdate(scope.row, 'update')"
                v-hasPermi="['oa/erp:finInvoiceInfo:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="danger"
                v-if="scope.row.invoiceStatus === INVOICE_STATUS.DRAFT"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['oa/erp:finInvoiceInfo:remove']"
              ></el-button>
            </el-tooltip>
          </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>
  </div>
</template>

<script setup name="FinInvoiceInfo" lang="ts">
import { useRouter } from 'vue-router';
import { listFinInvoiceInfo, delFinInvoiceInfo, addFinInvoiceInfo, updateFinInvoiceInfo } from '@/api/oa/erp/finInvoiceInfo';
import { FinInvoiceInfoVO, FinInvoiceInfoQuery, FinInvoiceInfoForm } from '@/api/oa/erp/finInvoiceInfo/types';
import { reactive } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const route = useRoute();

const { early_flag, invoice_category, invoice_status, wf_business_status } = toRefs<any>(
  proxy?.useDict('early_flag', 'invoice_category', 'invoice_status', 'wf_business_status')
);

const finInvoiceInfoList = ref<FinInvoiceInfoVO[]>([]);
const buttonLoading = ref(false);
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 finInvoiceInfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const INVOICE_STATUS = reactive({
  DRAFT: '1', //暂存，草稿
  AUDITING: '2', //审批中
  AVAILABLE: '3' //可用
});

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `开票ID`, visible: true },
  { key: 1, label: `租户编号`, visible: true },
  { key: 2, label: `开票申请编号`, visible: true },
  { key: 3, label: `提前开票标识(1是，0否)`, visible: true },
  { key: 4, label: `发票类型`, visible: true },
  { key: 5, label: `本次开具金额(自动计算)`, visible: true },
  { key: 6, label: `本次开具比例`, visible: true },
  { key: 7, label: `冲红标识`, visible: true },
  { key: 8, label: `项目ID`, visible: true },
  { key: 9, label: `冗余，项目号`, visible: true },
  { key: 10, label: `冗余，项目名称`, visible: true },
  { key: 11, label: `冗余，验收日期，冗余`, visible: true },
  { key: 12, label: `发货日期，发货单中是分批发记录的`, visible: true },
  { key: 13, label: `冗余，收货日期，冗余`, visible: true },
  { key: 14, label: `版本，新版本+1`, visible: true },
  { key: 15, label: `项目类型(1、实施类，2备件类)`, visible: true },
  { key: 16, label: `合同ID`, visible: true },
  { key: 17, label: `冗余，合同总价`, visible: true },
  { key: 18, label: `冗余，客户ID`, visible: true },
  { key: 19, label: `冗余，客户名称`, visible: true },
  { key: 20, label: `冗余，合同付款条款`, visible: true },
  { key: 21, label: `累计回款金额`, visible: true },
  { key: 22, label: `累计回款比例`, visible: true },
  { key: 23, label: `是否全部投料`, visible: true },
  { key: 24, label: `成本是否归集完整`, visible: true },
  { key: 25, label: `是否建立销售订单`, visible: true },
  { key: 26, label: `流程状态`, visible: true },
  { key: 27, label: `开票状态(1暂存 2审批中 3可用)`, visible: true },
  { key: 28, label: `发票备注`, visible: true },
  { key: 29, label: `提前开票原因`, visible: true },
  { key: 30, label: `删除标志`, visible: true },
  { key: 31, label: `创建部门`, visible: true },
  { key: 32, label: `创建人`, visible: true },
  { key: 33, label: `创建时间`, visible: true },
  { key: 34, label: `更新人`, visible: true },
  { key: 35, label: `更新时间`, visible: true }
]);

const initFormData: FinInvoiceInfoForm = {
  invoiceId: undefined,
  invoiceCode: undefined,
  earlyFlag: undefined,
  invoiceType: undefined,
  issueAmount: undefined,
  issuancePercentage: undefined,
  redInkFlag: undefined,
  projectId: undefined,
  projectCode: undefined,
  projectName: undefined,
  acceptanceDate: undefined,
  deliveryDate: undefined,
  arrivalDate: undefined,
  invoiceVersion: undefined,
  invoiceCategory: undefined,
  contractId: undefined,
  totalPrice: undefined,
  customerId: undefined,
  customerName: undefined,
  paymentMethod: undefined,
  returnedMoney: undefined,
  returnedRate: undefined,
  feedingFlag: undefined,
  costCompleteFlag: undefined,
  saleOrderCreateFlag: undefined,
  flowStatus: undefined,
  invoiceStatus: undefined,
  remark: undefined,
  earlyReason: undefined
};
const data = reactive<PageData<FinInvoiceInfoForm, FinInvoiceInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    invoiceCode: undefined,
    earlyFlag: undefined,
    invoiceType: undefined,
    issueAmount: undefined,
    issuancePercentage: undefined,
    redInkFlag: undefined,
    projectId: undefined,
    projectCode: undefined,
    projectName: undefined,
    acceptanceDate: undefined,
    deliveryDate: undefined,
    arrivalDate: undefined,
    invoiceVersion: undefined,
    invoiceCategory: undefined,
    contractId: undefined,
    totalPrice: undefined,
    customerId: undefined,
    customerName: undefined,
    paymentMethod: undefined,
    returnedMoney: undefined,
    returnedRate: undefined,
    feedingFlag: undefined,
    costCompleteFlag: undefined,
    saleOrderCreateFlag: undefined,
    flowStatus: undefined,
    invoiceStatus: undefined,
    earlyReason: undefined,
    params: {}
  },
  rules: {
    invoiceId: [{ required: true, message: '开票ID不能为空', trigger: 'blur' }],
    projectId: [{ required: true, message: '项目ID不能为空', trigger: 'blur' }],
    projectCode: [{ required: true, message: '冗余，项目号不能为空', trigger: 'blur' }],
    projectName: [{ required: true, message: '冗余，项目名称不能为空', trigger: 'blur' }],
    invoiceCategory: [{ required: true, message: '项目类型(1、实施类，2备件类)不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询开票信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listFinInvoiceInfo(queryParams.value);
  finInvoiceInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  finInvoiceInfoFormRef.value?.resetFields();
};

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  // proxy.$tab.closePage(route);
  router.push({
    path: '/fin/finInvoiceInfo/edit',
    query: {
      type: 'add'
    }
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: FinInvoiceInfoVO, type?: string) => {
  const _invoiceId = row?.invoiceId || ids.value[0];
  router.push({
    path: '/fin/finInvoiceInfo/edit',
    query: {
      type: type,
      id: _invoiceId
    }
  });
};

/** 提交按钮 */
const submitForm = () => {
  finInvoiceInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.invoiceId) {
        await updateFinInvoiceInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addFinInvoiceInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

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

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

onMounted(() => {
  getList();
});

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