<template>
  <div class="flex flex-col h-full">
    <div class="bg-white info flex-1 overflow-y-auto cellnormall">
      <van-cell title="合同编号" :value="infoData.number" />
      <van-cell title="合同名称" :value="infoData.name" />
      <van-cell title="合同金额" :value="infoData.amounts">
        <template #default>
          <span class="text-[#FF8B32]" v-if="infoData.amounts">¥ {{ infoData.amounts }}</span>
        </template>
      </van-cell>
      <van-cell title="已回款金额" :value="infoData.payment">
        <template #default>
          <span class="text-[#FF8B32]" v-if="infoData.payment">¥ {{ infoData.payment }}</span>
        </template>
      </van-cell>
      <van-cell title="已回款进度" :value="infoData.payment">
        <template #default>
          {{ infoData.payment ? (100 * infoData.payment / infoData.amounts).toFixed(1) + '%' : '0%' }}
        </template>
      </van-cell>
      <van-cell title="计划开始时间" :value="infoData.startDate" />
      <van-cell title="计划结束时间" :value="infoData.endDate" />
      <van-cell title="下笔回款日期" :value="infoData.nextPaymentDate">
        <template #default>
          {{ infoData.nextPaymentDate ? infoData.nextPaymentDate : '-' }}
        </template>
      </van-cell>
      <van-cell title="下笔回款金额" :value="infoData.payment">
        <template #default>
          <span class="text-[#FF8B32]" v-if="infoData.payment">¥ {{ infoData.payment.toFixed(2) }}</span>
        </template>
      </van-cell>
      <van-cell title="合同类型" :value="infoData.typeName" />
      <van-cell title="状态" :value="infoData.status">
        <template #default>
          <span :style="fixedFieldStatusArray[infoData.status].color">
            {{ fixedFieldStatusArray[infoData.status].label }}
          </span>
        </template>
      </van-cell>
    </div>
    <div class="bottomButton">
      <template v-if="infoData.status == 1">
        <van-button type="success" class="w-full block" @click="adoptOperation">通过合同</van-button>
        <van-button type="danger" class="w-full block" @click="rejectOperation">驳回合同</van-button>
      </template>
      <van-button type="default" class="w-full block" v-permission="[routingInformation.jurisdiction.edit]"
        @click="jumpEdit()">编辑合同</van-button>
      <van-button type="danger" class="w-full block" v-permission="[routingInformation.jurisdiction.delete]"
        @click="deleteRow()">删除合同</van-button>
    </div>

    <!-- 驳回弹窗 -->
    <van-dialog v-model:show="showDialog" :title="`驳回合同`" show-cancel-button @confirm="confirmTransfer"
      :before-close="dialogCloseBefo">
      <template #default>
        <van-field v-model.trim="dialogSelection" type="textarea" rows="3" label="驳回原因" placeholder="请输入驳回原因" />
      </template>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import requests from "@common/requests";
import { showConfirmDialog } from 'vant';
import { useLifecycle } from '@hooks/useCommon.js';
import { fixedFieldStatusArray } from '@/utility/defaultData.js';
import { CONTRACT_APPROVED, OBTAIN_CONTRACT_DETAILS } from '@hooks/useApi'
import useShowToast from '@hooks/useToast'
import useInfoStore from '@store/useInfoStore'
import useRouterStore from "@store/useRouterStore.js";
import { routingInfos } from "@utility/generalVariables"
import { resetListData, getListFieldKey } from '@components/common/formForm/formCorrespondenceProcessing'
import useFixedData from "@store/useFixedData.js"

const fixedData = useFixedData()
const router = useRouterStore()
const userInfo = useInfoStore()
const { toastSuccess, toastLoading, toastFail, toastText, clearToast } = useShowToast()
const props = defineProps({
  info: {
    type: Object,
    required: true,
    default: () => ({})
  }
})

const routingInformation = routingInfos['contract']
const showDialog = ref(false);
const showSelect = ref(false);
const dialogSelection = ref({});

watch(() => props.info, (newValue) => {
  processingData(newValue.id)
})

const infoData = ref(props.info);
const timeout = ref(null);

function adoptOperation() {
  const { name = '', id } = infoData.value
  showConfirmDialog({
    title: `合同通过`,
    message: `确认审核通过吗？，通过后合同基本信息无法修改`,
  }).then(() => {
    requests.post(CONTRACT_APPROVED, { id, status: 0 }).then((res) => {
      toastSuccess('操作成功')
      processingData(id)
    }).catch((err) => {
      toastFail(err.msg ? err.msg : '操作失败')
    })
  })
}

function rejectOperation() {
  dialogSelection.value = ''
  showDialog.value = true
}

function confirmTransfer() {
  const { name = '', id } = infoData.value
  if (!dialogSelection.value) {
    return toastText('请输入驳回原因')
  }

  showConfirmDialog({
    title: `合同驳回`,
    message: `确认驳回吗？，驳回后合同基本信息无法修改`,
  }).then(() => {
    requests.post(CONTRACT_APPROVED, { id, status: 2, msg: dialogSelection.value }).then((res) => {
      toastSuccess('操作成功')
      showDialog.value = false
      processingData(id)
    })
  })
}

function dialogCloseBefo(val) {
  if (val == 'confirm' && showDialog.value) {
    return false
  }

  return true
}

function deleteRow() {
  const { name = '', searchFiled = {}, deteleFiled = '' } = routingInformation
  const row = props.info
  const foemVal = { [routingInformation.key == 'tasks' ? 'taskIds' : 'id']: row.id }
  showConfirmDialog({
    title: `删除${name}`,
    message: `确定删除【${row[searchFiled?.search]}】${name}吗？`,
  }).then(() => {
    requests.post(deteleFiled, { ...foemVal }).then((res) => {
      toastSuccess('删除成功')
      router.navigateBack({
        success: () => {
          router.emit('moduleListDetailParameter', {
            row: JSON.stringify(routingInformation)
          })
        }
      })
    }).catch((err) => {
      toastFail(err.msg ? err.msg : '删除失败')
    })
  })
}

function jumpEdit() {
  const formJson = fixedData.formJson[routingInformation.key] || []
  const formList = resetListData(formJson?.list)
  const filedObj = getListFieldKey(formList, infoData.value)
  const formVal = { ...filedObj, id: props.info.id }

  router.navigateTo({
    pathName: 'addEditor',
    success: () => {
      router.emit('addEditorParameter', {
        routerInfo: JSON.stringify(routingInformation),
        filedValue: JSON.stringify(formVal)
      })
    }
  })
}

function getDetails(id) {
  requests.post(OBTAIN_CONTRACT_DETAILS, { id }).then((res) => {
    infoData.value = res.data || {}
  }).finally(() => {
    setTimeout(() => {
      clearToast()
    }, 200)
  })
}
function processingData(id) {
  clearTimeout(timeout.value);
  toastLoading('加载中...', 0)
  timeout.value = setTimeout(() => {
    getDetails(id)
  }, 100);
}

useLifecycle({
  init: () => {
    processingData(props.info.id)
  },
  load: () => {
    processingData(props.info.id)
  },
  unload: () => {
    clearTimeout(timeout.value)
  }
});
</script>

<style lang='scss' scoped>
.bottomButton {
  margin: 0 14px;
  padding-bottom: 30px;

  :deep(.van-button) {
    margin-bottom: 20px;
  }
}

.info {
  margin: 8px 14px 30px 14px;
  padding: 14px;
}
</style>