<template>
  <Page name="change-fee">
    <template #content>
      <u-alert type="warning" description="注意：只支持修改总运费，未支付或支付失败的款项"></u-alert>
      <view class="card" v-if="item.priceType === 'TON'">
        <view class="item">
          <view class="td">运输单价</view>
          <view class="amount">￥{{ item.weightUnitPrice }}</view>
        </view>
        <view class="item">
          <view class="td">货物吨位</view>
          <view class="amount">
            <u-input type="digit" @change="changeGoodsWeight" v-model="form.goodsWeight" suffix-icon="arrow-right" border="none" placeholder="请输入"> </u-input>
          </view>
        </view>
      </view>
      <view class="card">
        <view class="item">
          <view class="th">费用项</view>
          <view class="th">原运费</view>
          <view class="th">修改后运费</view>
        </view>
        <view class="item line-solid"> </view>
        <view class="item">
          <view class="td">应付司机运费</view>
          <view class="amount">￥{{ item.paidAmount }}</view>
          <view class="amount">
            <text>￥</text>
            <u-input type="digit" @change="computedService" v-model="form.paidAmount" suffix-icon="arrow-right" border="none" placeholder="请输入"> </u-input>
          </view>
        </view>
        <view class="item">
          <view class="td">安全服务费</view>
          <view class="amount">￥{{ item.securityServiceAmount ? item.securityServiceAmount : '0' }}</view>
          <view class="amount">
            <text>￥</text>
            <u-input v-model="form.securityServiceAmount" border="none" disabled placeholder="自动计算"></u-input>
          </view>
        </view>
        <u-form :model="form" labelWidth="100">
          <u-form-item label="更改备注">
            <u-input v-model="form.freightAdjustRemark" placeholder="请输入调整原因，选填" />
          </u-form-item>
        </u-form>
        <view class="item line-dashed"> </view>
        <view class="item" v-if="oilAmount.show">
          <view class="td">
            <text>油卡</text>
            <text v-if="oilAmount.payStatus === 'PAY_SUCCESS'" class="td--success">已支付</text>
            <text v-if="oilAmount.payStatus === 'PAY_FAILED'" class="td--warning">支付失败</text>
            <text v-if="oilAmount.payStatus === 'NOT_PAY'" class="td--info">未支付</text>
            <text v-if="oilAmount.payStatus === 'PAYING'" class="td--paying">支付中</text>
          </view>
          <view class="amount">￥{{ oilAmount.amount }}</view>
          <view class="amount">
            <text>￥</text>
            <u-input type="digit" @change="computedService" v-model="form.oilAmount" border="none" suffix-icon="arrow-right" placeholder="请输入" :disabled="oilAmount.disabled"></u-input>
          </view>
        </view>
        <view class="item" v-if="prePay.show">
          <view class="td">
            <text>预付款</text>
            <text v-if="prePay.payStatus === 'PAY_SUCCESS'" class="td--success">已支付</text>
            <text v-if="prePay.payStatus === 'PAY_FAILED'" class="td--warning">支付失败</text>
            <text v-if="prePay.payStatus === 'NOT_PAY'" class="td--info">未支付</text>
            <text v-if="prePay.payStatus === 'PAYING'" class="td--paying">支付中</text>
          </view>
          <view class="amount">￥{{ prePay.amount ? prePay.amount : '0' }}</view>
          <view class="amount">
            <text>￥</text>
            <u-input type="digit" @change="computedService" v-model="form.prepaidAmount" border="none" suffix-icon="arrow-right" :disabled="prePay.disabled" placeholder="请输入"></u-input>
          </view>
        </view>
        <view class="item" v-if="arrivalPay.show">
          <view class="td">
            <text>货到款</text>
            <text v-if="arrivalPay.payStatus === 'PAY_SUCCESS'" class="td--success">已支付</text>
            <text v-if="arrivalPay.payStatus === 'PAY_FAILED'" class="td--warning">支付失败</text>
            <text v-if="arrivalPay.payStatus === 'NOT_PAY'" class="td--info">未支付</text>
            <text v-if="arrivalPay.payStatus === 'PAYING'" class="td--paying">支付中</text>
          </view>
          <view class="amount">￥{{ arrivalPay.amount ? arrivalPay.amount : '0' }}</view>
          <view class="amount">
            <text>￥</text>
            <u-input
              border="none"
              type="digit"
              @change="computedService"
              v-model="form.deliveryAmount"
              :suffix-icon="autoComputedArrival ? '' : 'arrow-right'"
              :placeholder="autoComputedArrival ? '自动计算' : '请输入'"
              :disabled="autoComputedArrival || arrivalPay.disabled"
            >
              <template #suffix>
                <span v-if="autoComputedArrival && form.driverSecurityServiceAmount" class="color-red">-{{ form.driverSecurityServiceAmount }}</span>
              </template>
            </u-input>
          </view>
        </view>
        <view class="item">
          <view class="td">
            <text>尾款</text>
            <text v-if="final.payStatus === 'PAY_SUCCESS'" class="td--success">已支付</text>
            <text v-if="final.payStatus === 'PAY_FAILED'" class="td--warning">支付失败</text>
            <text v-if="final.payStatus === 'NOT_PAY'" class="td--info">未支付</text>
            <text v-if="final.payStatus === 'PAYING'" class="td--paying">支付中</text>
          </view>
          <view class="amount">￥{{ final.amount ? final.amount : '0' }}</view>
          <view class="amount">
            <text>￥</text>
            <u-input
              border="none"
              type="digit"
              @change="computedService"
              v-model="form.balancePaymentAmount"
              :suffix-icon="!autoComputedArrival ? '' : 'arrow-right'"
              :placeholder="!autoComputedArrival ? '自动计算' : '请输入'"
              :disabled="!autoComputedArrival || final.disabled"
            >
              <template #suffix>
                <span v-if="!autoComputedArrival && form.driverSecurityServiceAmount" class="color-red">-{{ form.driverSecurityServiceAmount }}</span>
              </template>
            </u-input>
          </view>
        </view>
      </view>
      <view v-if="showWarning" class="color-red" style="padding: 15px">
        <view style="font-weight: bold">温馨提示：</view>
        <view style="font-size: 12px; margin-top: 5px">
          当前订单已购买保险，保单号<span class="color-blue">[{{ item.policyNo }}]</span>，由于你增加了运费，出险后将无法足额理赔，请知悉！
        </view>
      </view>
    </template>
    <template #footer>
      <u-button type="primary" @tap="submit">确定更改</u-button>
    </template>
  </Page>
