<!--
@name: 中转策略-编辑页
@author: 张泽贤
@time: 2022-06-13
@doc: PROLOG_UPCloudSolutionForTMS__v1.2.1_基础配置_1.2.2
-->
<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>
      <div slot="extra" v-show="type !== 'view'">
        <p-button type="primary" @click="onSave">保存</p-button>
      </div>
    </p-card>
    <p-card>
      <div>
        <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" prop="name">
              <p-form-model-item label="策略名称" prop="name">
                <div v-if="type === 'view'">{{ form.name }}</div>
                <p-input v-model="form.name" :disabled="type === 'edit'" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="12" prop="memo">
              <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-row>
            <a-col :span="4">
              <p-form-model-item label="" prop="rematchLine">
                <p-checkbox v-model="form.rematchLine" :readOnly="type === 'view'">中转后重新匹配线路</p-checkbox>
              </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="收货方类型">客户</p-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="收货方单位" prop="consigneeUnitName">
                <div v-if="type === 'view'">{{ form.consigneeUnitName }}</div>
                <p-search-modal v-model="form.consigneeUnitName" v-bind="$data.$formItems.customerAttr" @change="(...args) => onFormChange('consigneeUnit', ...args)" v-else />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="收货方" prop="consigneeName">
                <div v-if="type === 'view'">{{ form.consigneeName }}</div>
                <p-search-modal
                  v-model="form.consigneeName"
                  v-bind="$data.$formItems.consigneeAttr"
                  @change="(...args) => onFormChange('consignee', ...args)"
                  :disabled="!form.consigneeUnitName"
                  v-else
                  :remoteBefore="
                    (vNode, remoteUrl) => {
                      remoteUrl.data = { customerId: form.consigneeUnitId, ...remoteUrl.data };
                    }
                  "
                />
              </p-form-model-item>
            </a-col>
          </a-row>

          <a-divider orientation="left">中转顺序</a-divider>
          <p-button type="primary" icon="plus" @click="onAdd" v-show="type !== 'view'">新增</p-button>
          <div v-for="(item, index) in formList" :key="index">
            <a-row>
              <a-col :span="6">
                <p-form-model-item label="中转站" prop="transferStationName">
                  <div v-if="type === 'view'">{{ item.transferStationName }}</div>
                  <p-search-modal v-model="item.transferStationName" v-bind="$data.$formItems.transferAttr" @change="(...args) => onTableChange('transfer', index, ...args)" v-else />
                </p-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="6">
                <p-form-model-item label="预计到达时间">
                  <div v-if="type === 'view'">{{ item.deliveryStartTimeTypeName }}</div>
                  <p-select v-model="item.deliveryStartTimeType" :options="options.TRANSFER_TIME_TYPE" allowClear v-else />
                </p-form-model-item>
              </a-col>
              <a-col :span="3">
                <p-form-model-item :wrapper-col="{ span: 24 }">
                  <div v-if="type === 'view'">{{ item.deliveryStartTime }}</div>
                  <p-time-picker v-model="item.deliveryStartTime" :default-open-value="moment('00:00', 'HH:mm')" valueFormat="HH:mm" format="HH:mm" style="width: 100%" @change="timeChange" v-else />
                </p-form-model-item>
              </a-col>
              <a-col :span="1">
                <p-form-model-item :wrapper-col="{ span: 24 }" style="text-align: center">------</p-form-model-item>
              </a-col>
              <a-col :span="3">
                <p-form-model-item :wrapper-col="{ span: 24 }">
                  <div v-if="type === 'view'">{{ item.deliveryEndTimeTypeName }}</div>
                  <p-select v-model="item.deliveryEndTimeType" :options="options.TRANSFER_TIME_TYPE" allowClear v-else />
                </p-form-model-item>
              </a-col>
              <a-col :span="1">
                <p-form-model-item :wrapper-col="{ span: 24 }" style="text-align: center">+</p-form-model-item>
              </a-col>
              <a-col :span="3">
                <p-form-model-item :wrapper-col="{ span: 24 }">
                  <div v-if="type === 'view'">{{ item.deliveryEndTimeDay }}天</div>
                  <a-input-number v-model="item.deliveryEndTimeDay" :step="1" :formatter="(value) => `${value}天`" :parser="(value) => value.replace('天', '')" style="width: 100%" v-else />
                </p-form-model-item>
              </a-col>
              <a-col :span="3">
                <p-form-model-item :wrapper-col="{ span: 24 }">
                  <div v-if="type === 'view'">{{ item.deliveryEndTime }}</div>
                  <p-time-picker v-model="item.deliveryEndTime" :default-open-value="moment('00:00', 'HH:mm')" valueFormat="HH:mm" format="HH:mm" style="width: 100%" @change="timeChange" v-else />
                </p-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="6">
                <p-form-model-item label="预计发出时间">
                  <div v-if="type === 'view'">{{ item.sendStartTimeTypeName }}</div>
                  <p-select v-model="item.sendStartTimeType" :options="options.TRANSFER_TIME_TYPE" allowClear v-else />
                </p-form-model-item>
              </a-col>
              <a-col :span="3">
                <p-form-model-item :wrapper-col="{ span: 24 }">
                  <div v-if="type === 'view'">{{ item.sendStartTime }}</div>
                  <p-time-picker v-model="item.sendStartTime" :default-open-value="moment('00:00', 'HH:mm')" valueFormat="HH:mm" format="HH:mm" style="width: 100%" @change="timeChange" v-else />
                </p-form-model-item>
              </a-col>
              <a-col :span="1">
                <p-form-model-item :wrapper-col="{ span: 24 }" style="text-align: center">------</p-form-model-item>
              </a-col>
              <a-col :span="3">
                <p-form-model-item :wrapper-col="{ span: 24 }">
                  <div v-if="type === 'view'">{{ item.sendEndTimeTypeName }}</div>
                  <p-select v-model="item.sendEndTimeType" :options="options.TRANSFER_TIME_TYPE" allowClear v-else />
                </p-form-model-item>
              </a-col>
              <a-col :span="1">
                <p-form-model-item :wrapper-col="{ span: 24 }" style="text-align: center">+</p-form-model-item>
              </a-col>
              <a-col :span="3">
                <p-form-model-item :wrapper-col="{ span: 24 }">
                  <div v-if="type === 'view'">{{ item.sendEndTimeDay }}天</div>
                  <a-input-number v-model="item.sendEndTimeDay" :step="1" :formatter="(value) => `${value}天`" :parser="(value) => value.replace('天', '')" style="width: 100%" v-else />
                </p-form-model-item>
              </a-col>
              <a-col :span="3">
                <p-form-model-item :wrapper-col="{ span: 24 }">
                  <div v-if="type === 'view'">{{ item.sendEndTime }}</div>
                  <p-time-picker v-model="item.sendEndTime" :default-open-value="moment('00:00', 'HH:mm')" valueFormat="HH:mm" format="HH:mm" style="width: 100%" @change="timeChange" v-else />
                </p-form-model-item>
              </a-col>
              <a-col :span="4" v-show="type !== 'view'">
                <p-form-model-item :wrapper-col="{ span: 24 }" style="text-align: right">
                  <a-space>
                    <p-button type="danger" @click="onDel(index)">删除</p-button>
                  </a-space>
                </p-form-model-item>
              </a-col>
            </a-row>
            <a-divider />
          </div>
        </p-form-model>
      </div>
    </p-card>
  </p-spin>
