<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">
            <el-form-item label="业务号码" prop="bussnessNo">
              <el-input v-model="queryParams.bussnessNo" placeholder="请输入业务号码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="管理机构" prop="manageCom">
              <el-select v-model="queryParams.manageCom" clearable placeholder="请输入管理机构">
                <template #header>
                  <el-input v-model="likeName" placeholder="可根据机构编码或名称模糊查询" @input="filterByManageCom"></el-input>
                </template>
                <el-option
                  v-for="dict in filteredManagecom"
                  :key="dict.dictValue"
                  :label="dict.dictValue + '-' + dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </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-row>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="infoList">
        <el-table-column label="业务号码" align="center" prop="bussnessNo" />
        <el-table-column label="归属系统" align="center" prop="fromSystem" />
        <el-table-column label="费用类型名称" align="center" prop="feeTypeName" />
        <el-table-column label="归属机构" align="center" prop="manageCom" />
        <el-table-column label="收据总金额" align="center" prop="totalAmount" />
        <el-table-column label="收据机构" align="center" prop="trustorName" />
        <el-table-column label="打印次数" align="center" prop="printTimes" />
        <el-table-column label="收据是否拆分" align="center" prop="splitMark" />
        <el-table-column label="业务员编码" align="center" prop="agentCode" />
        <el-table-column label="业务员姓名" align="center" prop="agentName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button v-hasPermi="['bls:receipt:detail']" link type="primary" icon="Document" @click="handleDetail(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.printTimes > 0" content="下载收据" placement="top">
              <el-button v-hasPermi="['bls:receipt:print']" link type="primary" icon="Printer" @click="handleDownLoad(scope.row)"></el-button>
            </el-tooltip>
<!--            <el-tooltip content="数据作废" placement="top">-->
<!--              <el-button v-hasPermi="['bls:receipt:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>-->
<!--            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="80%" append-to-body>
      <el-form ref="infoFormRef" :model="form" :rules="rules" label-width="180px">
        <el-row>
          <el-form-item label="业务号码" prop="bussnessNo">
            <el-input v-model="form.bussnessNo" readonly />
          </el-form-item>
          <el-form-item label="归属系统" prop="fromSystem">
            <el-select v-model="form.fromSystem" placeholder="请输入管理机构" style="width: 168px">
              <el-option v-for="dict in sys_from_system" :key="dict.value" :label="dict.label" :value="dict.value" :disabled="true"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="归属机构" prop="manageCom">
            <el-select v-model="form.manageCom" readonly style="width: 168px">
              <el-option v-for="dict in sys_managecom" :key="dict.value" :label="dict.label" :value="dict.value":disabled="true" ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="收据总金额" prop="totalAmount">
            <el-input v-model="form.totalAmount" readonly />
          </el-form-item>
          <el-form-item label="业务员编码" prop="agentCode">
            <el-input v-model="form.agentCode" readonly />
          </el-form-item>
          <el-form-item label="业务员姓名" prop="agentName">
            <el-input v-model="form.agentName" readonly />
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="是否拆分" prop="splitMark">
            <el-input v-model="form.splitMark" readonly />
          </el-form-item>
          <el-form-item label="费用类型名称" prop="feeTypeName">
            <el-input v-model="form.feeTypeName" type="textarea" readonly />
          </el-form-item>
        </el-row>
        <!-- 隐藏数据区域 -->
        <el-row v-if="false">
          <el-form-item prop="receiptId">
            <el-input v-model="form.receiptId" />
          </el-form-item>
          <el-form-item prop="printTimes">
            <el-input v-model="form.printTimes" />
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="打印模版" prop="tempId">
            <el-select v-model="form.tempId" style="width: 168px">
              <el-option
                v-for="dict in templateList"
                :key="dict.id"
                :label="dict.templateName + '-v' + dict.versionNumber"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <el-table :data="showSplitList">
        <el-table-column label="费用类型名称" align="center" prop="feeTypeName" />
        <el-table-column label="收据机构" align="center" prop="trustorName" />
        <el-table-column label="收据总金额" align="center" prop="amount" />
      </el-table>

      <el-row style="margin-top: 20px; margin-right: 20px">
        <el-button
          v-if="form.printTimes === 0 || form.printTimes === null"
          v-hasPermi="['bls:receipt:print']"
          type="primary"
          icon="Printer"
          @click="handlePrintByFrom"
          >打印收据</el-button
        >
        <el-button
          v-if="form.printTimes === 0 || form.printTimes === null"
          v-hasPermi="['bls:receipt:preview']"
          type="primary"
          icon="Printer"
          @click="handlePreviewByFrom"
          >收据预览</el-button
        >
        <el-button v-if="form.printTimes > 0" v-hasPermi="['bls:receipt:download']" type="primary" icon="Download" @click="handleDownload"
          >收据下载</el-button
        >
        <el-button v-if="form.printTimes > 0" v-hasPermi="['bls:receipt:reprint']" type="primary" icon="Printer" @click="handleRePrintByFrom"
          >重打收据</el-button
        >
<!--        <el-button v-hasPermi="['bls:receipt:remove']" type="primary" icon="Delete" @click="handleDeleteByFrom">收据作废</el-button>-->
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup name="ReceiptInfo" lang="ts">
import {
  deleteData,
  getPrintData,
  getTemplate,
  listInfo,
  listSplit, PrintPreviewReceipt,
  PrintReceipt,
  showDetail
} from '@/api/bls/receipt';
import {queryManageCom} from "@/api/bls/cache";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

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

const infoList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const showSplitList = ref([]);
const infoFormRef = ref<ElFormInstance>();
const templateList = ref([]);
const likeName = ref('');
const filteredManagecom = ref([]);
const sys_managecomCache = ref([]);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initFormData = {
  bussnessNo: undefined,
  fromSystem: undefined,
  manageCom: undefined,
  totalAmount: undefined,
  agentCode: undefined,
  agentName: undefined,
  splitMark: undefined,
  feeTypeName: undefined,
  tempId: undefined,
  receiptId: undefined,
  printTimes: undefined
};
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    bussnessNo: undefined,
    manageCom: undefined,
    status: 'Y',
    params: {}
  },
  form: { ...initFormData },
  rules: {
    tempId: [{ required: true, message: '收据模版不能为空', trigger: 'blur' }]
  }
});
const { queryParams, form, rules } = toRefs(data);

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

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

