<!--
@name: 线路管理-编辑
@author: 张泽贤
@time: 2022-10-10
@doc: PROLOG_UPCloudSolutionForTMS__v1.2.1_PC+小程序优化版本_1.3.9_v3.doc
-->
<template>
  <div style="height: 100%">
    <p-card class="full-card-panel" v-show="!mapType">
      <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="type !== 'view'">
        <p-button :disabled="spinning" type="primary" @click="onSave">保存</p-button>
      </div>
      <p-spin :spinning="spinning">
        <p-form-model ref="ruleForm" class="plg-grid-from" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" :rules="rules">
          <a-divider orientation="left">基本信息</a-divider>
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="线路编码" prop="lineCode">
                <div v-if="type === 'view'">{{ form.lineCode }}</div>
                <p-input v-model="form.lineCode" :disabled="type === 'edit'" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="线路名称" prop="lineName">
                <div v-if="type === 'view'">{{ form.lineName }}</div>
                <p-input v-model="form.lineName" :disabled="type === 'edit'" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="线路类型" prop="lineType">
                <div v-if="type === 'view'">{{ form.lineTypeName }}</div>
                <p-select v-model="form.lineType" :options="options.LINE_TYPE" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="部门" prop="departmentName">
                <div v-if="type === 'view'">{{ form.departmentName }}</div>
                <departmenTree :departmentId="form.departmentId" @getDepartment="getDepartment" v-else></departmenTree>
              </p-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="线路起点类型" prop="startLineType">
                <div v-if="type === 'view'">{{ form.startLineTypeName }}</div>
                <p-select v-model="form.startLineType" :options="options.START_LINE_TYPE" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="线路终点" prop="endLineName">
                <div v-if="type === 'view'">{{ form.endLineName }}</div>
                <p-search-modal v-model="form.endLineName" v-bind="$data.$formItems.branchAttr" @change="(...args) => onFormChange('endLine', ...args)" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="划分类型" prop="distinguishType">
                <div v-if="type === 'view'">{{ form.distinguishTypeName }}</div>
                <p-select v-model="form.distinguishType" :options="options.DISTINGUISH_TYPE" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="总里程数" prop="totalMileage">
                <div v-if="type === 'view'">{{ form.totalMileage }}</div>
                <p-input v-model="form.totalMileage" disabled v-else />
              </p-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="承运方类型" prop="carrierType">
                <div v-if="type === 'view'">{{ form.carrierTypeName }}</div>
                <p-select v-model="form.carrierType" :options="options.LINE_CARRIER_TYPE" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="4" :offset="2">
              <p-form-model-item label="" prop="limit">
                <p-checkbox v-model="form.limit" :readOnly="type === 'view'">是否承运方份额限制</p-checkbox>
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="限制依据" prop="basis">
                <div v-if="type === 'view'">{{ form.basisName }}</div>
                <p-select v-model="form.basis" :options="options.LINE_BASIS" allowClear v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="方向" prop="lineDirection">
                <div v-if="type === 'view'">{{ form.lineDirectionName }}</div>
                <p-select v-model="form.lineDirection" :options="options.LINE_DIRECTION" 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="type === 'view'">{{ form.memo }}</div>
                <p-input v-model="form.memo" v-else />
              </p-form-model-item>
            </a-col>
          </a-row>
          <a-divider orientation="left" v-if="mextendedField_list.length">扩展属性</a-divider>
          <extendedField :mextendedField_list="mextendedField_list" :type="type" :form="form"></extendedField>
        </p-form-model>

        <tabsEdit ref="tabsEdit" :type="type" :editData="form" :options="options" :newMapDataList="siteDTOs" style="margin-top: 20px" @onMap="onMap"></tabsEdit>
      </p-spin>
    </p-card>
    <!-- 线路地图 -->
    <lineMap v-show="mapType" :type="type" :distinguishType="form.distinguishType" :waypoint_dataSource="waypoint_dataSource" @mapBack="mapBack"></lineMap>
  </div>
</template>

<script>
import * as $formItems from '@/blocks/components/searchModalConfig/index';
import departmenTree from '@/blocks/components/formConfig/index.departmenTree.multiple.vue';
import extendedField from '@/blocks/extendedField/index.vue';

import tabsEdit from './tabsEdit.vue';
import lineMap from './lineMap.vue';
import { View, Save, Update } from '../js/api.js';

