<template>
  <Page name="order-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="showLoadTime = true" required>
            <u-datetime-picker :show="showLoadTime" :value="loadTimeDef" @cancel="showLoadTime = false" @close="showLoadTime = false" @confirm="loadTimeFormat"></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="内部单号">
            <u-input v-model="form.customerOrderCode" border="none" placeholder="请输入，选填" />
          </u-form-item>
        </view>
        <view class="card">
          <u-form-item label="装货地址" required @click="() => selectLocation(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="() => selectLocation(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="choseGoodsName">
            <u-input v-model="form.goodsName" border="none" suffix-icon="arrow-right" placeholder="请选择" disabledColor="#ffffff" disabled />
          </u-form-item>
          <u-form-item v-if="showGoodsValue" label="货物价值" required>
            <u-input v-model="form.goodsValue" border="none" type="digit" placeholder="请输入" />
          </u-form-item>
          <u-form-item label="货物件数">
            <u-input v-model="form.goodsPiece" border="none" type="digit" placeholder="请输入，选填" />
          </u-form-item>
          <u-form-item label="货物吨数" required>
            <u-input v-model="form.goodsWeight" border="none" type="digit" placeholder="请输入" />
          </u-form-item>
          <u-form-item label="货物方数">
            <u-input v-model="form.goodsVolume" border="none" type="digit" placeholder="请输入，选填" />
          </u-form-item>
        </view>
        <view class="card">
          <u-form-item label="司机手机" required>
            <u-input v-model="form.mobile" border="none" type="number" placeholder="请输入" @blur="mobileChange" />
          </u-form-item>
          <u-form-item label="司机姓名" required>
            <u-input v-model="form.driverName" border="none" placeholder="请输入" :disabled="!!form.driverId" />
          </u-form-item>
          <view class="payee">
            <payee ref="payee" v-model="payeeModel" :have-action="isCollect" />
          </view>
          <u-form-item label="车牌号" required @click="choseCar('licenseNumber')">
            <u-input v-model="form.licenseNumber" border="none" placeholder="请输入" disabledColor="#ffffff" disabled />
          </u-form-item>
          <u-form-item label="车挂号" @click="choseCar('trailerNumber')">
            <u-input v-model="form.trailerNumber" border="none" placeholder="请输入" disabledColor="#ffffff" disabled />
          </u-form-item>
        </view>
        <view class="card">
          <u-form-item label="应付司机运费">
            <u-input v-model="form.paidAmount" border="none" type="digit" prefix-icon="rmb" placeholder="请输入" @change="computedService" />
          </u-form-item>
          <u-form-item label="油卡" v-if="currentFreight.oilPayFlag">
            <u-input v-model="form.oilAmount" border="none" type="digit" prefix-icon="rmb" placeholder="请输入" @change="computedService" />
          </u-form-item>
          <u-form-item label="预付款" v-if="currentFreight.prePayFlag">
            <u-input v-model="form.prepaidAmount" border="none" type="digit" prefix-icon="rmb" placeholder="请输入" @change="computedService" />
          </u-form-item>
          <u-form-item label="货到款" v-if="currentFreight.arrivalPayFlag">
            <u-input
              v-model="form.deliveryAmount"
              border="none"
              type="digit"
              prefix-icon="rmb"
              :disabled="autoComputedArrival"
              :placeholder="autoComputedArrival ? '自动计算' : '请输入'"
              @change="computedService"
            />
          </u-form-item>
          <u-form-item label="尾款/回单付">
            <u-input
              v-model="form.balancePaymentAmount"
              border="none"
              type="digit"
              prefix-icon="rmb"
              @change="computedService"
              :disabled="!autoComputedArrival"
              :placeholder="!autoComputedArrival ? '自动计算' : '请输入'"
            />
          </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="装货联系人">
              <u-input v-model="form.waypoints[0].contactName" border="none" placeholder="请输入，选填" />
            </u-form-item>
            <u-form-item label="装货联系电话">
              <u-input v-model="form.waypoints[0].contactMobile" border="none" placeholder="请输入，选填" />
            </u-form-item>
          </view>
          <view class="card">
            <u-form-item label="卸货联系人">
              <u-input v-model="form.waypoints[1].contactName" border="none" placeholder="请输入，选填" />
            </u-form-item>
            <u-form-item label="卸货联系电话">
              <u-input v-model="form.waypoints[1].contactMobile" border="none" placeholder="请输入，选填" />
            </u-form-item>
          </view>
          <view class="card">
            <u-form-item label="订单备注">
              <u-input v-model="form.remark" border="none" placeholder="请输入，选填" />
            </u-form-item>
          </view>
        </template>
      </u-form>
    </template>
    <template #footer>
      <u-button type="primary" @tap="submitAddFun">下单并指派</u-button>
    </template>
    <u-toast ref="uToast"></u-toast>
    <popup-platenumber :visible="showCar" @update:visible="e => (showCar = e)" @confirm="carConfirm" v-model="carNumber"></popup-platenumber>
  </Page>
</template>
<script>
import { urlParam } from '@/utils/param';
import dayjs from 'dayjs';
import payee from '../../components/card/payee.vue';
import PopupPlatenumber from '../../components/popup/popup-platenumber.vue';
export default {
  name: 'order-add',
  components: { PopupPlatenumber, payee },
  data() {
    return {
      carNumber: '',
      showLoadTime: false,
      loadTimeDef: 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: [{}, {}],
      },
      payeeModel: {},
      currentFreight: {},
    };
  },
  computed: {
    isCollect() {
      return this.currentFreight.collectByOtherFlag || false;
    },
    autoComputedArrival() {
      // 自动计算货到
      return 'OUT_INVITE_ARRIVAL' === this.currentFreight?.autoComputeFeeType;
    },
    // 获取价值
    showGoodsValue() {
      return this.currentFreight ? this.currentFreight.driverSecurityServiceFlag || this.currentFreight.securityServiceFlag : false;
    },
  },
  onLoad(option) {
    if (option.code) {
      this.initData(option.code);
    }
    this.initConfig();
  },
  methods: {
    initConfig() {
      uni.$u.api.freightOrder.currentFreight({}).then(en => {
        this.currentFreight = en?.result || {};
        this.form.allowDriverSeeFreightAmountNode = this.currentFreight.allowDriverSeeFreightAmountNode;
      });
      uni.$u.api.filter.projectCode({}).then(res => {
        if (res.success && res.result && res.result.length === 1) {
          this.form.projectCode = res.result[0].code;
          this.form.projectName = res.result[0].name;
        }
      });
    },
    initData(code) {
      uni.$u.api.freightOrder.getDetail({ code }).then(res => {
        let detail = res.result || {};
        ['goodsName', 'waypoints', 'allowDriverSeeFreightAmountNode', 'projectCode', 'projectName'].forEach(key => {
          this.form[key] = detail[key];
        });
        this.computedDistance();
      });
    },
    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"}',
        })}`,
      });
    },
    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: '',
        })}`,
      });
    },
    // 地图选点
    selectLocation(index) {
      uni.$once('webview-select', 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();
      });
      const url = 'https://zeyi-tms-product.oss-cn-hangzhou.aliyuncs.com/webview/location-wx.html';
      const params = {
        lat: this.form.waypoints[index].lat ? Number(this.form.waypoints[index].lat) : '',
        lng: this.form.waypoints[index].lng ? Number(this.form.waypoints[index].lng) : '',
      };
      uni.navigateTo({ url: `/pages/common/webview?url=${url}&query=${JSON.stringify(params)}` });
    },
    computedDistance() {
      if (this.form.waypoints[0].lng && this.form.waypoints[1].lng) {
        uni.$u.api.freightOrder
          .getDistance({
            startLat: this.form.waypoints[0].lat,
            startLng: this.form.waypoints[0].lng,
            endLat: this.form.waypoints[1].lat,
            endLng: this.form.waypoints[1].lng,
          })
          .then(res => {
            this.form.distance = res.result;
          });
      }
    },
    loadTimeFormat({ value }) {
      this.form.loadTime = dayjs(value).format('YYYY-MM-DD HH:mm:ss');
      this.showLoadTime = false;
    },
    mobileChange() {
      if (this.form.mobile && this.form.mobile.length === 11) {
        uni.$u.api.filter.driver({ query: this.form.mobile }).then(res => {
          if (res.success && res.result && res.result.length === 1) {
            this.form.driverId = res.result[0].id;
            this.form.driverName = res.result[0].name;
            this.form.driverMobile = res.result[0].mobile;
            this.payeeModel = res.result[0];
            this.$refs.payee.setItem(this.payeeModel);
          } else {
            this.form.driverId = '';
            this.form.driverName = '';
            this.form.driverMobile = this.form.mobile;
            this.payeeModel = {};
            this.$refs.payee.setItem(this.payeeModel);
          }
        });
      }
    },
    vehicleChange(v) {
      if (this.typeCar === 'licenseNumber') {
        // 车头
        uni.$u.api.filter.vehicle({ query: v, operationModeList: 'OUT_INVITE' }).then(res => {
          if (res.success && res.result && res.result.length === 1) {
            let item = res.result[0];
            this.form.vehicleCode = item.code;
            this.form.specification = item.specification;
            if (item && item.type === 'TRACTOR' && item.vehicleList && item.vehicleList.length > 0) {
              this.form.trailerNumber = item.vehicleList[0].licenseNumber;
              this.form.trailerCode = item.vehicleList[0].code;
              this.form.specification = item.vehicleList[0].specification;
            }
          } else {
            this.form.vehicleCode = '';
            this.form.specification = '';
            this.form.trailerCode = '';
            this.form.trailerNumber = '';
          }
        });
      } else {
        uni.$u.api.filter.vehicle({ query: v, operationModeList: 'OUT_INVITE' }).then(res => {
          if (res.success && res.result && res.result.length === 1) {
            let item = res.result[0];
            this.form.trailerCode = item.code;
            this.form.specification = item.specification;
          } else {
            this.form.trailerCode = '';
            this.form.specification = '';
          }
        });
      }
    },
    choseCar(type) {
      this.typeCar = type;
      this.carNumber = '';
      this.showCar = true;
    },
    carConfirm(v) {
      this.form[this.typeCar] = v;
      this.showCar = false;
      this.vehicleChange(v);
    },
    computedService() {
      uni.$u.debounce(this.getServiceAmountInfo, 500);
    },
    getServiceAmountInfo() {
      const { paidAmount = '', oilAmount = '', deliveryAmount = '', prepaidAmount = '', balancePaymentAmount = '', goodsName = '', goodsValue = '' } = this.form;
      let params = {
        paidAmount,
        deliveryAmount,
        prepaidAmount,
        oilAmount,
        balancePaymentAmount,
        goodsName,
        goodsValue,
      };
      uni.$u.api.freightOrder.getServiceAmount(params).then(res => {
        if (res.success) {
          this.form.paidAmount = res.result.paidAmount || paidAmount;
          this.form.deliveryAmount = res.result.deliveryAmount || deliveryAmount;
          this.form.prepaidAmount = res.result.prepaidAmount || prepaidAmount;
          this.form.oilAmount = res.result.oilAmount || oilAmount;
          this.form.balancePaymentAmount = res.result.balancePaymentAmount || balancePaymentAmount;
          this.form.oilPayRebateRate = res.result.oilPayRebateRate || '';
          this.form.driverSecurityServiceAmount = res.result.driverSecurityServiceAmount || '';
          this.form.securityServiceAmount = res.result.securityServiceAmount || '';
          this.form.serviceAmount = res.result.serviceAmount || '';
          this.form.serviceRate = res.result.serviceRate || '';
        }
      });
    },
    submitAddFun() {
      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) {
            uni.showToast({ title: '下单成功', icon: 'none' });
            this.getOpenerEventChannel().emit('refreshData');
            setTimeout(() => uni.navigateBack(), 500);
          }
        })
        .catch(e => {
          this.$refs.uToast.show({
            type: 'default',
            message: e,
          });
        });
    },
  },
};
</script>
<style lang="scss">
.page-order-add {
  &__footer {
    background: $color-white;
  }
  .payee {
    margin-right: $padding-xs;
    margin-left: $padding-xs;
  }
  .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);
        }
      }
    }
  }
}
</style>
