<template>
  <Page name="settlement" flank>
    <template #header>
      <u-tabs :current="activeTab" :list="tabList" @click="onTabChange" :activeStyle="{ color: '#1E7B6B' }"> </u-tabs>
      <view class="line"></view>
      <view class="quick-tag">
        <view class="quick-tag-group">
          <view class="quick-tag-item" :class="searchForm.feeType ? 'active' : ''" @click="selectQuickTag({ key: 'feeType', value: searchForm.feeType })">
            <text>{{ searchForm.feeTypeName || '款项类型' }}</text>
            <view class="sx-img">
              <image v-if="searchForm.feeType" class="sx-image" :src="formatImagePath('active-down')"></image>
              <image v-else class="sx-image" :src="formatImagePath('down')"></image>
            </view>
          </view>
          <view class="quick-tag-item" :class="searchForm.projectCode ? 'active' : ''" @click="selectQuickTag({ key: 'projectCode', value: searchForm.projectCode })">
            <text>{{ searchForm.projectName || '所属项目' }}</text>
            <view class="sx-img">
              <image v-if="searchForm.projectCode" class="sx-image" :src="formatImagePath('active-down')"></image>
              <image v-else class="sx-image" :src="formatImagePath('down')"></image>
            </view>
          </view>
          <view class="quick-tag-item" :class="searchForm.startCityCode ? 'active' : ''" @click="selectQuickTag({ key: 'startCityCode', value: searchForm.startCityCode })">
            <text>{{ searchForm.startCityName || '始发地' }}</text>
            <view class="sx-img">
              <image v-if="searchForm.startCityCode" class="sx-image" :src="formatImagePath('active-down')"></image>
              <image v-else class="sx-image" :src="formatImagePath('down')"></image>
            </view>
          </view>
          <view class="quick-tag-item" :class="searchForm.endCityCode ? 'active' : ''" @click="selectQuickTag({ key: 'endCityCode', value: searchForm.endCityCode })">
            <text>{{ searchForm.endCityName || '目的地' }}</text>
            <view class="sx-img">
              <image v-if="searchForm.startCityCode" class="sx-image" :src="formatImagePath('active-down')"></image>
              <image v-else class="sx-image" :src="formatImagePath('down')"></image>
            </view>
          </view>
        </view>
        <view class="quick-screen" @click="openFilter">
          <image class="search-image" :src="formatImagePath('search')"></image>
        </view>
      </view>
    </template>
    <template #content>
      <List ref="list" v-model="list" :api="orderAPI" @update:loading="e => (loading = e)" :verify="true">
        <template v-for="(item, index) in list">
          <card @payment="onePaymentPlanFun" @longClick="longClick" @chose="choseItemFun" :key="index" :item="item" :choseIds="selection" :choseMore="longClickFlag"></card>
        </template>
        <template #empty>
          <Empty tips="暂无数据" />
        </template>
      </List>
    </template>
    <template v-if="longClickFlag">
      <view class="foot-submit">
        <view class="foot-but">
          <view style="flex: 1">
            <text style="color: #999999">已选中：</text>
            <text class="color-red">{{ choseWaybillNum }}</text>
            个订单，
            <text class="color-red">{{ selection.length }}</text>
            笔款项
          </view>
          <view class="but-view">
            <u-button type="primary" size="small" @click="toPayUrl">去支付</u-button>
          </view>
        </view>
        <u-safe-bottom></u-safe-bottom>
      </view>
    </template>
    <u-popup :show="popShow" @close="popShow = false" closeable mode="center" :round="10">
      <view class="popup">
        <view class="title">支付信息确认</view>
        <view class="alert"><u-icon name="error-circle" size="12"> </u-icon>列表长按可以批量选择支付哦~ </view>
        <view>
          <view class="row"><view class="text">订单号：</view>{{ payPlanForm.detail[0].orderCode }}</view>
          <view class="row"><view class="text">车牌号：</view>{{ payPlanForm.detail[0].vehicleLicenseNum }}</view>
          <view class="row"><view class="text">收款人：</view>{{ payPlanForm.detail[0].recAccountName }}{{ payPlanForm.detail[0].recMobile }}</view>
          <view class="row"><view class="text">运费：</view>{{ payPlanForm.detail[0].feeAmount }}元</view>
          <view class="row"><view class="text">服务费：</view>{{ payPlanForm.detail[0].serviceAmount }}元</view>
          <view class="row"><view class="text">总额：</view>{{ payPlanForm.detail[0].payAmount }}元</view>
        </view>
        <view class="but">
          <u-button @tap="popShow = false">取消</u-button>
          <u-button type="primary" @tap="(popShow = false), (pwdShow = true)">继续支付</u-button>
        </view>
      </view>
    </u-popup>
    <u-popup :show="pwdShow" :closeable="false" mode="center" :round="10">
      <view class="popup">
        <view class="title">输入密码</view>
        <view class="row">
          <u-input v-model="pwdStr" type="password" input-align="center" placeholder="请输入支付密码"></u-input>
        </view>
        <view class="but">
          <u-button @tap="(pwdShow = false), (popShow = true)">取消</u-button>
          <u-button type="primary" @tap="onSubmit">确定支付</u-button>
        </view>
      </view>
    </u-popup>
    <u-toast ref="uToast"></u-toast>
  </Page>
