<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">
          <template #header>
            <div class="clearfix">
              <span>结算信息</span>
            </div>
          </template>
          <el-form ref="invoiceFormRef" :model="invoiceForm" :inline="true" label-width="135px" label-position="left">
            <el-form-item label="管理机构" prop="manageCom">
              <el-select v-model="invoiceForm.manageCom" placeholder="">
                <el-option
                  v-for="dict in sys_managecom"
                  :key="dict.value"
                  readonly
                  :label="dict.value + '-' + dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="发票id" prop="invoiceId">
              <el-input v-model="invoiceForm.invoiceId" placeholder="" readonly />
            </el-form-item>
            <el-form-item label="结算批次号" prop="settlBatchNo">
              <el-input v-model="invoiceForm.settlBatchNo" placeholder="" readonly />
            </el-form-item>
            <el-form-item label="结算方名称" prop="settlVendorName">
              <el-input v-model="invoiceForm.settlVendorName" placeholder="" readonly />
            </el-form-item>
            <el-form-item label="统一社会信用代码" prop="settlVendorSocialCode">
              <el-input v-model="invoiceForm.settlVendorSocialCode" placeholder="" readonly />
            </el-form-item>
            <el-form-item label="业务类型" prop="businessType">
              <el-select v-model="invoiceForm.businessType" clearable disabled>
                <el-option
                  v-for="dict in bfs_business_type"
                  :key="dict.value"
                  :label="dict.value + '-' + dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="结算金额" prop="settlAmount">
              <el-input v-model="invoiceForm.settlAmount" placeholder="" readonly />
            </el-form-item>
            <el-form-item label="结算价额" prop="settlIncome">
              <el-input v-model="invoiceForm.settlIncome" placeholder="" readonly />
            </el-form-item>
            <el-form-item label="结算税额" prop="settlTax">
              <el-input v-model="invoiceForm.settlTax" placeholder="" readonly />
            </el-form-item>
            <el-form-item label="销售渠道" prop="salesChannel">
              <el-input v-model="invoiceForm.salesChannel" placeholder="" readonly />
            </el-form-item>
            <el-form-item label="业务渠道" prop="channelCode">
              <el-input v-model="invoiceForm.channelCode" placeholder="" readonly />
            </el-form-item>
            <el-form-item label="处理状态" prop="channelCode" >
              <el-select v-model="invoiceForm.status" clearable disabled>
                <el-option
                  v-for="dict in bfs_invoice_status"
                  :key="dict.value"
                  :label="dict.value + '-' + dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card>
          <template #header>
            <div class="clearfix">
              <span>结算明细</span>
            </div>
            <el-table v-loading="loading" :data="invoiceDetailList">
              b <el-table-column label="保单号" align="center" prop="settlBatchNo" width="150" show-overflow-tooltip />
              <el-table-column label="险种编码" align="center" prop="productCode" width="150" show-overflow-tooltip />
              <el-table-column label="缴费频率" align="center" prop="payIntv" width="150" show-overflow-tooltip />
              <el-table-column label="缴费年期" align="center" prop="payEndYear" width="150" show-overflow-tooltip />
              <el-table-column label="缴费年期单位" align="center" prop="payEndYearFlag" width="150" show-overflow-tooltip />
              <el-table-column label="保单管理机构" align="center" prop="manageCom" width="150" show-overflow-tooltip />
              <el-table-column label="分出摊回金额" align="center" prop="cededAmount" width="150" show-overflow-tooltip />
              <el-table-column label="分出摊回税额" align="center" prop="cededTax" width="150" show-overflow-tooltip />
              <el-table-column label="产品税率" align="center" prop="cededTaxRate" width="150" show-overflow-tooltip />
            </el-table>
          </template>
        </el-card>

        <el-card>
          <template #header>
            <div class="clearfix">
              <span>发票明细</span>
            </div>
            <el-table v-loading="loading" :data="invoiceWriteofList">
              b <el-table-column label="发票号码" align="center" prop="invoiceNo" width="150" show-overflow-tooltip />
              <el-table-column label="含税金额" align="center" prop="invoiceAmount" width="150" show-overflow-tooltip />
              <el-table-column label="不含税金额" align="center" prop="invoiceIncome" width="150" show-overflow-tooltip />
              <el-table-column label="税额" align="center" prop="invoiceTax" width="150" show-overflow-tooltip />
              <el-table-column label="税率" align="center" prop="invoiceTaxRate" width="150" show-overflow-tooltip />
              <el-table-column label="发票类型" align="center" prop="invoiceType" width="150" show-overflow-tooltip>
                <template #default="scope">
                  <dict-tag :options="bfs_invoice_type" :value="scope.row.invoiceType" />
                </template>
              </el-table-column>
              <el-table-column label="发票开具日期" align="center" prop="invoiceDate" width="150" show-overflow-tooltip >
                <template #default="scope">
                  <span>{{ parseTime(scope.row.invoiceDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template v-if="invoiceForm.status != '9'" #default="scope">
                  <el-tooltip content="修改" placement="top">
                    <el-button v-hasPermi="['bfs:invoice:writeof']" link type="primary" icon="Edit" @click="handleEdit(scope.row)">修改</el-button>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <el-button v-hasPermi="['bfs:invoice:writeof']" link type="primary" icon="Edit" @click="handleDelete(scope.row)">删除</el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-card>
        <el-card v-if="invoiceForm.status != '9'">
          <template #header>
            <div class="clearfix">
              <span>发票录入</span>
            </div>
          </template>
          <el-form
            ref="writeofFormRef"
            v-loading="writeofLoading"
            :model="writeofForm"
            :rules="rules"
            :inline="true"
            label-width="135px"
            label-position="left"
          >
            <el-form-item v-if="false" label="发票id" prop="id">
              <el-input v-model="writeofForm.id" />
            </el-form-item>
            <el-form-item v-if="false" label="发票号码id" prop="invoiceId">
              <el-input v-model="writeofForm.invoiceId" maxlength="50" show-word-limit placeholder="请输入发票号码" clearable />
            </el-form-item>
            <el-form-item label="发票号码" prop="invoiceNo">
              <el-input v-model="writeofForm.invoiceNo" maxlength="50" show-word-limit placeholder="请输入发票号码" clearable />
            </el-form-item>
            <el-form-item label="含税金额" prop="invoiceAmount">
              <el-input-number
                v-model="writeofForm.invoiceAmount"
                controls-position="right"
                :precision="2"
                :step="0.01"
                placeholder="请输入含税金额"
                clearable
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item label="不含税金额" prop="invoiceIncome">
              <el-input-number
                v-model="writeofForm.invoiceIncome"
                controls-position="right"
                :precision="2"
                :step="0.01"
                placeholder="请输入不含税金额"
                clearable
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item label="税额" prop="invoiceTax">
              <el-input-number
                v-model="writeofForm.invoiceTax"
                controls-position="right"
                :precision="2"
                :step="0.01"
                placeholder="请输入税额"
                clearable
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item label="税率" prop="invoiceTaxRate">
              <el-select v-model="writeofForm.invoiceTaxRate" placeholder="税率">
                <el-option v-for="dict in bfs_invoice_taxrate" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开票日期" prop="invoiceDate">
              <el-date-picker v-model="writeofForm.invoiceDate" value-format="YYYY-MM-DD" type="date" clearable> </el-date-picker>
            </el-form-item>
            <el-form-item label="发票类型" prop="invoiceType">
              <el-select v-model="writeofForm.invoiceType" placeholder="发票类型">
                <el-option v-for="dict in bfs_invoice_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>

            <el-row>
              <el-form-item>
                <el-button type="primary" v-hasPermi="['bfs:invoice:writeof']" icon="Search" @click="handleAdd">保存</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" v-hasPermi="['bfs:invoice:submit']" icon="Check" @click="handleSubmit">提交</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>
  </div>
</template>
<script setup lang="ts">
import {
  addWriteof,
  delWriteofList,
  editWriteof,
  queryInvoiceDetail,
  queryWriteofList,
  submitInvoice
} from '@/api/bfs/invoice';
import { RouteLocationNormalized } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));
const { bfs_invoice_taxrate } = toRefs<any>(proxy?.useDict('bfs_invoice_taxrate'));
const { bfs_invoice_status } = toRefs<any>(proxy?.useDict('bfs_invoice_status'));
const { bfs_business_type } = toRefs<any>(proxy?.useDict('bfs_business_type'));
const { bfs_invoice_type } = toRefs<any>(proxy?.useDict('bfs_invoice_type'));

const showSearch = ref(true);
const total = ref(0);
const loading = ref(false);
const invoiceDetailList = ref([]);
const invoiceWriteofList = ref([]);
const writeofFormRef = ref<ElFormInstance>();
const writeofLoading = ref(false);

const data = reactive({
  invoiceForm: {
    manageCom: undefined,
    settlBatchNo: undefined,
    settlVendorName: undefined,
    settlVendorSocialCode: undefined,
    businessType: undefined,
    status: undefined,
    settlAmount: undefined,
    settlIncome: undefined,
    settlTax: undefined,
    salesChannel: undefined,
    channelCode: undefined
  },
  writeofForm: {
    id: undefined,
    invoiceId: undefined,
    invoiceNo: undefined,
    invoiceAmount: undefined,
    invoiceIncome: undefined,
    invoiceTax: undefined,
    invoiceTaxRate: undefined,
    invoiceDate: undefined,
    invoiceType: undefined
  },
  rules: {
    invoiceNo: [{ required: true, message: '发票号码不能为空', trigger: 'blur' }],
    invoiceAmount: [{ required: true, message: '含税金额不能为空', trigger: 'blur' }],
    invoiceIncome: [{ required: true, message: '不含税金额不能为空', trigger: 'blur' }],
    invoiceTax: [{ required: true, message: '税额不能为空', trigger: 'blur' }],
    invoiceTaxRate: [{ required: true, message: '税率不能为空', trigger: 'blur' }],
    invoiceDate: [{ required: true, message: '发票开具日期不能为空', trigger: 'blur' }],
    invoiceType: [{ required: true, message: '发票类型不能为空', trigger: 'blur' }]
  }
});
const { invoiceForm, writeofForm, rules } = toRefs(data);

const getInvoiceDetail = async (invoiceId) => {
  loading.value = true;
  try {
    const res = await queryInvoiceDetail(invoiceId);
    if (res.code === 200) {
      Object.assign(invoiceForm.value, res.data.invoice);
      invoiceDetailList.value = res.data.invoiceDetailList;
      invoiceWriteofList.value = res.data.invoiceWriteofList;
    }
  } finally {
    loading.value = false;
  }
};

const handleAdd = async () => {
  const valid = await writeofFormRef.value.validate();
  if (valid && checkWriteofInput()) {
    writeofLoading.value = true;
    writeofForm.value.invoiceId = invoiceForm.value.invoiceId;
    try {
      if (writeofForm.value.id) {
        await editWriteof(writeofForm.value);
      } else {
        await addWriteof(writeofForm.value);
      }
      proxy.$modal.msgSuccess('保存成功');
      writeofFormRef.value?.resetFields();
      writeofForm.value.id = undefined;
      await getWriteofList();
    } finally {
      writeofLoading.value = false;
    }
  }
};

const checkWriteofInput = () => {
  if (writeofForm.value.invoiceAmount <= 0) {
    proxy.$modal.msgError('含税金额必须大于0');
    return false;
  }
  if (writeofForm.value.invoiceIncome <= 0) {
    proxy.$modal.msgError('不含税金额必须大于0');
    return false;
  }
  if (writeofForm.value.invoiceTax < 0) {
    proxy.$modal.msgError('税额必须大于等于0');
    return false;
  }
  let invoiceAmount = parseFloat(writeofForm.value.invoiceAmount);
  let invoiceIncome = parseFloat(writeofForm.value.invoiceIncome);
  let invoiceTax = parseFloat(writeofForm.value.invoiceTax);
  if (invoiceAmount != invoiceIncome + invoiceTax) {
    proxy.$modal.msgError('含税金额必须等于不含税金额加税额');
    return false;
  }
  return true;
};

const getWriteofList = async () => {
  const invoiceId = invoiceForm.value.invoiceId;
  const res = await queryWriteofList({ invoiceId });
  invoiceWriteofList.value = res.data;
};

const handleEdit = (row) => {
  Object.assign(writeofForm.value, row);
};

const handleDelete = async (row) => {
  const confirm = await proxy.$modal.confirm('确定要删除吗？');
  if (confirm) {
    const res = await delWriteofList(row);
    if (res.code == 200) {
      proxy.$modal.msgSuccess('保存成功');
      await getWriteofList();
    }
  }
};

const handleSubmit = async () => {
  const confirm = await proxy.$modal.confirm('确定要提交本次发票核销吗？');
  if (confirm) {
    const invoiceId = invoiceForm.value.invoiceId;
    const res = await submitInvoice({ invoiceId });
    if (res.code == 200) {
      proxy.$modal.msgSuccess('提交成功');
      const obj: RouteLocationNormalized = {
        fullPath: '',
        hash: '',
        matched: [],
        meta: undefined,
        name: undefined,
        params: undefined,
        query: undefined,
        redirectedFrom: undefined,
        path: '/bfs/Invoice'
      };
      proxy?.$tab.closeOpenPage(obj);
    }
  }
};

onMounted(() => {
  const route = useRoute();
  const invoiceId = route.query.invoiceId;
  if (invoiceId) {
    getInvoiceDetail(invoiceId);
  } else {
    proxy.$modal.msgError('获取信息失败');
  }
});
</script>
<style scoped lang="scss"></style>
