<template>
  <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
    <div v-show="showSearch" v-loading="loading" class="mb-[10px]">
      <el-card shadow="hover">
        <el-form ref="formRef" :model="form" :rules="rules" :inline="true" label-width="80px">
          <el-form-item label="id" prop="id">
            <el-input v-model="form.id" disabled />
          </el-form-item>
          <el-form-item label="红冲流水号" prop="invoicingId">
            <el-input v-model="form.invoicingId" disabled />
          </el-form-item>
          <el-form-item label="红冲原因" prop="invoicingReason">
            <el-select v-model="form.invoicingReason" placeholder="请选择红冲原因" clearable>
              <el-option v-for="item in bfs_invoicing_reason" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-row>
            <el-form-item label="原因描述" prop="invoicingDetail">
              <el-input v-model="form.invoicingDetail" type="textarea" style="width: 290px" :rows="4" placeholder="请输入原因描述"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item>
              <el-button type="primary" v-hasPermi="['bls:invoicing:saveInvoicing']" icon="Check" @click="handleSave">保存</el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </el-card>
      <el-card v-if="form.id !== ''" shadow="hover">
        <el-form ref="queryRef" :model="queryParams" :rules="queryRules" :inline="true" label-width="80px">
          <el-row>

            <el-form-item label="凭证大类" prop="certificateId">
              <el-select v-model="queryParams.certificateId" @change="CertificateChangeQury" clearable placeholder="请选择凭证大类">
                <template #header>
                  <el-input v-model="likeName" placeholder="可根据机构编码或名称模糊查询" @input="filterByCertificate"></el-input>
                </template>
                <el-option
                  v-for="dict in filteredCertificate"
                  :key="dict.certificateId"
                  :label="dict.certificateId + '-' + dict.certificateName"
                  :value="dict.certificateId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="凭证细类" prop="costId">
              <el-select v-model="queryParams.costId" clearable placeholder="请选择凭证细类">
                <el-option v-for="dict in filteredCostList" :key="dict.costId" :label="dict.costId + '-' + dict.costName" :value="dict.costId" />
              </el-select>
            </el-form-item>
            <el-form-item label="保单号码" prop="policyNo">
              <el-input v-model="queryParams.policyNo" placeholder="请输入保单号码" clearable />
            </el-form-item>
            <el-form-item label="业务号码" prop="businessNo">
              <el-input v-model="queryParams.businessNo" placeholder="请输入业务号码" clearable />
            </el-form-item>
            <el-form-item label="记账日期" prop="dateRange">
              <el-date-picker
                v-model="queryParams.dateRange"
                end-placeholder="结束日期"
                range-separator="-"
                start-placeholder="开始日期"
                type="daterange"
                value-format="YYYY-MM-DD"
                @change="handleDateRangeChange"
                style="width: 242px"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="管理机构" prop="manageCom">
              <el-select v-model="queryParams.manageCom" clearable placeholder="请输入管理机构">
                <template #header>
                  <el-input v-model="likeMangeName" placeholder="可根据机构编码或名称模糊查询" @input="filterByManageCom"></el-input>
                </template>
                <el-option v-for="dict in filteredManagecom" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="凭证类型" prop="dataType">
              <el-select v-model="queryParams.dataType" clearable placeholder="请选择凭证类型">
                <el-option v-for="dict in bfs_certificate_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="凭证号" prop="belnrSap">
              <el-input v-model="queryParams.belnrSap" placeholder="请输入凭证号" clearable />
            </el-form-item>
          </el-row>
          <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>
      <el-card v-if="form.id !== ''" class="box-card">
        <el-table v-loading="loading" :data="costResultList">
          <el-table-column v-if="false" label="id" align="center" prop="id" />
          <el-table-column label="凭证号" align="center" prop="belnrSap" />
          <el-table-column label="凭证大类编码" align="center" prop="certificateId" />
          <el-table-column label="场景编码" align="center" prop="costId" width="150px" />
          <el-table-column label="总账科目" align="center" prop="finItemCode" width="150px" />
          <el-table-column label="明细科目" align="center" prop="subItemCode" width="150px" />
          <el-table-column label="借贷标记" align="center" prop="finItemType">
            <template #default="scope">
              <dict-tag :options="bfs_debit_and_credit" :value="scope.row.finItemType" />
            </template>
          </el-table-column>
          <el-table-column label="金额" align="center" prop="amount" />
          <el-table-column label="记账日期" align="center" prop="accountDate" width="150px">
            <template #default="scope">
              <span>{{ parseTime(scope.row.accountDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="业务号码" align="center" prop="businessNo" width="200px" />
          <el-table-column label="业务机构" align="center" prop="manageCom" />
          <el-table-column label="交费年期" align="center" prop="payendyear" />
          <el-table-column label="保单号" align="center" prop="policyNo" width="200px" />
          <el-table-column label="分单号" align="center" prop="singlePolicyNo" width="200px" />
          <el-table-column label="手续费结算单位" align="center" prop="settlementUnit" width="100px" />
          <el-table-column label="银行对账码" align="center" prop="reconCode" width="200px" />
          <el-table-column label="销售渠道" align="center" prop="saleChnl" />
          <el-table-column label="往来单位分类" align="center" prop="businessPartners" />
          <el-table-column label="供应商" align="center" prop="intraBranch" />
          <el-table-column label="业务性质" align="center" prop="businessNature" />
          <el-table-column label="原因代码" align="center" prop="cashFlow" />
          <el-table-column label="开户行" align="center" prop="openingBank" />
          <el-table-column label="成本中心" align="center" prop="costCenter" />
          <el-table-column label="税率" align="center" prop="taxRate" />
          <el-table-column label="税码" align="center" prop="taxCode" />
          <el-table-column label="税项" align="center" prop="taxClass" />
          <el-table-column label="承诺项目" align="center" prop="budget" />
        </el-table>
        <pagination
          v-show="costResultTotal > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="costResultTotal"
          @pagination="getCertificateList"
        />
        <el-form-item style="margin-top: 20px">
          <el-button v-hasPermi="['bfs:redivoapply:addall']" type="primary" icon="Check" @click="handleAll">全部红冲</el-button>
        </el-form-item>
      </el-card>

      <el-card v-if="form.id !== ''" class="box-card">
        <el-table v-loading="detailLoading" :data="invoicingDetailList">
          <el-table-column v-if="false" label="id" align="center" prop="id" />
          <el-table-column label="凭证号" align="center" prop="belnrSap" />
          <el-table-column label="凭证大类编码" align="center" prop="certificateId" />
          <el-table-column label="场景编码" align="center" prop="costId" width="150px" />
          <el-table-column label="总账科目" align="center" prop="finItemCode" width="150px" />
          <el-table-column label="明细科目" align="center" prop="subItemCode" width="150px" />
          <el-table-column label="借贷标记" align="center" prop="finItemType">
            <template #default="scope">
              <dict-tag :options="bfs_debit_and_credit" :value="scope.row.finItemType" />
            </template>
          </el-table-column>
          <el-table-column label="金额" align="center" prop="amount" />
          <el-table-column label="记账日期" align="center" prop="accountDate" width="150px">
            <template #default="scope">
              <span>{{ parseTime(scope.row.accountDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="业务号码" align="center" prop="businessNo" width="200px" />
          <el-table-column label="业务机构" align="center" prop="manageCom" />
          <el-table-column label="交费年期" align="center" prop="payendyear" />
          <el-table-column label="保单号" align="center" prop="policyNo" width="200px" />
          <el-table-column label="分单号" align="center" prop="singlePolicyNo" width="200px" />
          <el-table-column label="手续费结算单位" align="center" prop="settlementUnit" width="100px" />
          <el-table-column label="银行对账码" align="center" prop="reconCode" width="200px" />
          <el-table-column label="销售渠道" align="center" prop="saleChnl" />
          <el-table-column label="往来单位分类" align="center" prop="businessPartners" />
          <el-table-column label="供应商" align="center" prop="intraBranch" />
          <el-table-column label="业务性质" align="center" prop="businessNature" />
          <el-table-column label="原因代码" align="center" prop="cashFlow" />
          <el-table-column label="开户行" align="center" prop="openingBank" />
          <el-table-column label="成本中心" align="center" prop="costCenter" />
          <el-table-column label="税率" align="center" prop="taxRate" />
          <el-table-column label="税码" align="center" prop="taxCode" />
          <el-table-column label="税项" align="center" prop="taxClass" />
          <el-table-column label="承诺项目" align="center" prop="budget" />
        </el-table>
        <pagination
          v-show="invoicingDetailTotal > 0"
          v-model:page="queryInvoicingParams.pageNum"
          v-model:limit="queryInvoicingParams.pageSize"
          :total="invoicingDetailTotal"
          @pagination="getInvoicingDetailList"
        />
        <el-form ref="invoicingFormRef" :inline="true" :model="invoicingForm" label-position="left" label-width="130px" style="margin-top: 20px">
          <el-form-item label="借方总额" prop="debitBalance">
            <el-input v-model="invoicingForm.debitBalance" readonly />
          </el-form-item>
          <el-form-item label="贷方总额" prop="creditBalance">
            <el-input v-model="invoicingForm.creditBalance" readonly />
          </el-form-item>
        </el-form>
        <el-form-item style="margin-top: 20px">
          <el-button v-hasPermi="['bfs:redivoapply:apply']" type="primary" icon="Refresh" @click="handleApply">申请确认</el-button>
          <el-button v-hasPermi="['bfs:redivoapply:reset']" type="primary" icon="Search" @click="handleReset">申请取消</el-button>
        </el-form-item>
      </el-card>
    </div>
  </transition>
</template>
<script setup lang="ts">
import {
  addInvoicingByIds,
  applyInvoicing,
  editInvoicing,
  getCacheList,
  getInvoicingDetail,
  quryCertificateList,
  quryInvoicingDetailList,
  saveInvoicing
} from '@/api/bfs/busnessQury/redInvoicing';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { bfs_invoicing_type } = toRefs<any>(proxy?.useDict('bfs_invoicing_type'));
const { bfs_invoicing_reason } = toRefs<any>(proxy?.useDict('bfs_invoicing_reason'));
const { bfs_certificate_type, bfs_debit_and_credit } = toRefs<any>(proxy?.useDict('bfs_certificate_type', 'bfs_debit_and_credit'));
const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));

const showSearch = ref(true);
const loading = ref(false);
const formRef = ref<ElFormInstance>();
const queryRef = ref<ElFormInstance>();
const certificateList = ref([]);
const likeName = ref('');
const filteredCertificate = ref([]);
const invoicingForm = ref({});
const invoicingFormRef = ref<ElFormInstance>();

const costList = ref([]);
const filteredCostList = ref([]);
const costResultList = ref([]);
const costResultTotal = ref(0);

const detailLoading = ref(false);
const invoicingDetailList = ref([]);
const invoicingDetailTotal = ref(0);

const filteredManagecom = ref([]);
const likeMangeName = ref('');


const initFormData = {
  id: '',
  invoicingId: '',
  invoicingReason: '',
  invoicingDetail: '',
  status: '',
  applyBy: ''
};

const data = reactive({
  form: { ...initFormData },
  rules: {
    invoicingReason: [{ required: true, message: '红冲原因不能为空', trigger: 'blur' }],
    invoicingDetail: [{ required: true, message: '原因描述不能为空', trigger: 'blur' }]
  }
});

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

const quryInvoicingData = reactive({
  queryInvoicingParams: {
    pageNum: 1,
    pageSize: 10,
    invoicingId: undefined,
    params: {}
  },
  queryInvoicingRules: {}
});
const { queryInvoicingParams, queryInvoicingRules } = toRefs(quryInvoicingData);

const quryData = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    certificateId: undefined,
    costId: undefined,
    policyNo: undefined,
    manageCom: undefined,
    businessNo: undefined,
    accountDate: undefined,
    dataType: undefined,
    dateRange: undefined,
    belnrSap: undefined,
    params: {}
  },
  queryRules: {
    dateRange: [{ required: true, message: '记账日期不能为空', trigger: 'blur' }]
  }
});
const { queryParams, queryRules } = toRefs(quryData);

const handleSave = async () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.invoicingId) {
        const res = await editInvoicing(form.value);
        Object.assign(form.value, res.data);
      } else {
        const res = await saveInvoicing(form.value);
        Object.assign(form.value, res.data);
        //  console.log(res);
        const newPath = `/bfs/Operation/invoicing/invoiceDetail`;
        const routeObj = {
          path: newPath,
          query: {
            invoicingId: form.value.invoicingId
          }
        };
        proxy?.$modal.msgSuccess('保存成功');
        proxy?.$tab.closePage();
        proxy?.$tab.refreshPage(routeObj);
      }
    }
  });
};
const loadingPage = async (invoicingId: string) => {
  loading.value = true;
  try {
    const res = await getInvoicingDetail(invoicingId);
    Object.assign(form.value, res.data.invoicing);
    await getInvoicingDetailList();
  } finally {
    loading.value = false;
  }
};

