<script setup name='projectTreasuryDetail'>
import { getCurrentInstance, h, reactive, ref, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { renewalProjectAsscess } from '@/http/apis/projectStoreManage/renewalProjectTreasury.js'
import { renewalDeclaredDetail } from '@/http/apis/declareMange/renewalProjectCapitalDeclare'
import store from '@/store'
import { contractDetail } from '@/http/apis/declareMange/contractRecord'
const tableListRef = ref(),
  { statusOptions, statusGjOptions, projectTypeOptions } = store.dictStore.globalDicts || {},
  ruleFormRef = ref(),
  router = useRouter(),
  route = useRoute(),
  total = ref(0),
  dialogFormVisible = ref(false),
  { proxy } = getCurrentInstance(),
  // 列表数据
  column = reactive([
    {
      label: '项目名称',
      key: 'projectName',
      prop: 'projectName'
    },
    {
      label: '项目类型',
      key: 'projectType',
      prop: 'projectType',
      minWidth: '80',
      render: row => h('span', projectTypeOptions[row.projectType] || '-')
    },
    {
      label: '批复总金额（万元）',
      key: 'approvalAmount',
      prop: 'approvalAmount'
    },
    {
      label: '累计年度投资资金',
      key: 'annualAccumulateAmountList',
      slot: 'annualAccumulateAmountList'
    },
    {
      label: '项目状态',
      key: 'status',
      prop: 'status',
      render: row => [
        h('span', {
          class: ['dot mr-4', `bg-${statusOptions[row.status]?.color || statusGjOptions[row.status]?.color}`]
        }),
        h(
          'span',
          {
            class: `text-${statusOptions[row.status]?.color || statusGjOptions[row.status]?.color}`
          },
          row.status && statusOptions[row.stage]?.name ? `${statusOptions[row.stage]?.name}-${statusOptions[row.status]?.name}` : statusGjOptions[row.status]?.name || '-'
        )
      ]
    }
  ]),
  data = ref([]),
  form = reactive({}),
  rules = reactive({
    auditOpinion: [
      { required: true, message: '请填写审核意见', trigger: 'blur' }
    ]
  }),
  submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        await renewalProjectAsscess({ projectRenewalId: route.query.projectRenewalId * 1, result: false, auditOpinion: form.auditOpinion })
        form.auditOpinion = undefined
        proxy.$message.success('审核意见提交成功！')
        dialogFormVisible.value = false
        getDetail()
        router.push({ name: 'renewalProjectTreasury' })
      } else {
        console.log('error submit!', fields)
      }
    })
  },
  adopt = () => {
    proxy.$messageBox
      .confirm('确认审核通过吗?', '提示！', {
        type: 'warning'
      })
      .then(async () => {
        await renewalProjectAsscess({ projectRenewalId: route.query.projectRenewalId * 1, result: true })
        proxy.$message.success('审核通过！')
        getDetail()
        router.push({ name: 'renewalProjectTreasury' })
      })
  },
  routeName = ref(''),
  detailData = ref({}),
  getDetail = async () => {
    const res = await renewalDeclaredDetail(route.query.projectRenewalId)
    detailData.value = res.data
    data.value = [{ ...res.data }]
    getPayInfo(data.value[0].projectId)
  },
  // 支付信息
  payColumn = [
    {
      label: '付款笔数',
      key: 'number',
      slot: 'number'
    },
    {
      label: '付款计划',
      key: 'planAmount',
      slot: 'planAmount'
    },
    {
      label: '付款比例（%）',
      key: 'ratio',
      slot: 'ratio'
    },
    {
      label: '付款金额（万元）',
      key: 'paymentAmount',
      slot: 'paymentAmount'
    },
    {
      label: '预计付款时间',
      key: 'paymentTime',
      slot: 'paymentTime'
    },
    {
      label: '实际支付金额（万元）',
      key: 'actualPaymentAmount',
      slot: 'actualPaymentAmount',
      width: 180
    }
  ],
  paymentsData = ref(),
  getPayInfo = async (id) => {
    const res = await contractDetail(id)
    paymentsData.value = res?.data?.payments || []
  }
watch(
  route,
  (val) => {
    routeName.value = route.meta.title
  },
  { immediate: true, deep: true }
)
onMounted(() => {
  getDetail()
})
</script>