</template>

<script>
import * as $formItems from '@/blocks/components/searchModalConfig/index';
import { Add, Update, View } from '../js/api';

export default {
  props: {
    type: '',
    editId: {
      type: String,
      default: '',
    },
    options: {
      type: Object,
      default: () => ({}),
    },
  },
  computed: {
    typeTitle() {
      const dictionary = {
        add: '新增',
        edit: '编辑',
        view: '查看',
      };
      return dictionary[this.type] || this.type;
    },
  },
  data() {
    return {
      $formItems,
      spinning: false,
      form: {
        name: '',
        memo: '',
        rematchLine: false,
        consigneeUnitId: '',
        consigneeUnitCode: '',
        consigneeUnitName: '',
        consigneeId: '',
        consigneeCode: '',
        consigneeName: '',
      },
      rules: {
        name: [{ required: true, message: '策略名称不能为空', trigger: 'blur' }],
      },

      formList: [],
    };
  },
  mounted() {
    if (this.editId) {
      this.spinning = true;
      View({ id: this.editId })
        .then((res) => {
          if (res.success) {
            res.data.rematchLine = res.data.rematchLine == 1;
            this.form = { ...res.data };
            res.data.transferStationViewDTOS.forEach((item) => {
              item.deliveryStartTime = item.deliveryStartTimeHour.toString().padStart(2, 0) + ':' + item.deliveryStartTimeMinute.toString().padStart(2, 0);
              item.deliveryEndTime = item.deliveryEndTimeHour.toString().padStart(2, 0) + ':' + item.deliveryEndTimeMinute.toString().padStart(2, 0);
              item.sendStartTime = item.sendStartTimeHour.toString().padStart(2, 0) + ':' + item.sendStartTimeMinute.toString().padStart(2, 0);
              item.sendEndTime = item.sendEndTimeDayHour.toString().padStart(2, 0) + ':' + item.sendEndTimeDayMinute.toString().padStart(2, 0);
              this.formList.push(item);
            });
            delete this.form.transferStationViewDTOS;
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    }
  },
  methods: {
    back() {
      this.$emit('back');
    },
    // 新增
    onAdd() {
      this.formList.push({
        id: '',
        code: '',
        name: '',
        deliveryStartTime: '00:00',
        deliveryEndTime: '00:00',
        sendStartTime: '00:00',
        sendEndTime: '00:00',
      });
    },
    // 删除
    onDel(index) {
      this.formList.splice(index, 1);
    },
    // 保存
    onSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return;
        if (this.type === 'add') this.onMethod(Add);
        if (this.type === 'edit') this.onMethod(Update);

        return;
      });
    },
    onMethod(method) {
      let params = { ...this.form };
      params.rematchLine = params.rematchLine ? 1 : 0;
      let VOS = [];
      for (let index = 0; index < this.formList.length; index++) {
        const item = this.formList[index];
        if (!item.transferStationId && item.transferStationId !== 0) {
          this.$message.error('第' + (index + 1) + '行中转站不能为空');
          return false;
        }
        if (!item.deliveryStartTimeType && item.deliveryStartTimeType !== 0) {
          this.$message.error('第' + (index + 1) + '行预计到达开始时间类型不能为空');
          return false;
        }
        if (!item.deliveryEndTimeType && item.deliveryEndTimeType !== 0) {
          this.$message.error('第' + (index + 1) + '行预计到达结束时间类型不能为空');
          return false;
        }
        if (!item.sendStartTimeType && item.sendStartTimeType !== 0) {
          this.$message.error('第' + (index + 1) + '行预计发出开始时间类型不能为空');
          return false;
        }
        if (!item.sendEndTimeType && item.sendEndTimeType !== 0) {
          this.$message.error('第' + (index + 1) + '行预计发出结束时间类型不能为空');
          return false;
        }
        item.deliveryStartTimeHour = item.deliveryStartTime.split(':')[0];
        item.deliveryStartTimeMinute = item.deliveryStartTime.split(':')[1];
        item.deliveryEndTimeHour = item.deliveryEndTime.split(':')[0];
        item.deliveryEndTimeMinute = item.deliveryEndTime.split(':')[1];
        item.sendStartTimeHour = item.sendStartTime.split(':')[0];
        item.sendStartTimeMinute = item.sendStartTime.split(':')[1];
        item.sendEndTimeDayHour = item.sendEndTime.split(':')[0];
        item.sendEndTimeDayMinute = item.sendEndTime.split(':')[1];
        item.transferOrder = index + 1;
        VOS.push(item);
      }
      params[this.type === 'add' ? 'transferStationSaveVOS' : 'transferStationUpdateVOS'] = VOS;

      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) {
      console.log(name, args[1]);
      if (name === 'consigneeUnit') {
        this.$set(this.form, 'consigneeUnitId', args[1] ? args[2][0].id : '');
        this.$set(this.form, 'consigneeUnitCode', args[1] ? args[2][0].code : '');
        this.$set(this.form, 'consigneeUnitName', args[1] ? args[2][0].name : '');
        if (!args[1]) {
          this.$set(this.form, 'consigneeId', '');
          this.$set(this.form, 'consigneeCode', '');
          this.$set(this.form, 'consigneeName', '');
        }
      } else if (name === 'consignee') {
        this.$set(this.form, 'consigneeId', args[1] ? args[2][0].id : '');
        this.$set(this.form, 'consigneeCode', args[1] ? args[2][0].code : '');
        this.$set(this.form, 'consigneeName', args[1] ? args[2][0].name : '');
      }
    },
    onTableChange(name, index, ...args) {
      if (name === 'transfer') {
        this.$set(this.formList[index], 'transferStationId', args[1] ? args[2][0].id : '');
        this.$set(this.formList[index], 'transferStationCode', args[1] ? args[2][0].code : '');
        this.$set(this.formList[index], 'transferStationName', args[1] ? args[2][0].name : '');
      }
    },

    timeChange() {
      this.formList = [...this.formList];
    },
  },
};
</script>

<style lang="less">
.ant-select {
  width: 100%;
}
</style>