<!--
 Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

 https://www.mall4j.com/

 未经允许，不可做商业用途！

 版权所有，侵权必究！
-->
<template>
  <el-dialog
    v-model="visible"
    :title="$t('order.order.modifyOrderAmount')"
    :close-on-click-modal="false"
    width="80%"
    class="components-order-amount-update"
  >
    <div class="mod-order-orderInfo">
      <el-alert
        :title="$t('order.order.modificatioAmount')"
        type="warning"
        show-icon
      />
      <div class="main">
        <div class="content">
          <div class="prod-tit">
            <el-row style="width:100%">
              <el-col :span="21">
                <el-col
                  :span="5"
                  header-align="center"
                >
                  <span class="item">{{ $t("order.order.product") }}</span>
                </el-col>
                <el-col
                  :span="2"
                  header-align="center"
                >
                  <span class="item">{{ $t("order.order.unitPrice") }}</span>
                </el-col>
                <el-col
                  :span="2"
                  header-align="center"
                >
                  <span class="item">{{ $t("order.order.quantity") }}</span>
                </el-col>
                <el-col
                  :span="2"
                  header-align="center"
                >
                  <span class="item">{{ $t("order.order.totalPrice") }}</span>
                </el-col>
                <el-col
                  :span="2"
                  header-align="center"
                >
                  <span class="item">{{ $t("order.order.totalDiscount") }}</span>
                </el-col>
                <el-col
                  :span="3"
                  header-align="center"
                >
                  <span class="item">{{ $t("order.order.userPayunt") }}</span>
                </el-col>
                <el-col
                  :span="2"
                  header-align="center"
                >
                  <span class="item">{{ $t("order.order.platforlowance") }}</span>
                </el-col>
                <el-col
                  :span="2"
                  header-align="center"
                >
                  <span class="item">{{ $t("order.order.estimancome") }}</span>
                </el-col>
                <el-col
                  :span="4"
                  header-align="center"
                >
                  <span class="item">{{ $t("order.order.userPayunt") }}</span>
                </el-col>
              </el-col>
              <el-col :span="3">
                <el-col
                  header-align="center"
                >
                  <span class="item product">{{ $t("order.order.shippingAmunt") }}</span>
                </el-col>
              </el-col>
            </el-row>
          </div>
          <div class="prod">
            <div class="prod-cont prod-bottom">
              <el-row style="width:100%">
                <el-col :span="21">
                  <el-col
                    v-for="(orderItem,index) in dataList"
                    :key="index"
                    class="prod"
                  >
                    <el-col class="prod-cont">
                      <el-row style="width:100%">
                        <el-col
                          :span="5"
                          style="height: 100%;"
                        >
                          <div class="item">
                            <span>{{ orderItem.spuName }}</span>
                            <span v-if="orderItem.skuName"> {{ orderItem.skuName }}</span>
                          </div>
                        </el-col>
                        <el-col
                          :span="2"
                          style="height: 100%;"
                        >
                          <div class="item">
                            <span>{{ handlerPrice(orderItem.price) }}</span>
                          </div>
                        </el-col>
                        <el-col
                          :span="2"
                          style="height: 100%;"
                        >
                          <div class="item">
                            <span>{{ orderItem.count }}</span>
                          </div>
                        </el-col>
                        <el-col
                          :span="2"
                          style="height: 100%;"
                        >
                          <div class="item">
                            <span>{{ handlerPrice(orderItem.spuTotalAmount) }}</span>
                          </div>
                        </el-col>
                        <el-col
                          :span="2"
                          style="height: 100%;"
                        >
                          <div class="item">
                            <span>{{ handlerPrice(orderItem.shareReduceAmount) }}</span>
                          </div>
                        </el-col>
                        <el-col
                          :span="3"
                          style="height: 100%;"
                        >
                          <div class="item">
                            <span>{{ handlerPrice(orderItem.actualTotalAmount) }}</span>
                          </div>
                        </el-col>
                        <el-col
                          :span="2"
                          style="height: 100%;"
                        >
                          <div class="item">
                            <span>{{ handlerPrice(orderItem.platformShareReduceAmount) }}</span>
                          </div>
                        </el-col>
                        <el-col
                          :span="2"
                          style="height: 100%;"
                        >
                          <div class="item">
                            <span>{{ handlerPrice(orderItem.amount) }}</span>
                          </div>
                        </el-col>
                        <el-col
                          :span="4"
                          style="height: 100%;"
                        >
                          <div class="item">
                            <el-input-number
                              v-model="orderItem.userPayAmount"
                              :precision="2"
                              :min="0.01"
                              :max="99999999"
                              :disabled="parseInt(orderItem.shopChangeFreeAmount) !== 0"
                              @change="setUserPayAmount(index)"
                            />
                          </div>
                        </el-col>
                      </el-row>
                    </el-col>
                  </el-col>
                </el-col>
                <el-col
                  :span="3"
                  style="height: 100%;  margin-left:10px"
                >
                  <div class="item">
                    <el-input-number
                      v-model="freightAmount"
                      :precision="2"
                      :min="0"
                      :max="99999999"
                    />
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </div>
    </div>
    <span v-if="lossAmount !== 0">{{ $t("order.order.decreaslowance") }} :{{ handlerLossAmount(lossAmount) }}{{ $t("constant.dollar") }}</span>
    <template #footer>
      <span>
        <el-button
          type="primary"
          @click="visible = false"
        >{{ $t("table.cancel") }}</el-button>
        <el-button
          type="primary"
          @click="submitProds()"
        >{{ $t("table.confirm") }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import Big from 'big.js'
import * as api from '@/api/order/order'
import { ElLoading as Loading, ElMessage } from 'element-plus'

const emit = defineEmits([
  'refreshOrderAmountUpdate'
])

const dataList = reactive([])

// 获取初始化
const dataListLoading = ref(false)
const freightAmount = ref(0)
const lossAmount = ref(0)
const orderId = ref(0)
const submit = ref(false)
const visible = ref(false)
const init = (order) => {
  orderId.value = order.orderId
  submit.value = false
  dataListLoading.value = true
  api.orderInfo(orderId.value).then((data) => {
    order = data
    freightAmount.value = new Big(data.freightAmount - data.platformFreeFreightAmount).div(100)
    lossAmount.value = 0
    // 订单项
    dataList.length = 0
    dataList.push(...data.orderItems)
    dataList.forEach(orderItem => {
      orderItem.userPayAmount = new Big(orderItem.actualTotal).div(100)
      orderItem.lossAmount = 0.00
      const shareReduceAmount = orderItem.shareReduce || 0
      const actualTotalAmount = orderItem.actualTotal || 0
      const platformShareReduceAmount = orderItem.platformShareReduce || 0
      orderItem.shareReduceAmount = shareReduceAmount || 0
      orderItem.actualTotalAmount = actualTotalAmount || 0
      orderItem.platformShareReduceAmount = platformShareReduceAmount || 0
      const actual = new Big(orderItem.actualTotalAmount)
      orderItem.amount = actual.plus(orderItem.platformShareReduce).round(2)
    })
    visible.value = true
    dataListLoading.value = false
  })
}

// 订单金额变化时，计算优惠金额
const setUserPayAmount = (index) => {
  const item = dataList[index]
  if (!item.userPayAmount) {
    item.userPayAmount = 0
    dataList[index] = item
  }
  const userPayAmount = new Big(item.userPayAmount).times(100)
  if (userPayAmount >= item.actualTotal) {
    item.lossAmount = 0
    item.shareReduceAmount = item.shareReduce || 0
    item.actualTotalAmount = userPayAmount
    item.platformShareReduceAmount = item.platformShareReduce || 0
    item.amount = new Big(item.actualTotalAmount).plus(item.platformShareReduce).round(2)
  } else {
    const changeAmount = new Big(item.actualTotal).minus(userPayAmount)
    const actualTotal = new Big(item.actualTotal)
    const platformShareReduceAmount = new Big(item.platformShareReduce)
    // 金额减少比例 = 减少金额 % 总金额
    const proportion = changeAmount.div(item.spuTotalAmount).round(6)
    // 平台优惠金额减少金额 = 减少比例 * 原平台优惠金额
    const platformAmount = proportion.times(platformShareReduceAmount).round(0)
    // 平台优惠金额 = 原平台优惠金额 - 平台优惠金额减少金额
    item.platformShareReduceAmount = platformShareReduceAmount.minus(platformAmount)
    // 总优惠金额 = 变化金额 + 原总优惠金额
    item.shareReduceAmount = changeAmount.plus(item.shareReduce)
    // 实际金额 = 原实际金额 - 变化金额
    item.actualTotalAmount = actualTotal.minus(changeAmount)
    // 店铺预计收入金额 = 实际金额 + 平台优惠金额
    item.amount = item.actualTotalAmount.plus(item.platformShareReduceAmount).round(2)
    // 店铺损失金额 = 平台优惠金额减少金额
    item.lossAmount = platformAmount
  }
  // 计算店铺亏损总金额
  let totalLossAmount = new Big(0)
  dataList.forEach(item => {
    totalLossAmount = totalLossAmount.plus(item.lossAmount)
  })
  lossAmount.value = totalLossAmount
  dataList[index] = item
}
/**
 * 校验金额
 */
const check = () => {
  dataList.forEach(orderItem => {
    if (orderItem.actualTotal <= 0) {
      errorMsg($t('order.order.theOraterThan0'))
      return true
    }
  })
  if (!freightAmount.value && freightAmount.value !== 0) {
    errorMsg('运费金额不能为空')
    return true
  }
  return false
}
/**
 * 确定事件
 */
const submitProds = () => {
  if (check()) {
    return
  }
  dataList.forEach(item => {
    if (!item.userPayAmount) {
      item.userPayAmount = 0
    }
    item.changeAmount = new Big(item.userPayAmount).times(100)
  })
  if (submit.value) {
    return
  }
  submit.value = true
  api.changeAmount({
    orderId: orderId.value,
    orderItems: dataList,
    freightAmount: new Big(freightAmount.value).times(100)
  }).then(() => {
    const loadingInstance = Loading.service({
      target: document.getElementsByClassName('mod-order-orderInfo')[0]
    })
    setTimeout(() => {
      emit('refreshOrderAmountUpdate')
      visible.value = false
      loadingInstance.close()
    }, 1200)
  }).catch(() => {
    submit.value = false
  })
}
const errorMsg = (message) => {
  ElMessage({
    message,
    type: 'error',
    duration: 1500
  })
}

// 精度运算-过滤
const handlerPrice = (val) => {
  if (val == null) {
    return ''
  }
  return new Big(val).div(100).toFixed(2)
}

const handlerLossAmount = (val) => {
  if (val == null) {
    return ''
  }
  return new Big(val).div(100)
}

defineExpose({
  init
})
</script>

<style scoped>
.components-order-amount-update {
  .mod-order-orderInfo {
    height: 100%;
    width: 100%;
    font: 14px Arial, "PingFang SC", "Hiragino Sans GB", STHeiti,
    "Microsoft YaHei", "WenQuanYi Micro Hei", sans-serif;
    color: #495060;
  }
  .item {
    text-align: center;
    line-height: 36px;
  }
  .mod-order-order .prod-cont {
    border-bottom: 1px solid #dddee1;
  }

  /* 运费输入框 居中 */
  .prod-cont :deep(.el-row) {
    display: flex;
    align-items: center;
  }

  .mod-order-order .prod-cont {
    border:0
  }

  .item :deep(.el-input-number){
    margin: 5px 0;
  }

  .item :deep(.el-input-number--medium) {
    width: 100%
  }
}
</style>
