<!--
@name: 承运商匹配策略-编辑页
@author: 张泽贤
@time: 2022-10-08
@doc:
-->
<template>
  <p-spin :spinning="spinning">
    <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="type !== 'view'">
        <p-button type="primary" @click="onSave">保存</p-button>
      </div>
    </p-card>
    <p-card>
      <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="configName">
              <div v-if="type === 'view'">{{ form.configName }}</div>
              <p-input v-model="form.configName" :disabled="type === 'edit'" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="12">
            <p-form-model-item label="备注" prop="memo" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
              <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">满足条件</a-divider>
        <p-button type="primary" v-if="type !== 'view'" @clickSync="onAddBtn">新增</p-button>
        <a-row v-for="(item, index) in configCtSaveVOList" :key="index">
          <a-col :span="6">
            <p-form-model-item label="" prop="configConditionType" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-select v-model="item.configConditionType" :options="STRATEGY_CONDITION_TYPE" allowClear @change="(value) => configConditionTypeChange(value, item)" :disabled="type === 'view'" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="item.configConditionType !== 8 && item.configConditionType !== 9">
            <p-form-model-item label="" prop="configConditionValue" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-select v-model="item.configConditionValue" :options="configConditionValueEnums[item.configConditionType]" allowClear :disabled="type === 'view'" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="(item.configConditionType === 2 || item.configConditionType === 3) && item.configConditionValue === 1">
            <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-search-modal v-model="item.unitName" v-bind="customerAttr" @change="(...args) => onConfigFormChange('customer', item, ...args)" :disabled="type === 'view'" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="(item.configConditionType === 2 || item.configConditionType === 3) && item.configConditionValue === 2">
            <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-search-modal v-model="item.unitName" v-bind="branchAttr" @change="(...args) => onConfigFormChange('branch', item, ...args)" :disabled="type === 'view'" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="(item.configConditionType === 2 || item.configConditionType === 3) && item.configConditionValue === 3">
            <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-search-modal v-model="item.unitName" v-bind="supplierAttr" @change="(...args) => onConfigFormChange('supplier', item, ...args)" :disabled="type === 'view'" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="item.configConditionType === 8">
            <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-search-modal v-model="item.unitName" v-bind="$data.$formItems.consignorAttr" @change="(...args) => onConfigFormChange('consignor', item, ...args)" :disabled="type === 'view'" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="item.configConditionType === 9">
            <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <departmenTree :departmentId="departmentId" @getDepartment="(value) => getDepartment(value, item)" :disabled="type === 'view'"></departmenTree>
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="item.configConditionType === 10 || item.configConditionType === 11">
            <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-select v-model="item.unitName" :options="options.TIME_FREQUENCY_VALUE" mode="multiple" allowClear :disabled="type === 'view'" />
            </p-form-model-item>
          </a-col>
          <a-col :span="2">
            <p-form-model-item style="text-align: right">
              <a-space>
                <p-button type="danger" v-if="type !== 'view'" @click="onDelBtn(index)">删除</p-button>
              </a-space>
            </p-form-model-item>
          </a-col>
        </a-row>

        <a-divider orientation="left">承运方信息</a-divider>
        <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" @change="carrierTypeChange" v-else />
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row v-show="form.carrierType === 2">
          <a-col :span="6">
            <p-form-model-item label="司机" prop="driverName">
              <div v-if="type === 'view'">{{ form.driverName }}</div>
              <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">
              <div v-if="type === 'view'">{{ form.driverPhoneNumber }}</div>
              <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">
              <div v-if="type === 'view'">{{ form.deliverymanName }}</div>
              <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">
              <div v-if="type === 'view'">{{ form.deliverymanPhoneNumber }}</div>
              <p-input v-model="form.deliverymanPhoneNumber" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="车辆" prop="vehiclePlateNumber">
              <div v-if="type === 'view'">{{ form.vehiclePlateNumber }}</div>
              <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-row>
        <a-row v-show="form.carrierType === 1">
          <a-col :span="6">
            <p-form-model-item label="承运商编码" prop="carrierCode">
              <div v-if="type === 'view'">{{ form.carrierCode }}</div>
              <p-search-modal v-model="form.carrierCode" v-bind="$data.$formItems.carrierAttr" @change="(...args) => onFormChange('carrier', ...args)" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="承运商名称">{{ form.carrierName }}</p-form-model-item>
          </a-col>
        </a-row>
      </p-form-model>
    </p-card>
  </p-spin>
