<template>
  <Page name="good-source" flank>
    <template #header>
      <u-tabs :current="activeTab" :list="tabList" @click="onTabChange" :scrollable="false" :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 })">
            <view class="value">{{ searchForm.projectName || '所属项目' }}</view>
            <view @click.stop="clearProject" v-if="searchForm.projectCode" style="width: 10px; padding: 0 2px">
              <u-icon name="close-circle"></u-icon>
            </view>
            <view v-else class="sx-img">
              <image 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 })">
            <view class="value">{{ searchForm.startCityName || '始发地' }}</view>
            <view @click.stop="clearStartCity" v-if="searchForm.startCityCode" style="width: 10px; padding: 0 2px">
              <u-icon name="close-circle"></u-icon>
            </view>
            <view v-else class="sx-img">
              <!--              <image v-if="searchForm.startCityCode" class="sx-image" :src="formatImagePath('active-down')"></image>-->
              <image 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 })">
            <view class="value">{{ searchForm.endCityName || '目的地' }}</view>
            <view @click.stop="clearEndCity" v-if="searchForm.endCityCode" style="width: 10px; padding: 0 2px">
              <u-icon name="close-circle"></u-icon>
            </view>
            <view v-else class="sx-img">
              <image class="sx-image" :src="formatImagePath('down')"></image>
            </view>
          </view>
          <view @click="sortChange"><text style="color: #999; margin-right: 6rpx">发布时间</text><zui-icon name="switch-vertical"></zui-icon></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="modifySource" @cancel="cancelSource" @end="completeSource" @delete="deleteSource" @qrShow="qrCodeShow" :key="index" :item="item" @tap="toDetail(item.code)"></card>
        </template>
        <template #empty>
          <Empty tips="暂无数据" />
        </template>
      </List>
      <view v-if="$permission('/freightGoodsSource/add')" class="add-order" @tap="toAddPage('')">
        <zui-icon name="add" color="#fff" size="30px"></zui-icon>
      </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="false" :safe-area-inset-bottom="false">
      <l-painter ref="painter" :board="poster"></l-painter>
      <view style="margin: 30upx">
        <u-button type="primary" @click="saveQrImage">保存</u-button>
      </view>
    </u-popup>
    <u-popup :show="noAddAutoShow" @close="noAddAutoShow = false" mode="center" :safe-area-inset-bottom="false" round="5px">
      <view style="margin: 30upx; font-size: 32upx; font-weight: 500">温馨提示</view>
      <view style="margin: 0 30upx; font-size: 32upx; color: red">您的账户未开通货源发布权限！</view>
      <view style="margin: 30upx; font-size: 32upx; color: #999999">请联系平台运营人员，经培训后开通。</view>
      <view style="margin: 30upx">
        <u-button type="primary" @click="noAddAutoShow = false">我知道了</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: '请输入取消原因，必填' },
      },
      loading: false,
      popShow: false,
      currentCode: '',
      searchForm: {
        projectCode: '',
        projectName: '',
        startCityCode: '',
        startCityName: '',
        endCityCode: '',
        endCityName: '',
        status: '',
        sortFlag: false,
      },
      activeTab: 0,
      count: {},
      list: [],
      noAddAutoShow: false,
      currentFreight: {},
    };
  },
  onPullDownRefresh() {
    this.onSearch();
  },
  onLoad() {
    this.getAllowDriverSeeFreightAmount();
  },
  computed: {
    tabList() {
      let list = [
        { name: '找车中', value: 'MATCHING', key: 'matchingCount' },
        { name: '已结束', value: 'COMPLETED', key: 'completedCount' },
        { name: '已取消', value: 'CANCELLED', key: 'cancelledCount' },
      ];
      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: {
    getAllowDriverSeeFreightAmount() {
      uni.$u.api.freightOrder.currentFreight({}).then(en => {
        this.currentFreight = en?.result || {};
      });
    },
    onTabChange({ index }) {
      if (this.loading) {
        return;
      }
      this.activeTab = index;
      this.list = [];
      this.onSearch();
    },
    clearProject() {
      this.searchForm = Object.assign(this.searchForm, { projectCode: '', projectName: '' });
      this.onSearch();
    },
    clearStartCity() {
      this.searchForm = Object.assign(this.searchForm, { startCityCode: '', startCityName: '' });
      this.onSearch();
    },
    clearEndCity() {
      this.searchForm = Object.assign(this.searchForm, { endCityCode: '', endCityName: '' });
      this.onSearch();
    },
    sortChange() {
      this.searchForm = Object.assign(this.searchForm, { sortFlag: !this.searchForm.sortFlag });
      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: '',
          })}`,
        });
      }
    },
    // 修改货源
    modifySource(code) {
      this.currentCode = code;
      this.toAddPage('?code=' + code);
    },
    // 取消货源
    cancelSource(code) {
      this.currentCode = code;
      this.popType = 'cancel';
      this.popValue = '';
      this.popShow = true;
      uni.hideTabBar();
    },
    // 删除货源
    deleteSource(code) {
      uni.showModal({
        title: '提示',
        content: '确定删除此货源吗？',
        success: res => {
          if (res.confirm) {
            uni.$u.api.freightGoodsSourceV2.delete([code]).then(res => {
              if (res.success) {
                this.onSearch();
              }
            });
          }
        },
      });
    },
    // 结束货源
    completeSource(code) {
      uni.showModal({
        title: '提示',
        content: '确定结束此货源吗？',
        success: res => {
          if (res.confirm) {
            uni.$u.api.freightGoodsSourceV2.complete([code]).then(res => {
              if (res.success) {
                this.onSearch();
              }
            });
          }
        },
      });
    },
    closePop() {
      setTimeout(() => uni.showTabBar(), 300);
      this.popShow = false;
    },
    popSubmit() {
      if (!this.popValue) {
        uni.showToast({ title: '请输入原因', icon: 'none' });
        return;
      }
      uni.$u.api.freightGoodsSourceV2[this.popType]({
        code: this.currentCode,
        cancelReason: this.popValue,
      }).then(res => {
        if (res.success) {
          this.closePop();
          this.onSearch();
        }
      });
    },
    toAddPage(param) {
      if (!param) {
        if (!this.currentFreight.goodsSourcePermissionFlag) {
          this.noAddAutoShow = true;
          return;
        }
      }
      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.freightGoodsSourceV2.page({
        ...format,
        ...params,
      });
    },
    // 获取聚合数量
    getAggregateType(params) {
      uni.$u.api.freightGoodsSourceV2.count({ ...params, status: '' }).then(res => {
        this.count = res?.result || {};
      });
    },
    toDetail(code) {
      uni.navigateTo({ url: '/pages/goodSource/detail?code=' + code });
    },
    qrCodeShow(code) {
      if (this.loading) return;
      this.loading = true;
      uni.$u.api.freightGoodsSourceV2
        .getDetail({ code })
        .then(detail => {
          uni.$u.api.freightGoodsSourceV2
            .buildMaQrcode({ code })
            .then(qrcode => {
              if (qrcode.success && detail.success) {
                this.qrShow = true;
                this.poster = this.getPoster(detail.result, qrcode.result);
              }
            })
            .finally(() => {
              this.loading = false;
            });
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>
<style lang="scss">
.page-good-source {
  &__content {
    padding-bottom: 120px !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-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;
        justify-content: space-between;
        gap: 15rpx;

        .quick-tag-item {
          flex: 1;
          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;
          position: relative;
          &: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;
          }

          .value {
            white-space: nowrap;
            overflow: hidden;
            flex: 1;
          }

          .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>