<template>
  <div class="">
    <el-alert
      v-if="detailData.approvalStatus==='NOT_PASS'"
      title="审核不通过"
      type="error"
      :description="`审核意见：${detailData.auditOpinion}`"
      show-icon
    />
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>申报信息</span>
        </div>
      </template>
      <div class="flex justify-around">
        <div class="flex-shrink-0 text-14">关联项目：</div>
        <table-list
          ref="tableListRef"
          :column="column"
          :data="data"
          :total="total"
          :height="200"
          :pagination="false"
          class="flex-1"
        >
          <template #annualAccumulateAmountList="{scope}">
            <p v-for="(item,index) in scope.row.annualAccumulateAmountList" :key="index">{{ index+1 }}、{{ item.projectYear }}年投资{{ item.annualAmount }}万元</p>
          </template>
        </table-list>
      </div>
      <p class="font-bold mb-8">支付信息</p>
      <table-list
        ref="tableListRef"
        :column="payColumn"
        :data="paymentsData"
        :pagination="false"
        :empty-temp="false"
        class="mb-16"
      >
        <template #number="{scope}">
          <span>第{{ scope.$index+1 }}笔</span>
        </template>
        <template #planAmount="{scope}">
          {{ scope.row.planAmount }}
        </template>
        <template #ratio="{scope}">
          {{ scope.row.ratio }}
        </template>
        <template #paymentAmount="{scope}">
          {{ scope.row.paymentAmount }}
        </template>
        <template #paymentTime="{scope}">
          {{ scope.row.paymentTime }}
        </template>
        <template #actualPaymentAmount="{scope}">
          {{ scope.row.actualPaymentAmount }}
        </template>
      </table-list>
      <template v-if="detailData.annualAccumulateAmountList?.filter((i,key)=>key!==0&&i.projectYear!==detailData.projectYear)?.length">
        <p class="font-bold mt-20">历史续建资金信息</p>
        <el-descriptions
          v-for="(item,index) in detailData.annualAccumulateAmountList.filter((i,key)=>key!==0&&i.projectYear!==detailData.projectYear)"
          :key="index"
          class="mt-20"
          :column="2"
          border
        >
          <el-descriptions-item
            label="预算年度"
            span="1"
            width="250px"
          >
            {{ item.projectYear }}
          </el-descriptions-item>
          <el-descriptions-item
            :label="`${item.projectYear}年支付金额（万元）`"
            width="250px"
          >
            {{ item.annualAmount }}
          </el-descriptions-item>
          <el-descriptions-item label="自有金额（万元）">
            {{ item.haveAmount }}
          </el-descriptions-item>
          <el-descriptions-item label="政府投资-本级财政资金（万元）">
            {{ item.govOwnFinanceAmount }}
          </el-descriptions-item>
          <el-descriptions-item label="政府投资-上级补助资金（万元）">
            {{ item.govSuperiorFinanceAmount }}
          </el-descriptions-item>
          <el-descriptions-item label="银行贷款（万元）">
            {{ item.bankLendingAmount }}
          </el-descriptions-item>
          <el-descriptions-item
            label="其他（万元）"
            span="2"
          >
            {{ item.otherAmount }}
          </el-descriptions-item>
        </el-descriptions>
      </template>
      <el-descriptions
        class="mt-20"
        title="申报续建资金信息"
        :column="2"
        border
      >
        <el-descriptions-item
          label="预算年度"
          span="1"
          width="250px"
        >
          {{ detailData.projectYear }}
        </el-descriptions-item>
        <el-descriptions-item
          label="下一年度支付金额（万元）"
          width="250px"
        >
          {{ detailData.annualPaymentAmount }}
        </el-descriptions-item>
        <el-descriptions-item label="自有金额（万元）">
          {{ detailData.haveAmount }}
        </el-descriptions-item>
        <el-descriptions-item label="政府投资-本级财政资金（万元）">
          {{ detailData.govOwnFinanceAmount }}
        </el-descriptions-item>
        <el-descriptions-item label="政府投资-上级补助资金（万元）">
          {{ detailData.govSuperiorFinanceAmount }}
        </el-descriptions-item>
        <el-descriptions-item label="银行贷款（万元）">
          {{ detailData.bankLendingAmount }}
        </el-descriptions-item>
        <el-descriptions-item
          label="其他（万元）"
          span="2"
        >
          {{ detailData.otherAmount }}
        </el-descriptions-item>
      </el-descriptions>
      <div class="flex justify-center items-center mt-10">
        <el-button
          v-if="routeName =='续建项目资金库详情'&&detailData.approvalStatus==='NOT_PASS'"
          class="mr-20"
          type="primary"
          @click="$router.push({name:'storeRenewalCapitalDeclare',query:{id:detailData.id}})"
        >重新申报</el-button>
        <template v-if="detailData.approvalStatus==='PENDING'">
          <el-button
            v-if="routeName !=='续建项目资金库详情'"
            class="mr-20"
            type="primary"
            @click="adopt"
          >通过</el-button>
          <el-button
            v-if="routeName !=='续建项目资金库详情'"
            class="mr-20"
            type="danger"
            @click="dialogFormVisible = true"
          >不通过</el-button>
        </template>
        <el-button
          plain
          @click="$router.go(-1)"
        >返回</el-button>
      </div>
    </el-card>
    <el-dialog
      v-model="dialogFormVisible"
      title="不通过"
    >
      <el-form
        ref="ruleFormRef"
        :model="form"
        :rules="rules"
        status-icon
      >
        <el-form-item
          label="审核意见"
          label-width="auto"
          prop="auditOpinion"
        >
          <el-input
            v-model="form.auditOpinion"
            maxlength="200"
            placeholder="请输入"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            type="primary"
            @click="submitForm(ruleFormRef)"
          >
            提交
          </el-button>
          <el-button @click="dialogFormVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang='less' scoped> </style>
