<!--
@name: 派车单收入业务-编辑页
@author: 张泽贤
@time: 2023-04-14
@doc:
-->
<template>
  <div>
    <p-spin :spinning="spinning" v-show="!detailsType">
      <p-card>
        <a-space slot="title" style="display: flex; align-items: center; cursor: pointer">
          <a-icon type="arrow-left" style="color: #1990ff" @click="back" />
          派车单收入业务-{{ typeTitle }}
        </a-space>
        <div slot="extra" v-show="editType !== 'view'">
          <p-button type="primary" @click="onSave">保存</p-button>
        </div>
      </p-card>
      <p-card>
        <a-divider orientation="left">派车单信息</a-divider>
        <p-form-model ref="ruleForm" class="plg-grid-from" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" :rules="rules">
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="派车单号" prop="loadingBillNo">
                <div v-if="editType === 'view'">{{ form.loadingBillNo }}</div>
                <p-input v-model="form.loadingBillNo" disabled v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="派车单状态" prop="status">
                <div v-if="editType === 'view'">{{ form.statusName }}</div>
                <p-select v-model="form.status" :options="options.LOADING_BILL_STATUS" disabled v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="货主" prop="cargoOwnerName">
                <div v-if="editType === 'view'">{{ form.cargoOwnerName }}</div>
                <p-search-modal v-model="form.cargoOwnerName" v-bind="$data.$formItems.consignorAttr" @change="(...args) => onFormChange('consignor', ...args)" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="结算部门" prop="departmentName">
                <div v-if="editType === 'view'">{{ form.departmentName }}</div>
                <departmenTree :departmentCode="departmentCode" @getDepartment="getDepartment" v-else />
              </p-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="调度日期" prop="loadingDate">
                <div v-if="editType === 'view'">{{ form.loadingDate }}</div>
                <p-date-picker v-model="form.loadingDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" style="width: 100%" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="调度审核日期" prop="loadingAuditDate">
                <div v-if="editType === 'view'">{{ form.loadingAuditDate }}</div>
                <p-date-picker v-model="form.loadingAuditDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" style="width: 100%" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="分组名称" prop="groupName">
                <div v-if="editType === 'view'">{{ form.groupName }}</div>
                <p-input v-model="form.groupName" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="配送线路" prop="deliveryLines">
                <div v-if="editType === 'view'">{{ form.deliveryLines }}</div>
                <p-input v-model="form.deliveryLines" v-else />
              </p-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="站点线路" prop="stationLines">
                <div v-if="editType === 'view'">{{ form.stationLines }}</div>
                <p-input v-model="form.stationLines" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="收入公里数" prop="totalMileage">
                <div v-if="editType === 'view'">{{ form.totalMileage }}</div>
                <p-input-number v-model="form.totalMileage" :min="0" style="width: 100%" v-else />
              </p-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="提货区域" prop="pickUpAreas">
                <div v-if="editType === 'view'">{{ form.pickUpAreas }}</div>
                <p-select v-model="form.pickUpAreas" :options="options.STATION_AREAS" allowClear v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="配送区域" prop="deliveryAreas">
                <div v-if="editType === 'view'">{{ form.deliveryAreas }}</div>
                <p-select v-model="form.deliveryAreas" :options="options.STATION_AREAS" allowClear v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="收入总件数" prop="totalPcs">
                <div v-if="editType === 'view'">{{ form.totalPcs }}</div>
                <p-input-number v-model="form.totalPcs" :min="0" style="width: 100%" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="收入总重量(kg)" prop="totalWeight">
                <div v-if="editType === 'view'">{{ form.totalWeight }}</div>
                <p-input-number v-model="form.totalWeight" :min="0" style="width: 100%" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="收入体积(m³)" prop="totalVolume">
                <div v-if="editType === 'view'">{{ form.totalVolume }}</div>
                <p-input-number v-model="form.totalVolume" :min="0" style="width: 100%" v-else />
              </p-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="备注" prop="memo">
                <div v-if="editType === 'view'">{{ form.memo }}</div>
                <p-input v-model="form.memo" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="承运方类型">
                <div>司机</div>
              </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)" @input="onFormInput('driver')" v-else />
                <!-- :targetClick="false" -->
              </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)" @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)" @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="车辆类别">{{ form.vehicleTypeCategoryName }}</p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="车辆规格">{{ form.vehicleSpec }}</p-form-model-item>
            </a-col>
          </a-row>
        </p-form-model>
        <a-divider orientation="left">运单信息</a-divider>
        <p-table
          ref="detailsTable"
          dragle
          bordered
          row-key="id"
          :id="$route.meta.menuId + '_detailsTable'"
          :scroll="{ x: true, y: 300 }"
          :columns="details_columns"
          :data-source.sync="detailsDataSource"
          :remote-url="detailsListRemoteUrl"
          :remoteData="detailsListParams"
          :rowSelectType="false"
          :autoLoad="false"
          :pagination="false"
        >
        </p-table>
      </p-card>
    </p-spin>

    <orderView
      v-show="detailsType === 'detailsView'"
      :st="1"
      :record="detailsData"
      :formExtendedField="formExtendedField"
      :goodsExtendedField="childrenFormExtendedField"
      @back="detailsType = ''"
    ></orderView>
  </div>
