<template>
  <q-btn v-if="showComputed" icon="calculate" color="primary" label="试算" :disable="testCalcNum < 1" @click="click">
    <q-badge :color="testCalcNum > 3 ? 'green' : 'red'" floating
      >{{ testCalcNum }}
      <q-tooltip> 剩余可试算次数 </q-tooltip>
    </q-badge>
  </q-btn>
</template>
<script setup lang="ts">
import { ref, inject, computed, onBeforeMount } from 'vue';
import { useQuasar } from 'quasar';
import { axios, Environment, NotifyManager, Tools } from 'platform-core';
import { Rating } from './ts/Rating';
import { Step } from './ts/Step';
import { Constant } from './ts/Constant';
import { round } from './ts/Utils';

const $q = useQuasar();
const rating = <Rating>inject('rating');
const testCalcNum = ref(0);

const getTestCalcNum = async () => {
  const resp = await axios.get(Environment.apiContextPath('api/irbs/companyRating/getQualTestCalcNum'), {
    params: { ratingId: rating.ratingData.value['id'] },
  });
  if (resp?.data) {
    testCalcNum.value = resp.data;
  }
};

const click = async () => {
  const result = rating.step.qualFormValidate();
  if (!result['result']) {
    return;
  }
  rating.showLoading('正在计算定性得分，请稍等...');
  const url = Environment.apiContextPath('api/irbs/companyRating/qualSaveIndices/' + Constant.QUAL_SAVE_OPERATOR.TEST);
  const resp = await axios.post(url, result['submitData']).catch((error) => {
    rating.hideLoading();
    NotifyManager.error('计算出错，请联系管理员');
    console.info('error====', error);
  });
  rating.hideLoading();
  if (resp?.data?.success === true) {
    rating.ratingData.value['lastQualTestCalcScore'] = round(resp.data.qualScore, 2);
    $q.dialog({
      title: '消息',
      message: '本次试算定性得分为：' + round(resp.data.qualScore, 2),
      cancel: false,
      persistent: true,
    });
    // 获取最新试算次数
    getTestCalcNum();
  } else if (resp?.data?.success === false && !Tools.isEmpty(resp.data.errorMsg)) {
    if (rating.ratingData.value['lastQualTestCalcScore']) {
      NotifyManager.error(resp.data.errorMsg + '，与最后一次试算结果相同，得分为：' + rating.ratingData.value['lastQualTestCalcScore']);
    } else {
      NotifyManager.error(resp.data.errorMsg);
    }
  }
};

const showComputed = computed(() => {
  if (rating.cm.isApplyUserProcessStatus.value && rating.step.currStep.value === Step.type.quanQualAnalysis.value) {
    return true;
  }
  return false;
});

onBeforeMount(() => {
  getTestCalcNum();
});
</script>
