<template>
  <Page name="good-source-add" flank>
    <template #content>
      <u-form :model="form" ref="uForm" labelWidth="100">
        <view class="card">
          <u-form-item label="所属项目" required @click="choseProjectCode">
            <u-input v-model="form.projectName" border="none" suffix-icon="arrow-right" placeholder="请选择项目" disabledColor="#ffffff" disabled />
          </u-form-item>
          <u-form-item label="开始时间" @click="showLoadTime1 = true" required>
            <u-datetime-picker :show="showLoadTime1" :value="loadTimeDef1" @cancel="showLoadTime1 = false" @close="showLoadTime2 = false" @confirm="loadTimeFormat1"></u-datetime-picker>
            <u-input v-model="form.loadTime" border="none" suffix-icon="arrow-right" placeholder="请选择时间" disabledColor="#ffffff" disabled />
          </u-form-item>
          <u-form-item label="结束时间" @click="showLoadTime2 = true" required>
            <u-datetime-picker :show="showLoadTime2" :value="loadTimeDef2" @cancel="showLoadTime2 = false" @close="showLoadTime2 = false" @confirm="loadTimeFormat2"></u-datetime-picker>
            <u-input v-model="form.loadTime" border="none" suffix-icon="arrow-right" placeholder="请选择时间" disabledColor="#ffffff" disabled />
          </u-form-item>
        </view>
        <view class="card">
          <u-form-item label="装货地址" required @click="() => selectAddress(0)">
            <u-input :value="form.waypoints[0].address" border="none" suffix-icon="arrow-right" placeholder="请选择" disabledColor="#ffffff" disabled />
          </u-form-item>
          <u-form-item label="卸货地址" required @click="() => selectAddress(1)">
            <u-input v-model="form.waypoints[1].address" border="none" suffix-icon="arrow-right" placeholder="请选择" disabledColor="#ffffff" disabled />
          </u-form-item>
        </view>
        <view class="card">
          <u-form-item label="货物类型" required @click="choseGoodsType">
            <u-input :value="form.goodsTypeName" border="none" suffix-icon="arrow-right" placeholder="请选择" disabledColor="#ffffff" disabled />
          </u-form-item>
          <u-form-item label="需求车型" required @click="specificationVisible = true">
            <u-input :value="formatSpecification" border="none" suffix-icon="arrow-right" placeholder="请选择" disabledColor="#ffffff" disabled />
          </u-form-item>
          <u-form-item label="需求箱型" required @click="vanTypeVisible = true">
            <u-input :value="formatVanType" border="none" suffix-icon="arrow-right" placeholder="请选择" disabledColor="#ffffff" disabled />
          </u-form-item>
        </view>
        <view class="card">
          <u-form-item label="计价方式" @click="chosePriceType">
            <u-input v-model="form.priceType" border="none" suffix-icon="arrow-right" placeholder="请选择" disabledColor="#ffffff" disabled />
          </u-form-item>
          <u-form-item label="货物总量" required>
            <u-input v-model="form.goodsValue" border="none" type="digit" placeholder="请输入">
              <template slot="suffix">吨</template>
            </u-input>
          </u-form-item>
          <u-form-item label="运输单价">
            <u-input v-model="form.goodsValue" border="none" type="digit" placeholder="请输入">
              <template slot="suffix">元/吨</template>
            </u-input>
          </u-form-item>
          <u-form-item label="需求车数" required>
            <u-input v-model="form.goodsValue" border="none" type="digit" placeholder="请输入">
              <template slot="suffix">吨</template>
            </u-input>
          </u-form-item>
          <u-form-item label="总运费">
            <u-input v-model="form.goodsValue" border="none" type="digit" placeholder="请输入">
              <template slot="suffix">元/吨</template>
            </u-input>
          </u-form-item>
        </view>
        <view class="card" @tap="more = !more">
          <view class="more-action">
            {{ !more ? '展开更多信息' : '收起更多信息' }}
            <view class="sx-img">
              <image v-if="more" class="sx-image up" :src="formatImagePath('down')"></image>
              <image v-else class="sx-image" :src="formatImagePath('down')"></image>
            </view>
          </view>
        </view>
        <template v-if="more">
          <view class="card">
            <u-form-item label="订单备注" @click="selectRemark">
              <u-input v-model="form.remark" border="none" suffix-icon="arrow-right" placeholder="请输入，选填" disabledColor="#ffffff" disabled />
            </u-form-item>
          </view>
          <view class="card">
            <u-form-item label="报价联系人">
              <u-input v-model="form.contactName" border="none" placeholder="请输入，选填" />
            </u-form-item>
            <u-form-item label="报价联系电话">
              <u-input v-model="form.contactMobile" border="none" placeholder="请输入，选填" />
            </u-form-item>
          </view>
        </template>
      </u-form>
    </template>
    <template #footer>
      <u-button :loading="loading" type="primary" @tap="submitAddFun">确定</u-button>
    </template>
    <tui-bottom-popup :show="vanTypeVisible" @close="vanTypeVisible = false">
      <view class="popup-more">
        <view class="pm-title">选择箱型</view>
        <view class="pm-list">
          <view v-for="(item, index) in vanTypeList" :key="index" @click="choseVanType(item.valueCode)" class="pm-btn">
            <text :class="choseVanTypeList.includes(item.valueCode) ? 'action' : ''">{{ item.valueName }}</text>
          </view>
        </view>
      </view>
    </tui-bottom-popup>
    <tui-bottom-popup :show="specificationVisible" @close="specificationVisible = false">
      <view class="popup-more">
        <view class="pm-title">选择车型</view>
        <view class="pm-list">
          <view v-for="(item, index) in specificationList" :key="index" @click="choseSpecification(item.valueCode)" class="pm-btn">
            <text :class="choseSpecificationList.includes(item.valueCode) ? 'action' : ''">{{ item.valueName }}</text>
          </view>
        </view>
      </view>
    </tui-bottom-popup>
    <u-toast ref="uToast"></u-toast>
  </Page>