/** 查询字典下拉信息 */
const getCache = async () => {
  const res = await getCacheList();
  certificateList.value = res.data.certificateTypeCache;
  costList.value = res.data.costTypeCache;
  filteredCertificate.value = certificateList.value;
  filteredCostList.value = costList.value;
  filteredManagecom.value = sys_managecom.value;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  if (!validateAllFields()) {
    proxy?.$modal.msgError('录入项不能全部为空');
    return;
  }
  if (!validateOthers()) {
    return;
  }
  queryRef.value.validate(async (valid: boolean) => {
    if (valid) {
      await getCertificateList();
    }
  });
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  costResultList.value = [];
  costResultTotal.value = 0;
};

const getCertificateList = async () => {
  const res = await quryCertificateList(proxy?.addDateRange(queryParams.value, queryParams.value.dateRange));
  costResultList.value = res.rows;
  costResultTotal.value = res.total;
};

const handleAll = async () => {
  if (!validateAllFields()) {
    proxy?.$modal.msgError('录入项不能全部为空');
    return;
  }
  if (!validateOthers()) {
    return;
  }
  queryRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const data = {
        ...queryParams.value,
        invoicingId: form.value.invoicingId,
        invoicingSelectType: '0'
      };
      const res = await addInvoicingByIds(data);
      if (res.code === 200) {
        proxy?.$modal.msgSuccess('操作成功');
        await getInvoicingDetailList();
      }
    }
  });
};

