<template>
  <div class="p-2" v-loading = "loading">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <el-card v-if="form.manualBatchId != undefined" shadow="never">
        <el-form ref="formRef" :model="form" :rules="rules" :inline="true" label-width="130px" label-position="left">
          <el-row :gutter="0">
            <el-form-item label="申请批次号" prop="manualBatchId">
              <el-input v-model="form.manualBatchId" placeholder="请输入申请批次号" readonly />
            </el-form-item>
            <el-form-item label="管理机构" prop="manageCom">
              <el-select v-model="form.manageCom" placeholder="请输入管理机构">
                <template #header>
                  <el-input v-model="likeName" 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="applyDate">
              <el-input v-model="form.applyDate" placeholder="请输入申请日期" readonly />
            </el-form-item>

            <el-form-item v-if="false" label="状态" prop="status">
              <el-input v-model="form.status" placeholder="请输入申请日期" readonly />
            </el-form-item>
          </el-row>
        </el-form>
      </el-card>
    </transition>
    <el-card v-if="form.manualBatchId != undefined" shadow="never">
      <el-table v-loading="attLoading" :data="manaulAttList" style="width: 580px">
        <el-table-column label="附件名称" align="center" prop="originalName" />
        <el-table-column v-if="false" label="ossid" align="center" prop="ossid" />
        <el-table-column v-if="false" label="id" align="center" prop="id" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="下载" placement="top">
              <el-button v-hasPermi="['bfs:manualatt:download']" link type="primary" icon="Download" @click="handleDownload(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card v-if="form.manualBatchId != undefined" shadow="never">
      <el-table v-loading="itemLoading" :data="manaulItemList">
        <el-table-column label="状态" align="center" prop="status" >
          <template #default="scope">
            <dict-tag :options="bfs_manaulitem_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="失败原因" align="center" prop="errorMsg" show-overflow-tooltip/>
        <el-table-column label="摘要" align="center" prop="vchrSmmry" show-overflow-tooltip/>
        <el-table-column label="凭证大类" align="center" prop="certificateId" />
        <el-table-column label="费用大类" align="center" prop="costId" width="150"/>
        <el-table-column label="所属会计年度" align="center" prop="fiscalYear" />
        <el-table-column label="所属会计月度" align="center" prop="fiscalMonth" />
        <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="finItemCode" width="150"/>
        <el-table-column label="明细科目代码" align="center" prop="subItemCode" width="150"/>
        <el-table-column label="保单号" align="center" prop="policyNo" width="200"/>
        <el-table-column label="业务号码" align="center" prop="businessNo" width="200"/>
        <el-table-column label="金额" align="center" prop="amount" />
        <el-table-column label="记账日期" align="center" prop="accountDate" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.accountDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否红字" align="center" prop="isRed" />
        <el-table-column label="做账机构是否集中" align="center" prop="isCentralized" width="150"/>
        <el-table-column label="业务机构" align="center" prop="manageCom" />
        <el-table-column label="交费年期" align="center" prop="payendyear" />
        <el-table-column label="手续费结算单位" align="center" prop="settlementUnit" width="150"/>
        <el-table-column label="银行对账码" align="center" prop="reconCode" width="150" />
        <el-table-column label="险种编码" align="center" prop="riskCode" />
        <el-table-column label="销售渠道" align="center" prop="saleChnl" />
        <el-table-column label="业务渠道" align="center" prop="busiChnl" />
        <el-table-column label="供应商" align="center" prop="intraBranch" />
        <el-table-column label="往来单位分类" align="center" prop="businessPartners" width="150"/>
        <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="accountMark" />
        <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="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getItemList" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {
  applyCancellation,
  applyConfirmation,
  delManualItem,
  getManaulBymanualBatchId,
  importDataManaulBookkeeping,
  listManualItemByBatchId,
  listManualVoucher
} from '@/api/bfs/exception/ManaulBookkeeping';
import {globalHeaders, globalUploadHeaders} from '@/utils/request';
import { parseTime } from '@/utils/ruoyi';

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

