<!--
@name: 已派车-修改
@author: 张泽贤
@time: 2022-04-28
-->
<template>
  <p-spin :spinning="spinning">
    <p-card>
      <!-- <div slot="title" style="display: flex; align-items: center; cursor: pointer">
        <a-icon type="arrow-left" style="color: #1990ff" @click="back" />
        {{ typeTitle }}
      </div> -->
      <a-space slot="extra" v-show="editType === 'edit'">
        <p-button type="primary" @click="onSave">保存</p-button>
      </a-space>
      <p-form-model ref="formTarget" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" class="plg-grid-from">
        <a-row>
          <a-col :span="6">
            <p-form-model-item label="订单数">{{ form.shipbillNumber }}</p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="总件数">{{ form.totalPcs }}</p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="总重量">{{ form.totalWeight }}</p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="总体积">{{ form.totalVolume }}</p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="承运方类型">{{ form.carrierTypeName }}</p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <p-form-model-item label="司机" prop="driverName">
              <span v-if="editType === 'view'">{{ form.driverName }}</span>
              <p-search-modal v-model="form.driverName" v-bind="driverAttr" @ok="(...args) => onFormChange('driver', ...args)" :targetClick="false" @input="onFormInput('driver')" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="司机手机号" prop="driverPhoneNumber">
              <span v-if="editType === 'view'">{{ form.driverPhoneNumber }}</span>
              <p-input v-model="form.driverPhoneNumber" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="送货员" prop="deliverymanName">
              <span v-if="editType === 'view'">{{ form.deliverymanName }}</span>
              <p-search-modal v-model="form.deliverymanName" v-bind="deliveryAttr" @ok="(...args) => onFormChange('delivery', ...args)" :targetClick="false" @input="onFormInput('delivery')" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="送货员手机号" prop="deliverymanPhoneNumber">
              <span v-if="editType === 'view'">{{ form.deliverymanPhoneNumber }}</span>
              <p-input v-model="form.deliverymanPhoneNumber" v-else />
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <p-form-model-item label="车辆" prop="vehiclePlateNumber">
              <span v-if="editType === 'view'">{{ form.vehiclePlateNumber }}</span>
              <p-search-modal v-model="form.vehiclePlateNumber" v-bind="carAttr" @ok="(...args) => onFormChange('car', ...args)" :targetClick="false" @input="onFormInput('car')" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="车型">{{ form.vehicleTypeName }}</p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="隶属机构" prop="vehicleAffiliationName">
              <span v-if="editType === 'view'">{{ form.vehicleAffiliationName }}</span>
              <p-search-modal v-model="form.vehicleAffiliationName" v-bind="affiliationAttr" @change="(...args) => onFormChange('affiliation', ...args)" :disabled="disAffiliation" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="装载率">{{ form.loadingRate }}</p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <p-form-model-item label="车辆类别" prop="vehicleTypeCategoryName">{{ form.vehicleTypeCategoryName }}</p-form-model-item>
          </a-col>
          <a-col :span="6" v-if="RELATION_THIRD_SYSTEM.includes('2') || RELATION_THIRD_SYSTEM.includes('3')">
            <p-form-model-item label="容器号" prop="containerName">
              <span v-if="editType === 'view'">{{ form.containerName }}</span>
              <p-search-modal v-model="form.containerName" v-bind="containerAttr" @change="(...args) => onFormChange('container', ...args)" :disabled="!form.vehiclePlateNumber" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" v-if="RELATION_THIRD_SYSTEM.includes('1')">
            <p-form-model-item label="设备号" prop="vehicleDeviceName">
              <span v-if="editType === 'view'">{{ form.vehicleDeviceName }}</span>
              <p-search-modal v-model="form.vehicleDeviceName" v-bind="deviceAttr" @change="(...args) => onFormChange('device', ...args)" :disabled="!form.vehiclePlateNumber" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="系统标志">{{ form.carrierSysFlagName }}</p-form-model-item>
          </a-col>
        </a-row>
      </p-form-model>

      <waybillList ref="waybillList" :editType="editType" :editData="editData" :options="options" @update="viewUrl"></waybillList>
    </p-card>
  </p-spin>
</template>

<script>
import * as $formItems from '@/blocks/components/searchModalConfig/index'
import store from '@/store'

import { setQueryFormItmes } from '../js/form'
import { viewUrl, sendcar_update } from '../js/api'

import waybillList from './waybillList.vue'