</template>
<script>
export default {
  name: 'change-fee',
  data() {
    return {
      currentFreight: {},
      item: {
        orderFeePayPlanList: [],
      },
      form: {
        freightAdjustRemark: '',
        paidAmount: '',
        oilAmount: '',
        deliveryAmount: '',
        prepaidAmount: '',
        balancePaymentAmount: '',
        goodsWeight: '',
      },
    };
  },
  computed: {
    oilAmount() {
      let resList = this.item.orderFeePayPlanList ? this.item.orderFeePayPlanList.filter(i => i.type === 'OIL_COST') : [];
      let res = resList.length === 1 ? resList[0] : {};
      return {
        ...res,
        show: this.item.oilPayFlag,
        disabled: !['NOT_PAY', 'PAY_FAILED', '', null, undefined].includes(res.payStatus),
      };
    },
    prePay() {
      let resList = this.item.orderFeePayPlanList.filter(i => i.type === 'OUT_INVITE_PRE');
      let res = resList.length === 1 ? resList[0] : {};
      return {
        ...res,
        show: this.item.prePayFlag,
        disabled: !['NOT_PAY', 'PAY_FAILED', '', null, undefined].includes(res.payStatus),
      };
    },
    arrivalPay() {
      let resList = this.item.orderFeePayPlanList.filter(i => i.type === 'OUT_INVITE_ARRIVAL');
      let res = resList.length === 1 ? resList[0] : {};
      return {
        ...res,
        show: this.item.arrivalPayFlag,
        disabled: !['NOT_PAY', 'PAY_FAILED', '', null, undefined].includes(res.payStatus),
      };
    },
    final() {
      let resList = this.item.orderFeePayPlanList.filter(i => i.type === 'OUT_INVITE_FINAL');
      let res = resList.length === 1 ? resList[0] : {};
      return {
        ...res,
        show: true,
        disabled: !['NOT_PAY', 'PAY_FAILED', '', null, undefined].includes(res.payStatus),
      };
    },
    autoComputedArrival() {
      // 自动计算货到
      return 'OUT_INVITE_ARRIVAL' === this.currentFreight?.autoComputeFeeType;
    },
    haveInsurance() {
      return this.item && this.item.insuranceStatus === 'SUCCESS';
    },
    showWarning() {
      return this.haveInsurance && this.form.paidAmount > this.item.paidAmount;
    },
  },
  onLoad(options) {
    if (options.code) {
      this.initData(options.code);
    }
  },
  methods: {
    initData(code) {
      uni.$u.api.freightOrder.currentFreight({}).then(en => {
        this.currentFreight = en?.result || {};
      });
      uni.$u.api.freightOrder.getDetail({ code }).then(res => {
        this.item = res.result || {};
        this.form.paidAmount = this.item.paidAmount;
        this.form.goodsWeight = this.item.goodsWeight;
        this.updateAfterAmount(this.item.orderFeePayPlanList);
      });
    },
    changeGoodsWeight() {
      let paidAmount = Number(this.item.weightUnitPrice) * Number(this.form.goodsWeight);
      this.form.paidAmount = paidAmount.toFixed(2);
      this.computedService();
    },
    updateAfterAmount(list) {
      let oilPay = list.filter(i => i.type === 'OIL_COST')[0];
      let prePay = list.filter(i => i.type === 'OUT_INVITE_PRE')[0];
      let arrivalPay = list.filter(i => i.type === 'OUT_INVITE_ARRIVAL')[0];
      let finalPay = list.filter(i => i.type === 'OUT_INVITE_FINAL')[0];
      this.form = {
        ...this.form,
        oilAmount: oilPay.amount,
        prepaidAmount: prePay.amount,
        deliveryAmount: arrivalPay.amount,
        balancePaymentAmount: finalPay.amount || 0,
        securityServiceAmount: this.item.securityServiceAmount || '',
      };
    },
    computedService() {
      uni.$u.debounce(this.getServiceAmountInfo, 500);
    },
    getServiceAmountInfo() {
      const { paidAmount = '0', oilAmount = '0', deliveryAmount = '0', prepaidAmount = '0', balancePaymentAmount = '0' } = this.form;
      const { goodsName = '', goodsValue = '' } = this.item;
      let params = {
        paidAmount,
        deliveryAmount,
        prepaidAmount,
        oilAmount,
        balancePaymentAmount,
        goodsName,
        goodsValue,
        enterpriseId: this.item.enterpriseId,
        code: this.item.code,
      };
      uni.$u.api.freightOrder.getServiceAmount(params).then(res => {
        if (res.success) {
          // this.form.paidAmount = res.result.paidAmount || paidAmount;
          // this.form.prepaidAmount = res.result.prepaidAmount || prepaidAmount;
          // this.form.oilAmount = res.result.oilAmount || oilAmount;
          if (this.autoComputedArrival) {
            this.form.deliveryAmount = res.result.deliveryAmount || '0';
          } else {
            this.form.balancePaymentAmount = res.result.balancePaymentAmount || '0';
          }
          this.form.driverSecurityServiceAmount = res.result.driverSecurityServiceAmount || '0';
          this.form.securityServiceAmount = res.result.securityServiceAmount || '0';
          this.form.serviceAmount = res.result.serviceAmount || '0';
        }
      });
    },
    submit() {
      let params = [
        { ...this.oilAmount, afterAmount: this.form.oilAmount === '' ? '0' : this.form.oilAmount },
        { ...this.prePay, afterAmount: this.form.prepaidAmount === '' ? '0' : this.form.prepaidAmount },
        { ...this.arrivalPay, afterAmount: this.form.deliveryAmount === '' ? '0' : this.form.deliveryAmount },
        { ...this.final, afterAmount: this.form.balancePaymentAmount === '' ? '0' : this.form.balancePaymentAmount },
      ];
      uni.$u.api.freightOrder
        .adjustAmount({ feeList: params, code: this.item.code, paidAmount: this.form.paidAmount, freightAdjustRemark: this.form.freightAdjustRemark, goodsWeight: this.form.goodsWeight })
        .then(res => {
          if (res.success) {
            uni.showToast({ title: '操作成功', icon: 'none' });
            this.getOpenerEventChannel().emit('refreshData');
            setTimeout(() => uni.navigateBack(), 500);
          }
        });
    },
  },
};
</script>