</template>

<script>
import * as $formItems from '@/blocks/components/searchModalConfig/index';
import departmenTree from '@/blocks/components/formConfig/index.departmenTree.vue';
import orderView from '@/views/BMS/$common/model/orderView/index.orderView.vue';

import { View, Update, detailsListRemoteUrl } from '../js/api.js';
import { setDetailsColumns } from '../js/tableConfig.js';

export default {
  components: { departmenTree, orderView },
  props: {
    editType: {
      type: String,
      default: '',
    },
    editData: {
      type: Object,
      default: () => ({}),
    },
    options: {
      type: Object,
      default: () => ({}),
    },
    formExtendedField: {
      type: Array,
      default: [],
    },
    childrenFormExtendedField: {
      type: Array,
      default: [],
    },
  },
  computed: {
    typeTitle() {
      const dictionary = {
        add: '新增',
        edit: '编辑',
        view: '查看',
        copy: '复制',
      };
      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;
    },
  },
  data() {
    return {
      $formItems,
      spinning: false,
      detailsType: '',
      detailsData: null,

      form: {
        driverId: '',
        driverCode: '',
        driverName: '',
        driverPhoneNumber: '',
        deliverymanId: '',
        deliverymanCode: '',
        deliverymanName: '',
        deliverymanPhoneNumber: '',
        vehicleId: '',
        vehicleCode: '',
        vehiclePlateNumber: '',
        vehicleTypeCode: '',
        vehicleTypeName: '',
      },
      rules: {
        expenseCode: [{ required: true, message: '费用科目编码不能为空', trigger: 'blur' }],
        expenseName: [{ required: true, message: '费用科目名称不能为空', trigger: 'blur' }],
        expenseClassify: [{ required: true, message: '费用类型不能为空', trigger: 'change' }],
      },

      departmentCode: '', // 部门code
      disAffiliation: false,

      // 运单表格
      detailsDataSource: [],
      detailsListRemoteUrl,
      detailsListParams: {},
      details_columns: setDetailsColumns(this),
    };
  },
  mounted() {
    this.View();
  },
  methods: {
    back() {
      this.$emit('back');
    },

    // 保存
    onSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return;
        this.onMethod(Update);
        return;
      });
    },
    onMethod(method) {
      let params = { ...this.form };

      this.spinning = true;
      method(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 === 'consignor') {
        this.$set(this.form, 'cargoOwnerId', args[1] ? args[2][0].cargoOwnerId : '');
        this.$set(this.form, 'cargoOwnerCode', args[1] ? args[2][0].cargoOwnerCode : '');
        this.$set(this.form, 'cargoOwnerName', args[1] ? args[2][0].cargoOwnerName : '');
      } else 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.vehicleSpec = args[2][0].vehicleSpec;
          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.vehicleSpec = args[2][0].vehicleSpec;
        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;
      }
    },
    getDepartment(value) {
      this.departmentCode = value.departmentCode;
      this.form.settlementDepartmentId = value.departmentId;
      this.form.settlementDepartmentCode = value.departmentCode;
      this.form.settlementDepartment = value.departmentName;
    },

    // 查询
    View() {
      this.detailsListParams = { id: this.editData.id };
      View({ id: this.editData.id }).then((res) => {
        this.form = { ...res.data };
        this.departmentCode = this.form.settlementDepartmentCode;
      });
    },

    // 明细查看
    onDetailsView(record) {
      this.detailsId = record;
      this.detailsType = 'detailsView';
    },
  },
};
</script>
<style>
</style>