export default {
  components: { waybillList },
  props: {
    editType: {
      type: String,
      default: '',
    },
    editData: {
      type: Object,
      default: () => ({}),
    },
    options: {
      type: Object,
      default: () => ({}),
    },
    mextendedField_list: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    RELATION_THIRD_SYSTEM() {
      return this.$store.state?.sysParameter?.sysParameter_TMS?.RELATION_THIRD_SYSTEM?.value?.split(',') ?? [];
    },
    typeTitle() {
      const dictionary = {
        edit: '修改',
        view: '查看',
      }
      return dictionary[this.editType] || this.editType
    },
    driverAttr() {
      let driverAttr = $formItems.driverAttr
      driverAttr.tableConfig.rowSelectType = 2
      return driverAttr
    },
    deliveryAttr() {
      let deliveryAttr = $formItems.deliveryAttr
      deliveryAttr.tableConfig.rowSelectType = 2
      return deliveryAttr
    },
    carAttr() {
      return Object.assign({ remoteData: { driverIds: this.form.driverId.split(',') } }, $formItems.carAttr)
      // return $formItems.carAttr
    },
    affiliationAttr() {
      let carrierAttr = $formItems.carrierAttr;
      carrierAttr.targetValueKey = 'name';
      return carrierAttr;
    },
    deviceAttr() {
      let deviceAttr = $formItems.deviceAttr_scanPage;
      deviceAttr.tableConfig.rowSelectType = 2;
      return Object.assign({ remoteData: { vehicleId: this.form.vehicleId } }, deviceAttr);
    },
    containerAttr() {
      let containerAttr = $formItems.containerAttr;
      containerAttr.tableConfig.rowSelectType = 2;
      return Object.assign({ remoteData: { vehiclePlateNumber: this.form.vehiclePlateNumber } }, containerAttr);
    },
  },
  data() {
    return {
      $formItems,
      setQueryFormItmes: setQueryFormItmes(this),
      spinning: false,

      form: {
        driverId: '',
        driverCode: '',
        driverName: '',
        driverPhoneNumber: '',
        deliverymanId: '',
        deliverymanCode: '',
        deliverymanName: '',
        deliverymanPhoneNumber: '',
        vehicleId: '',
        vehicleCode: '',
        vehiclePlateNumber: '',
        vehicleTypeCode: '',
        vehicleTypeName: '',
      },
      disAffiliation: false,

    }
  },
  mounted() {
    // this.RELATION_THIRD_SYSTEM = store.state.sysParameter.sysParameter_TMS?.RELATION_THIRD_SYSTEM.value.split(',');
    this.viewUrl();
  },
  methods: {
    // 返回
    // back() {
    //   this.$emit('back')
    // },
    // 保存
    onSave() {
      if (!this.form.driverName) {
        this.$message.error('请选择司机')
        return false
      }
      if (!this.form.vehiclePlateNumber) {
        this.$message.error('请选择车辆')
        return false
      }
      let params = { ...this.form, sendCarUpdateDetailVOS: [] }
      let waybillList = this.$refs.waybillList.waybillDataSource
      console.log(waybillList)
      for (let index = 0; index < waybillList.length; index++) {
        const element = waybillList[index]
        // if (!element.shippingOrder) {
        //   this.$message.error('请输入配送顺序')
        //   return false
        // }
        params.sendCarUpdateDetailVOS.push({ id: element.id, shippingOrder: element.shippingOrder })
      }

      this.spinning = true
      sendcar_update(params)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('back')
          } else {
            this.$exception(res)
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },

    onFormChange(name, ...args) {
      let idList = [],
        codeList = [],
        phoneList = [],
        affiliationIdSet = new Set(),
        affiliationCodeSet = new Set(),
        affiliationNameSet = new Set();
      args[2].forEach((item) => {
        idList.push(item.id)
        codeList.push(item.code)
        if (name === 'driver' || name === 'delivery') phoneList.push(item.phoneNumber)
        if (name === 'driver') {
          affiliationIdSet.add(item.affiliationId);
          affiliationCodeSet.add(item.affiliationCode);
          affiliationNameSet.add(item.affiliationName);
        }
      })
      if (name === 'driver') {
        this.form.driverId = idList.join(',')
        this.form.driverCode = codeList.join(',')
        this.form.driverName = args[1]
        this.form.driverPhoneNumber = phoneList.join(',')
        // 如果选择的司机里只有一个隶属机构（承运商），回显并且不能编辑；如果有多个，弹窗编辑
        if (affiliationIdSet.size === 1) {
          this.disAffiliation = true;
          this.form.vehicleAffiliationId = [...affiliationIdSet][0];
          this.form.vehicleAffiliationCode = [...affiliationCodeSet][0];
          this.form.vehicleAffiliationName = [...affiliationNameSet][0];
        } else {
          this.disAffiliation = false;
          this.form.vehicleAffiliationId = '';
          this.form.vehicleAffiliationCode = '';
          this.form.vehicleAffiliationName = '';
        }
        // 如果只有一辆车，默认选中
        if (args[2].length === 1) {
          this.form.vehicleId = args[2][0].vehicleId;
          this.form.vehicleCode = args[2][0].vehicleCode;
          this.form.vehiclePlateNumber = args[2][0].vehiclePlateNumber;
          this.form.vehicleTypeCode = args[2][0].vehicleTypeCode;
          this.form.vehicleTypeName = args[2][0].vehicleTypeName;
          this.form.vehicleTypeCategory = args[2][0].vehicleTypeCategory;
          this.form.vehicleTypeCategoryName = args[2][0].vehicleTypeCategoryName;
          this.form.vehicleDeviceId = '';
          this.form.vehicleDeviceCode = '';
          this.form.vehicleDeviceName = '';
          this.form.volumeLoadingRate = args[2][0].volume ? parseFloat(this.BigJs(this.form.actualTotalVolume).div(args[2][0].volume).times(100)).toFixed(0) + '%' : '';
          this.form.weightLoadingRate = args[2][0].weight ? parseFloat(this.BigJs(this.form.actualTotalWeight).div(args[2][0].weight).times(100)).toFixed(0) + '%' : '';
        }
      } else if (name === 'delivery') {
        this.form.deliverymanId = idList.join(',')
        this.form.deliverymanCode = codeList.join(',')
        this.form.deliverymanName = args[1]
        this.form.deliverymanPhoneNumber = phoneList.join(',')
      } else if (name === 'car') {
        this.form.vehicleId = args[2][0].id
        this.form.vehicleCode = args[2][0].code
        this.form.vehiclePlateNumber = args[2][0].plateNumber
        this.form.vehicleTypeCode = args[2][0].vehicleTypeCode
        this.form.vehicleTypeName = args[2][0].vehicleTypeName
        this.form.vehicleTypeCategory = args[2][0].typeCategory;
        this.form.vehicleTypeCategoryName = args[2][0].typeCategoryName;
        this.form.vehicleDeviceId = '';
        this.form.vehicleDeviceCode = '';
        this.form.vehicleDeviceName = '';

        let volumeLoadingRate = parseFloat(this.BigJs(this.form.totalVolume).div(args[2][0].volume).times(100)).toFixed(0) + '%'
        let weightLoadingRate = parseFloat(this.BigJs(this.form.totalWeight).div(args[2][0].weight).times(100)).toFixed(0) + '%'
        console.log(volumeLoadingRate, weightLoadingRate)
        this.form.loadingRate = weightLoadingRate + ',' + volumeLoadingRate
      } else if (name === 'affiliation') {
        this.form.vehicleAffiliationId = args[2][0].id;
        this.form.vehicleAffiliationCode = args[2][0].code;
        this.form.vehicleAffiliationName = args[2][0].name;
      } else if (name === 'device') {
        let idList = [],
          codeList = [],
          nameList = [];
        args[2].forEach((item) => {
          item.deviceId && idList.push(item.deviceId);
          item.deviceCode && codeList.push(item.deviceCode);
          item.deviceName && nameList.push(item.deviceName);
        });
        this.form.vehicleDeviceId = idList.join(',');
        this.form.vehicleDeviceCode = codeList.join(',');
        this.form.vehicleDeviceName = nameList.join(',');
      } else if (name === 'container') {
        let idList = [],
          codeList = [],
          nameList = [];
        args[2].forEach((item) => {
          item.id && idList.push(item.id);
          item.code && codeList.push(item.code);
          item.name && nameList.push(item.name);
        });
        this.form.containerId = idList.join(',');
        this.form.containerCode = codeList.join(',');
        this.form.containerName = nameList.join(',');
      }
    },

    // 查询
    viewUrl() {
      viewUrl({ id: this.editData.loadingBillId }).then((res) => {
        this.form = { ...res.data }
        delete this.form.sendCarViewDetailByIdDTOS
      })
    },

    onFormInput(name) {
      if (name === 'driver') {
        this.form.driverId = ''
        this.form.driverCode = ''
      } else if (name === 'delivery') {
        this.form.deliverymanId = ''
        this.form.deliverymanCode = ''
        this.form.deliverymanPhoneNumber = ''
      } else if (name === 'car') {
        this.form.vehicleId = ''
        this.form.vehicleCode = ''
        this.form.vehicleTypeCode = ''
        this.form.vehicleTypeName = ''
        this.form.volumeLoadingRate = ''
        this.form.weightLoadingRate = ''
        this.form.vehicleTypeCategory = '';
        this.form.vehicleTypeCategoryName = '';
        this.form.vehicleDeviceId = '';
        this.form.vehicleDeviceCode = '';
        this.form.vehicleDeviceName = '';
      }
    },
  },
}
</script>