const handleApply = async () => {
  const data = {
    invoicingId: form.value.invoicingId,
    status: '1'
  };
  const res = await applyInvoicing(data);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('申请成功');
    proxy?.$tab.closePage();
  }
};

const handleReset = async () => {
  const data = {
    invoicingId: form.value.invoicingId,
    status: '-1'
  };
  const res = await applyInvoicing(data);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('撤销成功');
    proxy?.$tab.closePage();
  }
};

const getInvoicingDetailList = async () => {
  queryInvoicingParams.value.invoicingId = form.value.invoicingId;
  const res = await quryInvoicingDetailList(queryInvoicingParams.value);
  invoicingDetailList.value = res.rows;
  invoicingDetailTotal.value = res.total;
  invoicingFormRef.value?.resetFields();
  invoicingForm.value.debitBalance = res.otherMsg.dandc.debitBalance;
  invoicingForm.value.creditBalance = res.otherMsg.dandc.creditBalance;
};

// 自定义校验函数，检查录入项是否全部为空
const validateAllFields = () => {
  const { queryParams } = quryData;
  for (const param in queryParams) {
    if (param !== 'pageNum' && param !== 'pageSize' && param !== 'params') {
      if (queryParams[param] !== undefined && queryParams[param] !== null && queryParams[param] !== '') {
        return true;
      }
    }
  }
  return false;
};