</template>
<script>
import { urlParam } from '@/utils/param';
import card from './card.vue';
import UFormItem from '../../uni_modules/uview-ui/components/u-form-item/u-form-item.vue';
import page from '@/mixins/page';
export default {
  name: 'payPlan',
  components: { UFormItem, card },
  data() {
    return {
      longClickFlag: false,
      pwdStr: '',
      pwdShow: false,
      loading: false,
      popShow: false,
      payPlanForm: {
        oilRate: '',
        payCount: '',
        serviceRate: '',
        totalFeeAmount: '',
        totalPayAmount: '',
        totalServiceAmount: '',
        detail: [
          {
            customerOrderCode: '',
            driverMobile: '',
            driverName: '',
            feeAmount: '',
            feeType: '',
            orderCode: '',
            payAmount: '',
            payCode: '',
            recAccountName: '',
            recMobile: '',
            serviceAmount: '',
            vehicleLicenseNum: '',
          },
        ],
      },
      searchForm: {
        payStatus: '', // 支付状态
        feeType: '', // 费用类型
        feeTypeName: '', // 费用类型
        projectCode: '',
        projectName: '',
        startCityCode: '',
        startCityName: '',
        endCityCode: '',
        endCityName: '',
        orderCode: '', // 订单号
        driverName: '',
        driverMobile: '', //
        vehicleLicenseNum: '',
        unHandledExceptionFlag: '', // 存在异常
      },
      activeTab: 0,
      count: {},
      list: [],
      selection: [],
    };
  },
  onPullDownRefresh() {
    this.onSearch();
  },
  computed: {
    tabList() {
      let res = [
        { name: '未支付', value: 'NOT_PAY', key: 'notPayCount' },
        { name: '支付中', value: 'PAYING', key: 'payingCount' },
        { name: '支付失败', value: 'PAY_FAILED', key: 'payFailedCount' },
        { name: '支付成功', value: 'PAY_SUCCESS', key: 'paySuccessCount' },
      ];
      return Object.keys(this.count).length > 0
        ? res.map(item => {
            return { ...item, name: `${item.name}(${this.count[item.key] || 0})`, disabled: this.loading };
          })
        : res;
    },
    choseWaybillNum() {
      if (this.list.length === 0 || this.selection.length === 0) {
        return 0;
      } else {
        let orderList = this.list.filter(i => this.selection.includes(i.id)).map(i2 => i2.orderCode);
        return new Set(orderList).size;
      }
    },
  },
  methods: {
    onTabChange({ index }) {
      if (this.loading) {
        return;
      }
      this.activeTab = index;
      this.list = [];
      this.onSearch();
    },
    orderAPI(params) {
      let format = {
        ...this.searchForm,
        payStatus: this.tabList[this.activeTab].value,
      };
      this.getAggregateType(format);
      return uni.$u.api.paymentPlan.page({
        ...format,
        ...params,
      });
    },
    // 获取聚合数量
    getAggregateType() {
      uni.$u.api.paymentPlan.getCount({}).then(res => {
        this.count = res?.result || {};
      });
    },
    selectQuickTag({ key, value }) {
      this.searchForm = Object.assign(this.searchForm, { [key]: value });
      if (key == 'feeType') {
        uni.$once('select-dict', option => {
          this.searchForm.feeType = option.valueCode;
          this.searchForm.feeTypeName = option.valueName;
          this.onSearch();
        });
        uni.navigateTo({
          url: `/pages/global/search-dict${urlParam({
            title: '款项类型',
            dict: 'ONLINE_FREIGHT_ORDER_FEE_TYPE',
          })}`,
        });
      } else if (key == 'startCityCode') {
        uni.$once('select-city', option => {
          this.searchForm.startCityCode = option.code;
          this.searchForm.startCityName = option.shortName;
          this.onSearch();
        });
        uni.navigateTo({ url: '/pages/global/search-city' });
      } else if (key == 'endCityCode') {
        uni.$once('select-city', option => {
          this.searchForm.endCityCode = option.code;
          this.searchForm.endCityName = option.shortName;
          this.onSearch();
        });
        uni.navigateTo({ url: '/pages/global/search-city' });
      } else if (key == 'projectCode') {
        uni.$once('select-common', option => {
          this.searchForm.projectCode = option.code;
          this.searchForm.projectName = option.name;
          this.onSearch();
        });
        uni.navigateTo({
          url: `/pages/global/search-common${urlParam({
            mode: 'select',
            url: 'projectCode',
            title: '项目',
            label: 'name',
            value: '',
          })}`,
        });
      }
    },
    // 筛选
    openFilter() {
      uni.navigateTo({
        url: `/pages/payPlan/filter${urlParam(this.searchForm)}`,
        events: {
          refreshData: option => {
            this.searchForm = { ...this.searchForm, ...option };
            this.onSearch();
          },
        },
      });
    },
    choseItemFun(id) {
      if (this.longClickFlag) {
        if (this.selection.includes(id)) {
          this.selection = this.selection.filter(i => i !== id);
        } else {
          this.selection.push(id);
        }
        if (this.selection.length === 0) {
          this.longClickFlag = false;
        }
      }
    },
    longClick(id) {
      this.selection = [id];
      this.longClickFlag = true;
    },
    onePaymentPlanFun(id) {
      uni.showLoading({ title: '加载中' });
      this.selection = [id];
      uni.$u.api.paymentPlan
        .getApplyDetailByIds([id])
        .then(res => {
          uni.hideLoading();
          this.payPlanForm = res.result || {};
          this.popShow = true;
        })
        .catch(res => {
          uni.hideLoading();
          this.$refs.uToast.default(res);
        });
    },
    onSubmit() {
      if (this.loading) {
        return;
      }
      if (!this.pwdStr) {
        uni.showToast({ title: '支付密码不能为空' });
        return;
      }
      this.loading = true;
      uni.$u.api.paymentPlan
        .checkPayPassword({ payPassword: this.pwdStr })
        .then(res => {
          uni.$u.api.paymentPlan.pay(this.selection).then(res => {
            this.loading = false;
            this.pwdStr = '';
            uni.showToast({ title: '提交成功' });
            this.search();
            this.pwdShow = false;
            this.popShow = false;
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },
    toPayUrl() {
      uni.showLoading({ title: '加载中' });
      let selection = this.selection;
      uni.$u.api.paymentPlan
        .getApplyDetailByIds(this.selection)
        .then(resp => {
          uni.navigateTo({
            url: '/pages/payPlan/paySubmit',
            events: {
              refreshData: () => {
                this.selection = [];
                this.longClickFlag = false;
                this.onSearch();
              },
            },
            success(res) {
              res.eventChannel.emit('payPlanDate', { form: resp.result, selection });
            },
          });
        })
        .catch(res => {
          this.$refs.uToast.default(res);
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
  },
};
</script>
<style lang="scss">
.page-settlement {
  &__header {
    padding: 0 !important;

    .line {
      height: 1rpx;
      background: #f6f6f6;
      position: relative;
      top: -5rpx;
    }

    .quick-tag {
      display: flex;
      padding: 15upx 22upx;
      box-sizing: border-box;
      position: relative;

      .quick-cover {
        width: 25upx;
        height: 90upx;
        position: absolute;
        right: 122upx;
        top: 0;

        .cover-image {
          width: 100%;
          height: 100%;
        }
      }

      .quick-screen {
        width: 100upx;
        display: flex;
        align-items: center;
        justify-content: center;

        .search-image {
          width: 42upx;
          height: 42upx;
        }
      }

      .quick-tag-group {
        flex: 1;
        display: flex;
        align-items: center;
        background-color: #fff;
        padding-left: $padding-xs !important;
        padding-right: $padding-xs !important;
        overflow-y: auto;

        .quick-tag-item {
          flex-shrink: 0;
          min-width: 158upx;
          height: 58upx;
          background: #f6f6f6;
          border-radius: 8upx;
          font-size: 28upx;
          font-weight: 400;
          color: #2b2a27;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0 10upx;
          box-sizing: border-box;

          &:not(:last-child) {
            margin-right: 18upx;
          }

          &.active {
            background: #ffffff;
            border-radius: 8upx;
            border: 2upx solid #2673fb;
            font-size: 28upx;
            font-family:
              PingFangSC,
              PingFang SC;
            font-weight: 400;
            color: #2673fb;
          }

          .sx-img {
            height: 12upx;
            width: 14upx;
            position: relative;
            margin-left: 12upx;

            .sx-image {
              width: 100%;
              height: 100%;
              position: absolute;
              top: 0;
              left: 0;
            }
          }
        }

        .z-dropdown__text .text {
          word-break: keep-all;
        }
      }
    }
  }
  .add-order {
    right: 34upx;
    bottom: 34upx;
    height: 106upx;
    width: 106upx;
    position: fixed;
    .sx-image {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
    }
  }
  .popup {
    padding-left: $padding-md;
    padding-right: $padding-md;
    width: 70vw;
    .title {
      padding-top: $padding-xs;
      padding-bottom: $padding-xs;
      display: flex;
      align-content: center;
      justify-content: center;
      font-weight: 400;
      font-size: 32rpx;
      color: #2b2a27;
      line-height: 45px;
      text-align: left;
      font-style: normal;
    }
    .alert {
      color: orange;
      font-size: 24rpx;
      display: flex;
      padding-bottom: 20rpx;
    }
    .row {
      display: flex;
      padding: 10upx 0;
      .text {
        width: 130rpx;
      }
    }
    .but {
      margin-top: $padding-md;
      display: flex;
      gap: 20px;
    }
  }
  &__content {
    padding-bottom: 100px !important;
  }
  .foot-submit {
    position: fixed;
    width: 100vw;
    bottom: 0;
    background: white;
    .foot-but {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px;
      .but-view {
        max-width: 100px;
      }
    }
  }
}
</style>