const showSearch = ref(true);
const queryFormRef = ref<ElFormInstance>();
const loading = ref(false);
const formRef = ref<ElFormInstance>();
const buttonLoading = ref(false);
const likeName = ref('');
const filteredManagecom = ref([]);
const { bfs_debit_and_credit } = toRefs<any>(proxy?.useDict('bfs_debit_and_credit'));
const { bfs_manaulitem_status } = toRefs<any>(proxy?.useDict('bfs_manaulitem_status'));

const attLoading = ref(false);
const manaulAttList = ref([]);

const itemLoading = ref(false);
const manaulItemList = ref([]);

const total = ref(0);

const initFormData = {
  manualBatchId: undefined,
  manageCom: undefined,
  manualReason: undefined,
  applyDate: undefined,
  status: undefined
};

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    manualBatchId: undefined,
  },
  form: { ...initFormData },
  rules: {}
});
const { queryParams, form, rules } = toRefs(data);

const uploadRef = ref<ElUploadInstance>();
/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalUploadHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});

const loadingPage = async (manualBatchId: string) => {
  const res = await getManaulBymanualBatchId(manualBatchId);
  Object.assign(form.value, res.data.bookkeeping);
  manaulAttList.value = res.data.att;
  getItemList();
};
/** 模糊查询 */
const filterByManageCom = () => {
  if (likeName.value) {
    filteredManagecom.value = sys_managecom.value.filter((item) => {
      return item.label.includes(likeName.value) || item.value.includes(likeName.value);
    });
  } else {
    filteredManagecom.value = sys_managecom.value;
  }
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value.submit();
}

const handleFileSuccess = async (response, file, fileList) => {
  // 从响应数据中获取 id
  const ossId = response.data.ossId;
  const manualBatchId = form.value.manualBatchId;
  const data = {
    ossId,
    manualBatchId
  };
  const res = await importDataManaulBookkeeping(data);
  if (res.data.bookkeeping.manualBatchId != manualBatchId) {
    const newPath = `/bfs/exception/manual-voucher-detail/manualBatchId`;
    const routeObj = {
      path: newPath,
      query: {
        manualBatchId: res.data.bookkeeping.manualBatchId
      }
    };
    proxy?.$modal.msgSuccess('导入成功');
    proxy?.$tab.closePage();
    proxy?.$tab.refreshPage(routeObj);
  } else {
    loadingPage(manualBatchId);
    upload.open = false;
    upload.isUploading = false;
    uploadRef.value?.handleRemove(file);
    proxy?.$modal.msgSuccess('导入成功');
  }
};

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '导入';
  upload.open = true;
};

/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('bfs/manualVoucher/importTemplate', {}, `manualVoucher_${new Date().getTime()}.xlsx`);
};

const getItemList = async () => {
  itemLoading.value = true;
  queryParams.value.manualBatchId = form.value.manualBatchId;
  const res = await listManualItemByBatchId(queryParams.value);
  manaulItemList.value = res.rows;
  total.value = res.total;
  itemLoading.value = false;
};

/** 下载按钮操作 */
const handleDownload = (row) => {
  proxy?.$download.oss(row.ossid);
};

const handleDelete = async (row) => {
  const res = await delManualItem(row.id);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('删除成功');
    loadingPage(form.value.manualBatchId);
  }
};

const handleApply = async () => {
  loading.value = true;
  try {
    const res = await applyConfirmation(form.value);
    if (res.code === 200) {
      proxy?.$modal.msgSuccess('提交成功');
      proxy?.$tab.closePage();
    }
  } finally {
    loading.value = false;
  }
};

const handleReset = async () => {
  loading.value = true;
  try {
    const res = await applyCancellation(form.value);
    if (res.code === 200) {
      proxy?.$modal.msgSuccess('取消申请操作成功');
      proxy?.$tab.closePage();
    }
  } finally {
    loading.value = false;
  }
};

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

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