<template>
  <Page name="good-source" flank>
    <template #header>
      <u-tabs :current="activeTab" :list="tabList" @click="onTabChange" :scrollable="true" :disabled="loading" :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.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.endCityCode" 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 @modify="more" @cancel="cancelOrder" @end="deleteOrder" @delete="deleteOrder" @qrShow="qrCodeShow" :key="index" :item="item" @tap="toDetail(item.code)"></card>
        </template>
        <template #empty>
          <Empty tips="暂无数据" />
        </template>
      </List>
      <view class="add-order" @tap="toAddPage('')">
        <zui-icon name="add" color="#fff" size="30px"></zui-icon>
        <!--        <image class="sx-image" src="/static/addOrder.png"></image>-->
      </view>
    </template>
    <u-popup :show="popShow" @close="closePop" closeable>
      <view class="popup">
        <view class="title">{{ popConfig[popType].title }}</view>
        <u--textarea v-model="popValue" :placeholder="popConfig[popType].placeholder" placeholderStyle="background:#f6f6f6" :cursorSpacing="60"></u--textarea>
        <view class="but">
          <u-button type="primary" @tap="popSubmit">确定</u-button>
        </view>
      </view>
    </u-popup>
    <u-popup :show="qrShow" @close="qrShow = false" mode="center" closeable>
      <l-painter ref="painter" :board="poster"></l-painter>
      <view style="margin-top: 30upx">
        <u-button type="primary" @click="saveQrImage">保存</u-button>
      </view>
    </u-popup>
  </Page>
</template>
<script>
import { urlParam } from '@/utils/param';
import card from './card.vue';
import page from '../../mixins/page';
import qrPainter from './qr-painter';
export default {
  name: 'goodSource',
  mixins: [page, qrPainter],
  components: { card },
  data() {
    return {
      poster: {},
      qrShow: false,
      popType: 'cancel',
      popValue: '',
      popConfig: {
        cancel: { fun: '', title: '取消原因', placeholder: '请输入取消原因，必填' },
        delete: { fun: '', title: '删除原因', placeholder: '请输入删除原因，必填' },
      },
      loading: false,
      popShow: false,
      currentCode: '',
      searchForm: {
        projectCode: '',
        projectName: '',
        code: '', //
        driverName: '',
        driverMobile: '', // 客户
        vehicleLicenseNum: '',
        unHandledExceptionFlag: '', // 存在异常
        startCityCode: '',
        endCityCode: '',
        status: '',
        receiptFlag: '', // 是否已签单
        payStatus: '', // 支付状态
        payStatusName: '', //
      },
      activeTab: 0,
      count: {},
      list: [],
    };
  },
  onPullDownRefresh() {
    this.onSearch();
  },
  computed: {
    tabList() {
      let list = [
        { name: '找车中', value: 'TRANSFER', key: 'transfer' },
        { name: '已结束', value: 'COMPLETED', key: 'completed' },
        { name: '已取消', value: 'CANCEL', key: 'cancel' },
      ];
      return Object.keys(this.count).length > 0
        ? list.map(item => {
            return { ...item, name: `${item.name}(${this.count[item.key] || 0})`, disabled: this.loading };
          })
        : list;
    },
  },
  methods: {
    onTabChange({ index }) {
      if (this.loading) {
        return;
      }
      this.activeTab = index;
      this.list = [];
      this.onSearch();
    },
    selectQuickTag({ key, value }) {
      this.searchForm = Object.assign(this.searchForm, { [key]: value });
      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: '',
          })}`,
        });
      }
    },
    // 再来一单
    more(code) {
      this.currentCode = code;
      this.toAddPage('?code=' + code);
    },
    // 取消订单
    cancelOrder(code) {
      this.currentCode = code;
      this.popType = 'cancel';
      this.popValue = '';
      this.popShow = true;
      uni.hideTabBar();
    },
    closePop() {
      setTimeout(() => uni.showTabBar(), 300);
      this.popShow = false;
    },
    popSubmit() {
      if (!this.popValue) {
        uni.showToast({ title: '请输入原因', icon: 'none' });
        return;
      }
      uni.$u.api.freightOrder[this.popType]({
        codeList: [this.currentCode],
        reason: this.popValue,
      }).then(res => {
        if (res.success) {
          this.closePop();
          this.onSearch();
        }
      });
    },
    // 删除订单
    deleteOrder(code) {
      this.currentCode = code;
      this.popType = 'delete';
      this.popValue = '';
      this.popShow = true;
      uni.hideTabBar();
    },
    toUploadReceipt(code) {
      uni.navigateTo({
        url: '/pages/order/upload-receipt?code=' + code,
        events: {
          refreshData: () => {
            this.onSearch();
          },
        },
      });
    },
    toAddPage(param) {
      uni.navigateTo({
        url: '/pages/goodSource/add' + param,
        events: {
          refreshData: option => {
            this.onSearch();
          },
        },
      });
    },
    // 筛选
    openFilter() {
      uni.navigateTo({
        url: `/pages/order/filter${urlParam(this.searchForm)}`,
        events: {
          refreshData: option => {
            this.searchForm = { ...this.searchForm, ...option };
            this.onSearch();
          },
        },
      });
    },
    orderAPI(params) {
      let format = {
        ...this.searchForm,
        status: this.tabList[this.activeTab].value,
      };
      this.getAggregateType(format);
      return uni.$u.api.freightOrder.page({
        ...format,
        ...params,
      });
    },
    // 获取聚合数量
    getAggregateType(params) {
      uni.$u.api.freightOrder.count({ ...params, status: '' }).then(res => {
        this.count = res?.result || {};
      });
    },
    toDetail(code) {
      uni.navigateTo({ url: '/pages/order/detail?code=' + code });
    },
    toStartCar(code) {
      uni.navigateTo({
        url: '/pages/order/start-car?code=' + code,
        events: {
          refreshData: () => {
            this.onSearch();
          },
        },
      });
    },
    toArrivalCar(code) {
      uni.navigateTo({
        url: '/pages/order/arrival-car?code=' + code,
        events: {
          refreshData: () => {
            this.onSearch();
          },
        },
      });
    },
    qrCodeShow(code, data) {
      if (this.loading) return;
      this.loading = true;
      this.qrShow = true;
      uni.$u.api.freightOrder
        .getSensitiveByOrderCode({ orderCode: code })
        .then(res => {
          if (res.success) {
            uni.$u.api.freightOrder
              .buildMaQrcode({ orderCode: code })
              .then(res2 => {
                this.loading = false;
                if (res2.success) {
                  this.poster = this.getPoster(res.result, data, res2.result);
                  console.info(this.poster);
                }
              })
              .catch(e => {
                this.loading = false;
              });
          }
        })
        .catch(e => {
          this.loading = false;
        });
    },
  },
};
</script>
<style lang="scss">
.page-good-source {
  &__content {
    padding-bottom: 100px !important;
  }
  &__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 {
    left: 34upx;
    bottom: 34upx;
    height: 90upx;
    width: 90upx;
    background: $color-primary;
    border-radius: 100upx;
    position: fixed;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .popup {
    padding-left: $padding-md;
    padding-right: $padding-md;
    border-top-left-radius: $radius-md;
    border-top-right-radius: $radius-md;
    .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;
    }
    .but {
      margin-top: $padding-md;
    }
  }
}
</style>