/** 查询收据信息总列表 */
const getList = async () => {
  loading.value = true;
  const res = await listInfo(queryParams.value);
  infoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/**
 * 查看详情
 */
const handleDetail = async (row) => {
  reset();
  dialog.title = '查看收据信息详情';
  dialog.visible = true;
  const res = await showDetail(row.receiptId);
  Object.assign(form.value, res.data.receiptInfo);
  showSplitList.value = res.data.splitList;
};

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

/**
 * 获取有效打印模版
 */
const getTemplateList = async () => {
  const res = await getTemplate();
  templateList.value = res.data;
};

/**
 * 打印收据
 */
const handlePrintByFrom = async () => {
  const data = {
    receiptId: form.value.receiptId,
    tempId: form.value.tempId,
    rePrint: false
  };
  const res = await PrintReceipt(data);
  if (res.code === 200) {
    DownloadFile(res.data.ossId);
  }
  dialog.visible = false;
};

/**
 * 收据预览
 */
const handlePreviewByFrom = async () => {
  const data = {
    receiptId: form.value.receiptId,
    tempId: form.value.tempId,
    rePrint: false
  };
  const res = await PrintPreviewReceipt(data);
  if (res.code === 200) {
    DownloadFile(res.data.ossId);
  }
  dialog.visible = false;
};

/**
 * 重打打印收据
 */
const handleRePrintByFrom = async () => {
  const data = {
    receiptId: form.value.receiptId,
    tempId: form.value.tempId,
    rePrint: true
  };
  const res = await PrintReceipt(data);
  if (res.code === 200) {
    DownloadFile(res.data.ossId);
  }
  dialog.visible = false;
  await getList();
};

/**
 * 根据form表单内容下载
 */
const handleDownload = async () => {
  const data = {
    receiptId: form.value.receiptId
  };
  await getDownLoad(data);
};

/**
 * 根据行内容下载
 */
const handleDownLoad = async (row) => {
  const data = {
    receiptId: row.receiptId
  };
  await getDownLoad(data);
};

/**
 * 获取打印有效记录
 */
const getDownLoad = async (data) => {
  const res = await getPrintData(data);
  if (res.code === 200) {
    DownloadFile(res.data.ossId);
  }
};

/**
 * 下载文件
 */
const DownloadFile = (ossId) => {
  proxy?.$download.oss(ossId);
};

const handleDeleteByFrom = async () => {
  await proxy?.$modal.confirm('是否要作废业务号码为' + form.value.bussnessNo + '的数据?');
  const res = await deleteData(form.value);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('作废成功');
    await getList();
  }
};

const handleDelete = async (row) => {
  await proxy?.$modal.confirm('是否要作废业务号码为' + row.bussnessNo + '的数据?');
  const res = await deleteData(row);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('作废成功');
    await getList();
  }
};

/** 模糊查询 */
const filterByManageCom = () => {
  if (likeName.value) {
    filteredManagecom.value = sys_managecomCache.value.filter((item) => {
      return item.dictLabel.includes(likeName.value) || item.dictValue.includes(likeName.value);
    });
  } else {
    filteredManagecom.value = sys_managecomCache.value;
  }
};
const getCache = async () => {
  const res = await queryManageCom();
  if (res.code == 200) {
    sys_managecomCache.value = res.data;
    filteredManagecom.value = sys_managecomCache.value;
  }
};

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

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