</template>
<script>
import { urlParam } from '@/utils/param';
import { mapGetters } from 'vuex';
import dayjs from 'dayjs';
export default {
  name: 'good-source-add',
  data() {
    return {
      loading: false,
      showModal: '',
      showModal2: '',
      content: '',
      content2: '',
      carNumber: '',
      showLoadTime1: false,
      showLoadTime2: false,
      loadTimeDef1: new Date(),
      loadTimeDef2: new Date(),
      showCar: false,
      typeCar: '',
      more: false,
      radioList: [],
      form: {
        projectCode: '',
        loadTime: '',
        projectName: '',
        customerOrderCode: '',
        goodsName: '',
        goodsValue: '',
        goodsPiece: '',
        goodsWeight: '',
        goodsVolume: '',
        mobile: '',
        driverId: '',
        driverName: '',
        licenseNumber: '',
        trailerNumber: '',
        paidAmount: '',
        oilAmount: '',
        prepaidAmount: '',
        deliveryAmount: '',
        balancePaymentAmount: '',
        distance: '',
        allowDriverSeeFreightAmountNode: '',
        waypoints: [{}, {}],
        remark: '',
      },
      payeeModel: {},
      driverObj: {}, //司机信息
      currentFreight: {},
      vanTypeVisible: false,
      choseVanTypeList: [],
      specificationVisible: false,
      choseSpecificationList: [],
    };
  },
  computed: {
    ...mapGetters(['dictList', 'dictValue']),
    // 箱型
    vanTypeList() {
      return [...this.dictList('VEHICLE_COMPARTMENT_TYPE'), { valueCode: 'ALL', valueName: '不限' }];
    },
    formatVanType() {
      let res = [];
      for (let v of this.choseVanTypeList) {
        if (v === 'ALL') {
          res.push('不限');
        } else {
          res.push(this.dictValue('VEHICLE_COMPARTMENT_TYPE', v));
        }
      }
      return res.join('/');
    },
    // 箱型
    specificationList() {
      return [...this.dictList('VEHICLE_SPECIFICATION'), { valueCode: 'ALL', valueName: '不限' }];
    },
    formatSpecification() {
      let res = [];
      for (let v of this.choseSpecificationList) {
        if (v === 'ALL') {
          res.push('不限');
        } else {
          res.push(this.dictValue('VEHICLE_SPECIFICATION', v));
        }
      }
      return res.join('/');
    },
  },
  onLoad(option) {
    if (option.code) {
      uni.setNavigationBarTitle({ title: '修改货源' });
    }
  },
  methods: {
    initData(code) {
      uni.$u.api.freightOrder.getDetail({ code }).then(res => {
        let detail = res.result || {};
        ['goodsName', 'waypoints', 'allowDriverSeeFreightAmountNode', 'projectCode', 'projectName', 'remark', 'goodsPiece', 'goodsWeight', 'goodsVolume'].forEach(key => {
          this.form[key] = detail[key];
        });
        if (detail.vehicleLicenseNum) {
          this.typeCar = 'licenseNumber';
          this.form.licenseNumber = detail.vehicleLicenseNum;
          this.vehicleChange(detail.vehicleLicenseNum);
        }
        if (detail.trailerLicenseNum) {
          setTimeout(() => {
            this.typeCar = 'trailerNumber';
            this.form.trailerNumber = detail.trailerLicenseNum;
            this.vehicleChange(detail.trailerLicenseNum);
          }, 500);
        }
        this.form.mobile = detail.driverMobile;
        this.form.driverId = detail.driverId;
        this.form.driverName = detail.driverName;
        this.form.driverMobile = detail.driverMobile;
        this.payeeModel = {
          driverId: detail.payeeId,
          dueBank: detail.dueBank,
          openingBank: detail.openingBank,
          dueBankCardNo: detail.dueBankCardNo,
        };
        this.$refs.payee.setItem(this.payeeModel);
        this.computedDistance();
      });
    },
    selectRemark() {
      uni.$once('select-remark', remark => {
        this.form.remark = remark || '';
      });
      uni.navigateTo({
        url: `/pages/order/select-remark`,
      });
    },
    choseProjectCode() {
      uni.$once('select-common', option => {
        this.form.projectCode = option.code;
        this.form.projectName = option.name;
      });
      uni.navigateTo({
        url: `/pages/global/search-common${urlParam({
          mode: 'select',
          url: 'projectCode',
          title: '项目',
          label: 'name',
          value: '',
          params: '{"status":"ENABLE"}',
        })}`,
      });
    },
    // 选择箱型
    choseVanType(code) {
      if (this.choseVanTypeList.includes(code)) {
        this.choseVanTypeList = this.choseVanTypeList.filter(i => i !== code);
      } else {
        if (code === 'ALL') {
          this.choseVanTypeList = [code];
        } else {
          this.choseVanTypeList = this.choseVanTypeList.filter(i => i !== 'ALL');
          this.choseVanTypeList.push(code);
        }
      }
      this.form.vanType = this.choseVanTypeList.join('/');
    },
    // 选择车型
    choseSpecification(code) {
      if (this.choseSpecificationList.includes(code)) {
        this.choseSpecificationList = this.choseSpecificationList.filter(i => i !== code);
      } else {
        if (code === 'ALL') {
          this.choseSpecificationList = [code];
        } else {
          this.choseSpecificationList = this.choseSpecificationList.filter(i => i !== 'ALL');
          this.choseSpecificationList.push(code);
        }
      }
      this.form.specification = this.choseSpecificationList.join('/');
    },
    choseGoodsName() {
      uni.$once('select-common', option => {
        this.form.goodsName = option.name;
      });
      uni.navigateTo({
        url: `/pages/global/search-common${urlParam({
          mode: 'select',
          url: 'goodsName',
          title: '货物名称',
          label: 'name',
          value: '',
        })}`,
      });
    },
    selectAddress(index) {
      uni.$once('select-detail', location => {
        let station = {
          lng: location.lng,
          lat: location.lat,
          provinceCode: location.provinceCode,
          provinceName: location.provinceName,
          cityCode: location.cityCode,
          cityName: location.cityName,
          areaCode: location.areaCode,
          areaName: location.areaName,
          address: (location.provinceName || '') + (location.cityName || '') + (location.areaName || '') + (location.address || ''),
        };
        let waypoints = index === 0 ? [station, this.form.waypoints[1]] : [this.form.waypoints[0], station];
        this.form = {
          ...this.form,
          waypoints,
        };
        this.computedDistance();
      });
      let type = index === 0 ? 'getStartLatestAddress' : 'getEndLatestAddress';
      let lat = this.form.waypoints[index].lat ? Number(this.form.waypoints[index].lat) : '';
      let lng = this.form.waypoints[index].lng ? Number(this.form.waypoints[index].lng) : '';
      uni.navigateTo({ url: `/pages/global/search-address?type=${type}&lng=${lng}&lat=${lat}` });
    },

    loadTimeFormat1({ value }) {
      this.form.loadTime = dayjs(value).format('YYYY-MM-DD HH:mm:ss');
      this.showLoadTime1 = false;
    },
    loadTimeFormat2({ value }) {
      this.form.loadTime = dayjs(value).format('YYYY-MM-DD HH:mm:ss');
      this.showLoadTime2 = false;
    },
    choseGoodsType() {
      uni.$once('select-dict', option => {
        this.searchForm.goodsType = option.valueCode;
        this.searchForm.goodsTypeName = option.valueName;
      });
      uni.navigateTo({
        url: `/pages/global/search-dict${urlParam({
          title: '货物类型',
          dict: 'ONLINE_FREIGHT_ORDER_PAY_STATUS',
        })}`,
      });
    },
    chosePriceType() {
      uni.$once('select-dict', option => {
        this.searchForm.goodsType = option.valueCode;
        this.searchForm.goodsTypeName = option.valueName;
      });
      uni.navigateTo({
        url: `/pages/global/search-dict${urlParam({
          title: '计价方式',
          dict: 'ONLINE_FREIGHT_ORDER_PAY_STATUS',
        })}`,
      });
    },
    submitAddFun() {
      if (this.loading) return;
      this.loading = true;
      let totalAmount = Number(this.form.paidAmount || 0) + Number(this.form.serviceAmount || 0) + Number(this.form.securityServiceAmount || 0);
      uni.$u.api.freightOrder
        .add({ ...this.form, totalAmount, payeeId: this.payeeModel.driverId })
        .then(res => {
          if (res.success) {
            this.form = {};
            uni.showToast({ title: '下单成功', icon: 'none' });
            this.getOpenerEventChannel().emit('refreshData');
            setTimeout(() => uni.navigateBack(), 500);
          }
          this.loading = false;
        })
        .catch(e => {
          this.loading = false;
          this.$refs.uToast.show({
            type: 'default',
            message: e,
          });
        });
    },
  },
};
</script>
<style lang="scss">
.page-good-source-add {
  &__footer {
    background: $color-white;
  }
  .card {
    color: #999999;
    margin-bottom: $padding-md;
    background-color: $color-white;
    border-radius: $radius-md;
    box-shadow: $shadow-normal;
    .u-form-item {
      padding-left: $padding-md !important;
      padding-right: $padding-sm !important;
    }
    .u-form-item + .u-form-item {
      border-top: 1px solid #f6f6f6;
    }
    .more-action {
      display: flex;
      padding: $padding-sm;
      justify-content: center;
      align-content: center;
      align-items: center;
      .sx-img {
        height: 12upx;
        width: 14upx;
        position: relative;
        margin-left: 12upx;

        .sx-image {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
        }
        .up {
          transform: rotate(180deg);
        }
      }
    }
  }
  .popup-more {
    background: #fff;
    border-radius: 20rpx;
    .pm-title {
      display: flex;
      justify-content: center;
      color: #999999;
      font-size: 32rpx;
      padding: 32rpx 0;
    }
    .pm-list {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      grid-gap: 10px;
      padding-bottom: 70rpx;
      .pm-btn {
        padding: 20rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        color: #2b2a27;
        font-size: 30rpx;
        font-weight: 700;
        .action {
          color: #2673fb;
        }
      }
    }
  }
}
</style>
