<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-page-header @back="Cancel" class="mb-[10px]">
          <template #content>
            <span class="text-large font-600 mr-3"> 查看 </span>
          </template>
        </el-page-header>
        <div class="mb-[10px] flex text-[14px] pt-2 pb-2 pl-4 pr-4 gap-[20px]">
          <div class="w-[240px] flex" v-for="item in info">
            <div class="w-[auto] pr-[12px] text-right">{{ item.label }}：</div>
            <div class="flex-1">{{ item.value }}</div>
          </div>
        </div>

        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="warning" plain @click="exportList">导出列表</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain @click="exportInvoice">批量导出发票</el-button>
              </el-col>
              <right-toolbar :search="false" @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="expertName" />
            <el-table-column label="职称等级" prop="proLevel" />
            <el-table-column label="电话" prop="contact" />
            <el-table-column label="身份证号" prop="idcard" />
            <el-table-column label="参与评审阶段" prop="reviewSn">
              <template #default="{ row }">
                {{ item_stage.find((e) => e.value == row.reviewSn)?.label + '阶段' || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="费用标准" prop="expertMoney">
              <template #default="{ row }">{{ row.expertMoney || 0 }}元/次</template>
            </el-table-column>
            <el-table-column label="费用总额" prop="expertTypeMoneyFee">
              <template #default="{ row }">{{ row.expertTypeMoneyFee || 0 }}元/次</template>
            </el-table-column>
            <el-table-column label="开票情况" prop="invStu" />
            <el-table-column label="开票金额" prop="invoiceMoney">
              <template #default="{ row }">{{ row.invoiceMoney || 0 }}元</template>
            </el-table-column>
            <el-table-column label="发票" prop="invoice" align="center" width="100px">
              <template #default="{ row }">
                <!-- <a :href="scope.row.url || ''" :download="row.voucherCode" class="download" target="_blank">{{ row.voucherCode }}</a> -->
                <el-button type="primary" :disabled="row.invStu === '未开票'" link @click="downloadInvoice(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>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { getDetailList, getOssIds } from '@/api/expertMoneyConfig/audit';
import { listPosition } from '@/api/expert/person/index';
import { getFile } from '@/api/filemanage';
import { globalHeaders } from '@/utils/request';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { item_stage } = toRefs<any>(proxy?.useDict('item_stage'));
const { invoicing_status } = toRefs<any>(proxy?.useDict('invoicing_status'));
const showSearch = ref(true);

const route = useRoute();

const id = computed(() => route.query.id);
const productName = computed(() => route.query.productName);
const reviewSn = computed(() => route.query.reviewSn);
const projectYear = computed(() => route.query.projectYear);
const productScale = computed(() => route.query.productScale);

const page = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

const info = computed(() => {
  let review_sn = item_stage.value.find((e) => e.value == reviewSn.value)?.label || '-';
  return [
    {
      label: '项目名称',
      value: productName.value
    },
    {
      label: '项目阶段',
      value: review_sn
    },
    {
      label: '项目年份',
      value: projectYear.value
    },
    {
      label: '项目规模',
      value: productScale.value + '万元'
    }
  ];
});

/** 重置按钮操作 */
const tableRows = ref([]);
const loading = ref(false);
const getList = async () => {
  loading.value = true;
  let res = await getDetailList({
    productId: id.value,
    reviewSn: reviewSn.value,
    ...page.value
  }).finally(() => {
    loading.value = false;
  });
  tableRows.value = res.rows;
};
const Cancel = () => {
  proxy?.$tab.closePage(proxy?.$route).then(() => {
    proxy?.$router.replace({
      path: '/expertmoneyconfig/audit'
    });
  });
};
//职称列表
const positionList = ref([]);
const getpositionList = async () => {
  const res = await listPosition();
  positionList.value = res.data;
};
const exportList = () => {
  proxy?.download(
    '/zjk-api/inoutCheck/export',
    {
      productId: id.value
    },
    `财务审计支持详情_${new Date().getTime()}.xlsx`
  );
};
const exportInvoice = async () => {
  let res = await getOssIds({
    productId: id.value,
    reviewSn: reviewSn.value
  });
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
  }
  downloadFile(`${import.meta.env.VITE_APP_BASE_API}/resource/oss/downloadToZip/${res.data.join(',')}`, '批量导出发票.zip');
};
const downloadInvoice = async (row) => {
  let fileRes = await getFile(row.invFileId);
  if (fileRes.code != 200) {
    ElNotification({
      title: '提示',
      message: fileRes.msg,
      type: 'error'
    });
  }
  downloadFile(fileRes.data[0].url, fileRes.data[0].originalName);
};

async function downloadFile(url, filename) {
  try {
    const response = await fetch(url, {
      headers: globalHeaders()
    });
    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);
  }
}
watch(
  [() => id.value, () => reviewSn.value],
  ([_id, r_s]) => {
    if (!_id || !r_s) return;
    getList();
    getpositionList();
  },
  {
    deep: true,
    immediate: true
  }
);
</script>