// 计算属性用于动态设置 picker options
const handleDateRangeChange = (value: [string, string] | null) => {
  if (!value || !value[0] || !value[1]) return;

  const startDate = new Date(value[0]);
  const endDate = new Date(value[1]);

  const maxEndDate = new Date(startDate);
  maxEndDate.setDate(maxEndDate.getDate() + 30);

  if (endDate > maxEndDate) {
    proxy.$modal.msgError('结束日期不能超过开始日期30天以上');
    queryParams.value.dateRange = ['', ''];
  }
};

/** 模糊查询 */
const filterByCertificate = () => {
  if (likeName.value) {
    filteredCertificate.value = certificateList.value.filter((item) => {
      return item.certificateId.includes(likeName.value) || item.certificateName.includes(likeName.value);
    });
  } else {
    filteredCertificate.value = certificateList.value;
  }
};

const CertificateChangeQury = () => {
  if (queryParams.value.certificateId) {
    filteredCostList.value = costList.value.filter((item) => {
      return item.certificateId === queryParams.value.certificateId;
    });
  }
};

/** 模糊查询 */
const filterByManageCom = () => {
  if (likeMangeName.value) {
    filteredManagecom.value = sys_managecom.value.filter((item) => {
      return item.label.includes(likeMangeName.value) || item.value.includes(likeMangeName.value);
    });
  } else {
    filteredManagecom.value = sys_managecom.value;
  }
};

const validateOthers = () => {
  if (queryParams.value.belnrSap && (!queryParams.value.manageCom || !queryParams.value.dateRange)) {
    proxy?.$modal.msgError('凭证号不为空时，机构和日期范围不能为空');
    return false;
  }
  return true;
};

onMounted(() => {
  const route = useRoute();
  const invoicingId = route.query.invoicingId;
  if (invoicingId) {
    loadingPage(typeof invoicingId === 'string' ? invoicingId : invoicingId.toString());
  }
  getCache();
});
</script>

<style scoped lang="scss"></style>
