<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.startTime" 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.endTime" 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="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="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="choseGoodsName">
            <u-input :value="form.goodsName" 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.priceTypeName" border="none" suffix-icon="arrow-right" placeholder="请选择" disabledColor="#ffffff" disabled />
          </u-form-item>
          <template v-if="form.priceType === 'TON'">
            <u-form-item label="货物总量" required>
              <u-input v-model="form.goodsWeight" border="none" type="digit" placeholder="请输入">
                <template slot="suffix">吨</template>
              </u-input>
            </u-form-item>
            <u-form-item label="运输单价">
              <u-input v-model="form.weightUnitPrice" border="none" type="digit" placeholder="请输入">
                <template slot="suffix">元/吨</template>
              </u-input>
            </u-form-item>
          </template>
          <template v-if="form.priceType === 'VEHICLE'">
            <u-form-item label="需求车数" required>
              <u-input v-model="form.vehicleNumber" border="none" type="number" placeholder="请输入">
                <template slot="suffix">车</template>
              </u-input>
            </u-form-item>
            <u-form-item label="总运费">
              <u-input v-model="form.vehicleUnitPrice" border="none" type="digit" placeholder="请输入">
                <template slot="suffix">元/车</template>
              </u-input>
            </u-form-item>
          </template>
        </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="订单备注">
              <u-input v-model="form.remark" border="none" suffix-icon="arrow-right" placeholder="请输入，选填" />
            </u-form-item>
          </view>
          <view class="card">
            <u-form-item label="报价联系人">
              <u-input v-model="form.contactUser" 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 { formatLngLat } from '@/utils/format-value';