export default {
  components: { departmenTree, extendedField, tabsEdit, lineMap },
  props: {
    type: {
      type: String,
      default: '',
    },
    editId: {
      type: String,
      default: '',
    },
    options: {
      type: Object,
      default: () => ({}),
    },
    mextendedField_list: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    typeTitle() {
      const dictionary = {
        add: '新增',
        edit: '编辑',
        view: '查看',
        copy: '复制',
      };
      return dictionary[this.type] || this.type;
    },
  },
  data() {
    return {
      spinning: false,
      $formItems,
      mapType: false,

      form: {
        startLineType: 1,
        distinguishType: 1,
        carrierType: 1,
        limit: false,
      },
      rules: {
        lineCode: [{ required: true, message: '线路编码不能为空', trigger: 'blur' }],
        lineName: [{ required: true, message: '线路名称不能为空', trigger: 'blur' }],
        lineType: [{ required: true, message: '线路类型不能为空', trigger: 'change' }],
        departmentName: [{ required: true, message: '部门不能为空', trigger: 'change' }],
        distinguishType: [{ required: true, message: '划分类型不能为空', trigger: 'change' }],
        startLineType: [{ required: true, message: '线路起点类型不能为空', trigger: 'change' }],
        lineDirection: [{ required: true, message: '方向不能为空', trigger: 'change' }],
      },

      waypoint_dataSource: [],
      siteDTOs: [],
    };
  },
  mounted() {
    if (this.editId) {
      this.spinning = true;
      View({ lineId: this.editId })
        .then((res) => {
          res.data.limit = res.data.limit === 1;
          this.form = { ...res.data };
        })
        .finally(() => {
          this.spinning = false;
        });
    }
  },
  methods: {
    back() {
      this.$emit('back');
    },

    // 部门
    getDepartment(value) {
      this.form.departmentId = value.departmentId;
      this.form.departmentCode = value.departmentCode;
      this.form.departmentName = value.departmentName;
    },

    onFormChange(name, ...args) {
      if (name === 'endLine') {
        this.$set(this.form, 'endLineId', args[1] ? args[2][0].id : '');
        this.$set(this.form, 'endLineCode', args[1] ? args[2][0].code : '');
        this.$set(this.form, 'endLineName', args[1] ? args[2][0].name : '');
      }
    },

    onMap(list) {
      this.waypoint_dataSource = list;
      this.mapType = true;
    },
    mapBack(data) {
      this.form.totalMileage = data.totalMileage || '';
      this.siteDTOs = data.siteDTOs;
      this.mapType = false;
    },

    // 保存
    onSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return;
        if (this.type === 'add') this.onMethod(Save);
        if (this.type === 'edit') this.onMethod(Update);

        return;
      });
    },
    onMethod(method) {
      let params = { ...this.form };
      params.limit = params.limit ? 1 : 0;

      let tabsEditData = this.$refs.tabsEdit;

      // 发货方
      if (params.startLineType === 1) {
        // 仓库
        params.tmsShipperVOS = tabsEditData.shipper_assignedList.map((item) => {
          let fdata = tabsEditData.waypoint_dataSource.find((item2) => item.code === item2.siteCode);
          return {
            branchCode: item.code,
            branchId: item.id,
            branchName: item.name,
            lineId: item.lineId,
            pickupOrder: item.pickupOrder,
            longitude: item.longitude,
            latitude: item.latitude,
            shipperAgingTime: fdata?.shipperAgingTime || '',
            shipperAgingTimeLine: fdata?.shipperAgingTimeLine || '',
          };
        });
        params.shipperAdministrativeAreas = [];
      } else {
        // 区域
        params.tmsShipperVOS = [];
        this.siteDTOs.forEach((item) => {
          if (item.siteTypeName === '提货') {
            params.tmsShipperVOS.push({
              lineId: this.form.lindId,
              branchCode: item.siteCode,
              branchName: item.siteName,
              shipperAddress: item.address,
              pickupOrder: item.siteOrder,
            });
          }
        });
        params.shipperAdministrativeAreas = tabsEditData.shipper_checkedKeys;
      }

      // 收货方
      if (params.distinguishType === 1) {
        // 客户-收货方
        params.tmsArriverVOS = tabsEditData.consignee_assignedList.map((item) => {
          let fdata = tabsEditData.waypoint_dataSource.find((item2) => item.code === item2.siteCode);
          return {
            consigneeAddress: item.address,
            consigneeCode: item.code,
            consigneeContact: item.contact,
            consigneeId: item.id,
            consigneeMemo: item.memo,
            consigneeName: item.name,
            consigneePhoneNumber: item.phoneNumber,
            customerCode: item.customerCode,
            customerId: item.customerId,
            customerName: item.customerName,
            deliveryOrder: item.deliveryOrder,
            enterpriseId: item.enterpriseId,
            lineId: item.lineId,
            longitude: item.longitude,
            latitude: item.latitude,
            consigneeAgingTime: fdata?.consigneeAgingTime || '',
            consigneeAgingTimeLine: fdata?.consigneeAgingTimeLine || '',
          };
        });
        params.administrativeAreas = [];
      } else {
        // 区域
        params.tmsArriverVOS = [];
        this.siteDTOs.forEach((item) => {
          if (item.siteTypeName === '送货') {
            params.tmsArriverVOS.push({
              lineId: this.form.lindId,
              consigneeCode: item.siteCode,
              consigneeName: item.siteName,
              consigneeAddress: item.address,
              deliveryOrder: item.siteOrder,
            });
          }
        });
        params.administrativeAreas = tabsEditData.consignee_checkedKeys;
      }

      // 承运方
      params.tmsCarrierVOS = tabsEditData.carrier_dataSource;

      // 线路可用日期
      params.week = tabsEditData.weekList
        .map((item) => {
          return item.value + ':' + (tabsEditData.selectWeek.includes(item.value) ? 1 : 0);
        })
        .join(',');
      params.day = tabsEditData.dayList
        .map((item) => {
          return 'day_' + item + ':' + (tabsEditData.selectDay.includes(item) ? 1 : 0);
        })
        .join(',');

      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;
        });
    },
  },
};
</script>