<template>
  <div class="flex flex-col h-full paymentCollection">
    <div class="info flex-1 overflow-y-auto cellnormall">
      <template v-if="paymentPlanList.length">
        <div class="bg-white py-2 mb-4" v-for="item in paymentPlanList" :key="item.id">
          <van-cell-group inset>
            <van-cell title="回款时间" :value="item.createTime" />
            <van-cell title="操作人">
              <template #default>
                <TranslationComponent :openId="item.creatorName"></TranslationComponent>
              </template>
            </van-cell>
            <van-cell title="回款金额" :value="item.money" />
            <van-cell title="未回款金额" :value="item.unReceivedPayment" />
            <van-cell title="操作">
              <template #default>
                <div class="flex justify-end">
                  <div class="mr-3 themeTextColor" @click="editPaymentCollection(item)">编辑</div>
                  <div class="text-[red]" @click="deletePaymentCollection(item)">删除</div>
                </div>
              </template>
            </van-cell>
          </van-cell-group>
        </div>
      </template>
      <template v-else>
        <van-empty description="暂无数据" />
      </template>
    </div>
    <div class="bottomButton">
      <van-button type="primary" class="w-full block" @click="addPaymentCollection">添加回款</van-button>
    </div>

    <!-- 添加回款 -->
    <van-dialog v-model:show="showDialog" :title="`${dialogNumberVal.rowId ? '编辑' : '新增'}回款金额`" show-cancel-button
      @confirm="addEditReceipt" :before-close="dialogCloseBefo">
      <van-field v-model="dialogNumberVal.val" type="digit" label="回款金额" placeholder="请输入回款金额" />
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { showConfirmDialog } from 'vant';
import { useLifecycle } from '@hooks/useCommon.js';
import { OBTAIN_SALES_ORDER_RECEIPTS, NEW_SALES_ORDER_PAYMENT_COLLECTION, SALES_ORDER_COLLECTION_EDITING, DELETE_SALES_ORDER_PAYMENT_RECORDS } from '@hooks/useApi'
import requests from "@common/requests";
import useShowToast from '@hooks/useToast'

const { toastSuccess, toastFail, toastText } = useShowToast()
const props = defineProps({
  info: {
    type: Object,
    required: true,
    default: () => ({})
  }
})
const paymentPlanList = ref([])
const showDialog = ref(false);
const dialogNumberVal = ref({
  rowId: null,
  val: null
})

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

function deletePaymentCollection(row) {
  showConfirmDialog({
    message: `确定删除该回款记录吗？`,
  }).then(() => {
    requests.post(DELETE_SALES_ORDER_PAYMENT_RECORDS, { paymentId: row.id }).then(() => {
      toastSuccess('操作成功')
      processingData(props.info.id)
    }).catch((err) => {
      toastFail(err.msg ? err.msg : '删除失败')
    })
  })
}

function addEditReceipt() {
  const { rowId, val } = dialogNumberVal.value
  if (!val || val <= 0) {
    toastText('请填写回款金额并且不能为负数')
    return
  }
  const url = rowId ? SALES_ORDER_COLLECTION_EDITING : NEW_SALES_ORDER_PAYMENT_COLLECTION
  const arrList = paymentPlanList.value.filter(item => item.id !== rowId)
  const totalMoney = arrList.reduce((acc, item) => acc + item.money, 0);
  const orderAmount = props.info.price
  const formVal = {
    [rowId ? 'paymentId' : 'orderId']: rowId ? rowId : props.info.id,
    money: val,
  }
  if ((+totalMoney + val) > orderAmount) {
    toastText('回款金额不能大于订单金额')
    return
  }
  requests.post(url, formVal).then(() => {
    toastSuccess('操作成功')
    processingData(props.info.id)
    showDialog.value = false
  })
}

function addPaymentCollection() {
  dialogNumberVal.value = { rowId: null, val: null }
  showDialog.value = true
}

function editPaymentCollection(row) {
  const { id, money } = row
  dialogNumberVal.value = { rowId: id, val: money }
  showDialog.value = true
}

function processingData(id) {
  requests.post(OBTAIN_SALES_ORDER_RECEIPTS, { orderId: id }).then((res) => {
    paymentPlanList.value = res.data.reverse()
  })
}

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

  return true
}


useLifecycle({
  init: () => {
    processingData(props.info.id)
  }
});
</script>

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

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

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