<style lang="scss">
.page-change-fee {
  &__content {
    padding-top: 0 !important;
  }
  &__footer {
    background: $color-white;
  }
  .card {
    background-color: $color-white;
    color: $color-text;
    padding: $padding-sm;
    margin: $padding-sm;
    border-radius: $radius-md;
    box-shadow: $shadow-normal;
    font-size: $font-md;
    .line-solid {
      border-bottom: 1px solid #dddddd;
    }
    .line-dashed {
      border-bottom: 1px dashed #dddddd;
    }
    .item + .item {
      margin-top: $padding-md;
    }
    .item {
      display: flex;
      view {
        flex: 1;
      }
      .th {
        font-weight: 500;
        font-size: 30upx;
        color: #2b2a27;
        line-height: 30upx;
        text-align: left;
        font-style: normal;
      }
      .td {
        font-weight: 400;
        font-size: 28upx;
        color: #999999;
        line-height: 28upx;
        text-align: left;
        font-style: normal;
        &--warning {
          color: #f52723;
          font-size: 20rpx;
          margin-left: 20upx;
          padding-left: 10upx;
          padding-right: 10upx;
          border-radius: 8upx;
          border: 2rpx solid #f52723;
        }
        &--info {
          color: #999999;
          font-size: 20upx;
          margin-left: 20upx;
          padding-left: 10upx;
          padding-right: 10upx;
          border-radius: 8upx;
          border: 2rpx solid #999999;
        }
        &--paying {
          color: #ff9339;
          font-size: 20upx;
          margin-left: 20upx;
          padding-left: 10upx;
          padding-right: 10upx;
          border-radius: 8upx;
          border: 2rpx solid #ff9339;
        }
        &--success {
          color: #00b87a;
          font-size: 20upx;
          margin-left: 20upx;
          padding-left: 10upx;
          padding-right: 10upx;
          border-radius: 8upx;
          border: 2rpx solid #00b87a;
        }
      }
      .amount {
        font-weight: 400;
        font-size: 28upx;
        color: #2b2a27;
        line-height: 28upx;
        text-align: left;
        font-style: normal;
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>
