<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch">
        <el-card shadow="hover" class="mb-[10px]">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="对账批次" prop="checkNo">
              <el-input v-model="queryParams.checkNo" placeholder="请输入对账批次"></el-input>
            </el-form-item>
            <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 shadow="never">
          <template #header>
            <el-row :gutter="10">
              <el-col :span="1.5">
                <el-button type="primary" plain @click="add">新增</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="tableRows">
            <el-table-column label="序号" type="index" width="50px"></el-table-column>
            <el-table-column label="对账批次" prop="checkNo" />
            <el-table-column label="对账周期" prop="date">
              <template #default="{ row }"> {{ row.checkRangeStart }} ~ {{ row.checkRangeEnd }} </template>
            </el-table-column>
            <el-table-column label="操作员" prop="createBy" />
            <el-table-column label="操作" width="120px">
              <template #default="{ row }">
                <el-button type="primary" link @click="view(row)">查看</el-button>
                <el-divider direction="vertical" />
                <el-button type="primary" link @click="deleteRow(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="page.total > 0" :total="page.total" v-model:page="page.pageNum" v-model:limit="page.pageSize" @pagination="getList" />
        </el-card>
        <el-dialog :title="activeRow ? '查看' : '新增'" width="600px" v-model="visible" :before-close="cancel">
          <el-form ref="dialogFormRef" :model="form" label-width="auto" :rules="rules">
            <el-form-item label="对账批次">
              <el-input v-model="form.checkNo" disabled placeholder="提交自动生成，不可编辑" v-if="!activeRow"></el-input>
              <span v-else>{{ form.checkNo }}</span>
            </el-form-item>
            <el-form-item label="对账周期" prop="date">
              <el-date-picker
                v-if="!activeRow"
                v-model="form.date"
                type="datetimerange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                range-separator="~"
              ></el-date-picker>
              <span v-else>{{ form.date.join(' ~ ') }}</span>
            </el-form-item>
            <el-form-item :label="activeRow ? '对账附件' : '上传对账附件'" prop="file">
              <el-upload
                v-if="!activeRow"
                ref="uploadRef"
                :action="upload.url"
                :auto-upload="true"
                :headers="upload.headers"
                :limit="1"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :on-exceed="handleExceed"
                accept=".xlsx, .xls, .doc, .docx, .txt, .zip, .pdf"
                drag
                style="flex: 1"
                :file-list="fileLists"
              >
                <el-icon class="el-icon--upload">
                  <i-ep-upload-filled />
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <!-- <template #tip>
                  <div class="text-center el-upload__tip">
                    <span>支持后缀为 .xls、.xlsx、.doc、.docx、.txt、.zip、.pdf 且大小不超过 200MB的文件，最多上传 10个文件</span>
                  </div>
                </template> -->
              </el-upload>
              <div class="flex-1 justify-between items-center flex" v-else>
                <span>{{ fileLists?.[0]?.originalName }}</span>
                <el-button link type="primary" @click="downloadFile(fileLists?.[0]?.url, fileLists?.[0]?.originalName)">下载</el-button>
              </div>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submit" v-if="!activeRow">确 定</el-button>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { getTableList, addReconciliation, delReconciliation } from '@/api/expertMoneyConfig/reconciliation';
import { globalHeaders } from '@/utils/request';
import { getFile } from '@/api/filemanage';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const showSearch = ref(true);
const upload = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});

const page = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const queryFormRef = ref();
const queryParams = ref<any>({
  checkNo: ''
});

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
const tableRows = ref([]);
const loading = ref(false);
const getList = async () => {
  loading.value = true;
  let res = await getTableList({
    ...queryParams.value,
    ...page.value
  });
  tableRows.value = res.rows;
  loading.value = false;
};
const dialogFormRef = ref();
const visible = ref(false);
const activeRow = ref(null);
const form = reactive({
  checkNo: '',
  date: [],
  file: null
});
const rules = {
  date: [{ required: true, message: '请选择对账周期', trigger: 'change' }],
  file: [{ required: true, message: '请上传对账附件', trigger: 'change' }]
};
const fileLists = ref([]);
const add = () => {
  visible.value = true;
  activeRow.value = null;
  form.checkNo = '';
  form.date = [];
  form.file = null;
  fileLists.value = [];
};
const view = async (row) => {
  visible.value = true;
  activeRow.value = row;
  form.checkNo = row.checkNo;
  form.date = [row.checkRangeStart, row.checkRangeEnd];
  form.file = row.fileId;
  let res = await getFile(form.file);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
  }
  fileLists.value = res.data;
};
const deleteRow = (row) => {
  ElMessageBox.confirm('是否确认删除', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await delReconciliation(row.id);
      if (res.code != 200) {
        ElNotification({
          title: '提示',
          message: res.msg,
          type: 'error'
        });
        return;
      }
      ElNotification({
        title: '提示',
        message: '删除成功',
        type: 'success'
      });
      getList();
    })
    .catch(() => {});
};
const cancel = () => {
  dialogFormRef.value?.resetFields();
  visible.value = false;
};
const handleExceed = () => {
  ElNotification({
    title: '提示',
    message: '附件只允许上传一个',
    type: 'error'
  });
};
const handleRemove = () => {
  form.file = null;
  fileLists.value = [];
};
const handleSuccess = (res) => {
  form.file = res.data.ossId;
};
function submit() {
  dialogFormRef.value?.validate(async (valid) => {
    if (!valid) return;
    const params = {
      ...form,
      checkRangeStart: form.date?.[0] || '',
      checkRangeEnd: form.date?.[1] || '',
      fileId: form.file
    };
    let res = await addReconciliation(params);
    if (res.code != 200) {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      });
      return;
    }
    ElNotification({
      title: '提示',
      message: '新增成功',
      type: 'success'
    });
    cancel();
    getList();
  });
}
async function downloadFile(url, filename) {
  try {
    const response = await fetch(url);
    const blob = await response.blob();
    const blobUrl = window.URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = blobUrl;
    a.download = filename || 'document.pdf';
    document.body.appendChild(a);
    a.click();
    
    // 清理
    window.URL.revokeObjectURL(blobUrl);
    document.body.removeChild(a);
  } catch (error) {
    console.error('下载失败:', error);
  }
}
onMounted(() => {
  getList();
});
</script>