import { mapGetters } from 'vuex';
import dayjs from 'dayjs';
export default {
  name: 'good-source-add',
  data() {
    return {
      loading: false,
      showLoadTime1: false,
      showLoadTime2: false,
      loadTimeDef1: new Date(),
      loadTimeDef2: new Date(),
      more: false,
      waypoints: [{}, {}],
      form: {
        code: '',
        projectCode: '',
        projectName: '',
        startTime: '',
        endTime: '',
        startCityCode: '',
        startAreaCode: '',
        startAddress: '',
        startLng: '',
        startLat: '',
        endCityCode: '',
        endAreaCode: '',
        endAddress: '',
        endLng: '',
        endLat: '',
        distance: '',
        specification: '',
        vanType: '',
        goodsName: '',
        priceType: 'VEHICLE', // VEHICLE, TON
        priceTypeName: '',
        goodsWeight: '',
        weightUnitPrice: '',
        vehicleNumber: '',
        vehicleUnitPrice: '',
        contactUser: '',
        contactMobile: '',
        remark: '',
      },
      vanTypeVisible: false,
      choseVanTypeList: [],
      specificationVisible: false,
      choseSpecificationList: [],
    };
  },
  computed: {
    ...mapGetters(['dictList', 'dictValue', 'userInfo']),
    // 箱型
    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: '修改货源' });
      this.initData(option.code);
    }
    this.form = {
      ...this.form,
      contactUser: this.userInfo.name,
      contactMobile: this.userInfo.mobile,
    };
    if (this.form.priceType) {
      this.form.priceTypeName = this.dictValue('FREIGHT_GOODS_SOURCE_PRICE_TYPE', this.form.priceType);
    }
  },
  methods: {
    initData(code) {
      uni.$u.api.freightGoodsSourceV2.getDetail({ code }).then(res => {
        let detail = res.result || {};
        Object.keys(this.form).forEach(key => {
          this.form[key] = detail[key];
        });
        let startAddressObj = {
          address: detail.startAddress,
          areaCode: detail.startAreaCode,
          cityCode: detail.startCityCode,
          lng: detail.startLng,
          lat: detail.startLat,
        };
        let endAddressObj = {
          address: detail.endAddress,
          areaCode: detail.endAreaCode,
          cityCode: detail.endCityCode,
          lng: detail.endLng,
          lat: detail.endLat,
        };
        this.waypoints = [startAddressObj, endAddressObj];
        this.choseVanTypeList = detail.vanType.split(',');
        this.choseSpecificationList = detail.specification.split(',');
        if (this.form.priceType) {
          this.form.priceTypeName = this.dictValue('FREIGHT_GOODS_SOURCE_PRICE_TYPE', this.form.priceType);
        }
      });
    },
    // 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(',');
    },
    chosePriceType() {
      uni.$once('select-dict', option => {
        this.form.priceType = option.valueCode;
        this.form.priceTypeName = option.valueName;
      });
      uni.navigateTo({
        url: `/pages/global/search-dict${urlParam({
          title: '计价方式',
          dict: 'FREIGHT_GOODS_SOURCE_PRICE_TYPE',
        })}`,
      });
    },
    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) {
      let lat = this.waypoints[index].lat ? Number(this.waypoints[index].lat) : '';
      let lng = this.waypoints[index].lng ? Number(this.waypoints[index].lng) : '';
      wx.chooseLocation({
        latitude: lat ? Number(lat) : undefined,
        longitude: lng ? Number(lng) : undefined,
      })
        .then(res => {
          return formatLngLat({ lng: res.longitude, lat: res.latitude });
        })
        .then(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 || ''),
          };
          this.waypoints = index === 0 ? [station, this.waypoints[1]] : [this.waypoints[0], station];
          this.computedDistance();
        });
      // 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 || ''),
      //   };
      //   this.waypoints = index === 0 ? [station, this.waypoints[1]] : [this.waypoints[0], station];
      // });
      // let type = index === 0 ? 'getStartLatestAddress' : 'getEndLatestAddress';
      // let lat = this.waypoints[index].lat ? Number(this.waypoints[index].lat) : '';
      // let lng = this.waypoints[index].lng ? Number(this.waypoints[index].lng) : '';
      // uni.navigateTo({ url: `/pages/global/search-address?type=${type}&lng=${lng}&lat=${lat}` });
    },
    computedDistance() {
      if (this.waypoints[0].lng && this.waypoints[1].lng) {
        uni.$u.api.freightOrder
          .getDistance({
            startLat: this.waypoints[0].lat,
            startLng: this.waypoints[0].lng,
            endLat: this.waypoints[1].lat,
            endLng: this.waypoints[1].lng,
          })
          .then(res => {
            this.form.distance = res.result;
          });
      }
    },
    loadTimeFormat1({ value }) {
      this.form.startTime = dayjs(value).format('YYYY-MM-DD HH:mm:ss');
      this.showLoadTime1 = false;
    },
    loadTimeFormat2({ value }) {
      this.form.endTime = dayjs(value).format('YYYY-MM-DD HH:mm:ss');
      this.showLoadTime2 = false;
    },
    submitAddFun() {
      if (this.loading) return;
      this.loading = true;
      let startAddressObj = {
        startCityCode: this.waypoints[0].cityCode,
        startAreaCode: this.waypoints[0].areaCode,
        startAddress: this.waypoints[0].address,
        startLng: this.waypoints[0].lng,
        startLat: this.waypoints[0].lat,
      };
      let endAddressObj = {
        endCityCode: this.waypoints[1].cityCode,
        endAreaCode: this.waypoints[1].areaCode,
        endAddress: this.waypoints[1].address,
        endLng: this.waypoints[1].lng,
        endLat: this.waypoints[1].lat,
      };
      let opType = this.form.code ? 'modify' : 'add';
      uni.$u.api.freightGoodsSourceV2[opType]({ ...this.form, ...startAddressObj, ...endAddressObj })
        .then(res => {
          if (res.success) {
            this.form = {};
            uni.showToast({ title: '成功', icon: 'none' });
            this.getOpenerEventChannel().emit('refreshData');
            setTimeout(() => uni.navigateBack(), 1000);
          }
          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>