</template>

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

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

export default {
  components: { departmenTree },
  props: {
    type: {
      type: String,
      default: '',
    },
    editId: {
      type: String,
      default: '',
    },
    options: {
      type: Object,
      default: () => ({}),
    },
  },
  computed: {
    typeTitle() {
      const dictionary = {
        add: '新增',
        edit: '编辑',
        view: '查看',
        copy: '复制',
      };
      return dictionary[this.type] || this.type;
    },
    customerAttr() {
      let customerAttr = $formItems.customerAttr;
      customerAttr.tableConfig.rowSelectType = 2;
      return customerAttr;
    },
    branchAttr() {
      let branchAttr = $formItems.branchAttr;
      branchAttr.tableConfig.rowSelectType = 2;
      return branchAttr;
    },
    supplierAttr() {
      let supplierAttr = $formItems.supplierNoConsignorAttr;
      supplierAttr.tableConfig.rowSelectType = 2;
      return supplierAttr;
    },

    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);
    },
  },
  data() {
    return {
      $formItems,
      spinning: false,

      form: {
        carrierType: '',
        driverId: '',
        driverCode: '',
        driverName: '',
        driverPhoneNumber: '',
        deliverymanId: '',
        deliverymanCode: '',
        deliverymanName: '',
        deliverymanPhoneNumber: '',
        vehicleId: '',
        vehicleCode: '',
        vehiclePlateNumber: '',
        vehicleTypeCode: '',
        vehicleTypeName: '',
        vehicleTypeId: '',
        carrierId: '',
        carrierCode: '',
        carrierName: '',
        weight: '',
        volume: '',
      },
      rules: {
        configName: [{ required: true, message: '策略名称不能为空', trigger: 'blur' }],
      },

      configCtSaveVOList: [],
      configConditionValueEnums: {
        1: this.options.DELIVERY_METHOD_TYPE, // 配送方式
        2: this.options.SHIPPER_TYPE,
        3: this.options.CONSIGNEE_TYPE,
        4: this.options.ORDER_TYPE,
        5: this.options.ORDER_BUSINESS_TYPE,
        6: this.options.TRANSPORT_TYPE,
        7: this.options.TEMPERATURE_REQUIREMENT,
        8: [],
        10: this.options.TIME_FREQUENCY_KEY,
        11: this.options.TIME_FREQUENCY_KEY,
        12: this.options.SOURCE,
      },
      STRATEGY_CONDITION_TYPE: [],
      departmentId: '', // 部门code
    };
  },
  mounted() {
    this.STRATEGY_CONDITION_TYPE = this.options.STRATEGY_CONDITION_TYPE.map((item) => {
      item.disabled = false;
      return item;
    });
    if (this.editId) {
      this.spinning = true;
      View({ id: this.editId })
        .then((res) => {
          if (res.success) {
            this.form = { ...res.data };
            this.configCtSaveVOList = res.data.carrierConfigCtViewDTOList.map((item) => {
              let result = { ...item };
              if (result.configConditionType === 10 || result.configConditionType === 11) {
                result.unitName = result.unitName.split(',').map((value) => Number(value));
              }
              return result;
            });
            delete this.form.carrierConfigCtViewDTOList;
            this.STRATEGY_CONDITION_TYPE_INIT();

            // 处理部门渲染
            this.$nextTick(() => {
              this.departmentId = this.configCtSaveVOList.find((item) => item.configConditionType === 9)?.unitId;
            });
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    }
  },
  methods: {
    back() {
      this.$emit('back');
    },

    // 保存
    onSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return;
        let configCtSaveVOList = [];
        for (let index = 0; index < this.configCtSaveVOList.length; index++) {
          const element = { ...this.configCtSaveVOList[index] };
          if ([10, 11].includes(element.configConditionType) && !element.unitName.length) {
            this.$message.error('时间频率类型不能为空');
            return false;
          }
          if ([10, 11].includes(element.configConditionType)) {
            element.unitName = element.unitName.join(',');
          }
          configCtSaveVOList.push(element);
        }

        if (this.type === 'add' || this.type === 'copy') {
          let params = { ...this.form, configCtSaveVOList: configCtSaveVOList };
          this.onMethod(Save, params);
        }
        if (this.type === 'edit') {
          let params = { ...this.form, configCtUpdateVOList: configCtSaveVOList };
          this.onMethod(Update, params);
        }

        return;
      });
    },
    onMethod(method, params) {
      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;
        });
    },

    onConfigFormChange(name, item, ...args) {
      if (!args[1]) {
        this.$set(item, 'unitId', '');
        this.$set(item, 'unitCode', '');
        this.$set(item, 'unitName', '');
        return;
      }
      if (name === 'consignor') {
        this.$set(item, 'unitId', args[2][0].cargoOwnerId);
        this.$set(item, 'unitCode', args[2][0].cargoOwnerCode);
        this.$set(item, 'unitName', args[2][0].cargoOwnerName);
      } else {
        let idList = [],
          codeList = [];
        args[2].forEach((item) => {
          idList.push(item.id);
          codeList.push(item.code);
        });
        this.$set(item, 'unitId', idList.join(','));
        this.$set(item, 'unitCode', codeList.join(','));
        this.$set(item, 'unitName', args[1]);
      }
    },

    onAddBtn() {
      this.configCtSaveVOList.push({
        configConditionType: '',
        configConditionValue: '',
        configConditionValueEnums: [],
        unitId: '',
        unitCode: '',
        unitName: '',
      });
    },
    onDelBtn(index) {
      this.configCtSaveVOList.splice(index, 1);
      this.STRATEGY_CONDITION_TYPE_INIT();
    },

    configConditionTypeChange(value, item) {
      if (value == 10 || value == 11) {
        item.configConditionValue = 1;
        item.unitName = [];
      } else {
        item.configConditionValue = '';
        item.unitId = '';
        item.unitCode = '';
        item.unitName = '';
      }

      this.STRATEGY_CONDITION_TYPE_INIT();
    },

    // 更新STRATEGY_CONDITION_TYPE
    STRATEGY_CONDITION_TYPE_INIT() {
      let selectList = this.configCtSaveVOList.map((item) => item.configConditionType);
      this.STRATEGY_CONDITION_TYPE.forEach((item) => {
        if (selectList.includes(item.value)) {
          item.disabled = true;
        } else {
          item.disabled = false;
        }
      });
    },

    // 部门change
    getDepartment(value, item) {
      this.departmentId = value.departmentId;
      item.unitId = value.departmentId;
      item.unitCode = value.departmentCode;
      item.unitName = value.departmentName;
    },

    // 承运方类型
    carrierTypeChange() {
      this.form.driverId = '';
      this.form.driverCode = '';
      this.form.driverName = '';
      this.form.driverPhoneNumber = '';
      this.form.deliverymanId = '';
      this.form.deliverymanCode = '';
      this.form.deliverymanName = '';
      this.form.deliverymanPhoneNumber = '';
      this.form.vehicleId = '';
      this.form.vehicleCode = '';
      this.form.vehiclePlateNumber = '';
      this.form.vehicleTypeCode = '';
      this.form.vehicleTypeName = '';
      this.form.vehicleTypeId = '';

      this.form.carrierId = '';
      this.form.carrierCode = '';
      this.form.carrierName = '';
    },

    onFormChange(name, ...args) {
      let idList = [],
        codeList = [],
        phoneList = [];
      args[2].forEach((item) => {
        idList.push(item.id);
        codeList.push(item.code);
        if (name === 'driver' || name === 'delivery') phoneList.push(item.phoneNumber);
      });
      if (name === 'driver') {
        this.form.driverId = idList.join(',');
        this.form.driverCode = codeList.join(',');
        this.form.driverName = args[1];
        this.form.driverPhoneNumber = phoneList.join(',');
        // 如果只有一辆车，默认选中
        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.vehicleTypeId = args[2][0].vehicleTypeId;
          this.form.weight = args[2][0].weight;
          this.form.volume = args[2][0].volume;
        }
      } 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.vehicleTypeId = args[2][0].vehicleTypeId;
        //         this.form.vehicleTypeId
        //         vehicleTypeCode: "6.2"
        //       vehicleTypeId: "10000043"
        // vehicleTypeName: "6.2"

        this.form.weight = args[2][0].weight;
        this.form.volume = args[2][0].volume;
      } else if (name === 'carrier') {
        this.form.carrierId = args[2][0].id;
        this.form.carrierCode = args[2][0].code;
        this.form.carrierName = args[2][0].name;
      }
    },
    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.vehicleTypeId = '';
      }
    },
  },
};
</script>

<style lang="less" scoped>
.border {
  border: 1px solid #e8e8e8;
}
</style>