<template>
	<a-modal
		:title="permissionFlag === 1 ? $t('plan.dvp.create-dvp'): $t('plan.dvp.edit-dvp')"
		:visible="addFlag"
    :maskClosable="false"
		:width="800"
		@ok="save"
		@cancel="closeModal"
		:footer="null"
	>
		<div>
			<a-form layout='vertical'>
				<a-row :gutter='24'>
          <!--性能模块-->
					<a-col :md="12" :sm="12">
						<a-form-item :label="$t('plan.dvp.vehicle-performance-module')">
							<a-input disabled v-model="performanceModule" :maxLength="128"/>
						</a-form-item>
					</a-col>
          <!--试验车用途描述-->
          <a-col :md="12" :sm="12">
            <a-form-item :required='true' :label="$t('plan.dvp.description-of-the-purpose-of-the-test-vehicle')">
              <a-input v-model.trim="formData.vehicleUse" :maxLength="128" :placeholder="$t('plan.dvp.please_enter-description-of-the-purpose-of-the-test-vehicle')"/>
            </a-form-item>
          </a-col>
				</a-row>
				<a-row :gutter='24'>
          <!--试验类型-->
          <a-col :md="12" :sm="12">
            <a-form-item :required='true' :label="$t('plan.dvp.test-type')">
              <a-select allowClear v-model="formData.testType" :options="testTypeList" @change="handleTestType" :placeholder="$t('plan.dvp.please_select-test-type')"></a-select>
            </a-form-item>
          </a-col>
          <!--车辆状态描述-->
          <a-col :md="12" :sm="12">
            <a-form-item :required='true' :label="$t('plan.dvp.description-of-the-vehicle-status')">
              <a-input v-model.trim="formData.vehicleState" :maxLength="128" :placeholder="$t('plan.dvp.please_enter-description-of-the-vehicle-status')"/>
            </a-form-item>
          </a-col>
				</a-row>
				<a-row :gutter='24'>
          <!--车辆数量-->
          <a-col :md="12" :sm="12">
            <a-form-item :required='true' :label="$t('plan.dvp.number-of-vehicles')">
              <a-input-number v-model.number="formData.count" :defaultValue="0" :min="1" :max="999" @change="handleCount" :placeholder="$t('plan.dvp.please_select-number-of-vehicles')" style="width: 100%"></a-input-number>
            </a-form-item>
          </a-col>
          <!--动态下拉选框-->
          <a-col  :md='12' :sm='12'  v-for="(item,index) in selectDataList"  :key="index">
            <a-form-item :required='true' :label="item.name">
              <a-select allowClear v-model="searchSelectData[item.id]" :options="item.configData" :key="index" :placeholder="$t('global-constant.please-select')"></a-select>
            </a-form-item>
          </a-col>
          <!--试验地点-->
          <a-col :md="12" :sm="12">
            <a-form-item :required='true' :label="$t('plan.dvp.test-location')">
              <a-input v-model.trim="formData.testSite" :maxLength="128" :placeholder="$t('plan.dvp.please-enter-test-location')"/>
            </a-form-item>
          </a-col>
          <!--试验负责人-->
          <a-col :md="12" :sm="12">
            <a-form-item :label="$t('plan.dvp.study-director')" required>
              <a-select
                allowClear
                showSearch
                v-model='formData.testOwner'
                :placeholder="$t('plan.dvp.please_select-study-director')"
                @search="getTestOwner"
                @change="handleTestOwner"
                :filterOption="handleOwnerFilterOption"
              >
                <a-icon slot='suffixIcon' type='search'/>
                <a-select-option
                  v-for='item in userList'
                  :key='item.accountName'
                  :value='item.userId'
                >
                  {{ item.account + " " + item.userName + " 【 " + item.departmentName + " 】" }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!--项目节点-->
          <a-col :md="12" :sm="12">
            <a-form-item :required='nodeRequired' :label="$t('plan.dvp.project-node')">
              <a-select allowClear v-model="formData.node" :options="projectNodeList" @change="handleProjectNode" :placeholder="$t('plan.dvp.please_select-project-node')"></a-select>
            </a-form-item>
          </a-col>
          <!--样车计划提供时间-->
          <a-col :md="12" :sm="12">
            <a-form-item :required='true' :label="$t('plan.dvp.sample-vehicle-plan-delivery-time')">
              <a-date-picker v-model="formData.prototypePlanTime" :disabled-date="disabledPlanDate" style="width: 100%" allowClear @change="handlePlanTime" valueFormat="YYYY/MM/DD" :placeholder="$t('plan.dvp.please_select-sample-vehicle-plan-delivery-time')"/>
            </a-form-item>
          </a-col>
          <!--计划开始时间-->
          <a-col :md="12" :sm="12">
            <a-form-item :required='true' :label="$t('plan.dvp.scheduled-start-time')">
              <a-date-picker v-model="formData.planStartTime" :disabled-date="disabledStartDate" @change="handleStartTime" :placeholder="$t('plan.dvp.please_select-scheduled-start-time')" style="width: 100%" allowClear valueFormat="YYYY/MM/DD"/>
            </a-form-item>
          </a-col>
          <!--计划结束时间-->
          <a-col :md="12" :sm="12">
            <a-form-item :required='true' :label="$t('plan.dvp.scheduled-end-time')">
              <a-date-picker v-model="formData.planEndTime" :disabled-date="disabledEndDate" @change="handleEndTime" :placeholder="$t('plan.dvp.please_select-scheduled-end-time')" style="width: 100%" allowClear valueFormat="YYYY/MM/DD"/>
            </a-form-item>
          </a-col>
				</a-row>
			</a-form>
			<div slot="footer" v-if="permissionFlag !== 4" class="mt10 text-right">
				<a-button @click="closeModal">
					{{ $t('global-btn.cancel') }}
				</a-button>
				<a-button
					type="primary"
					class="ml10"
					@click="save()">
					{{ $t('global-btn.confirm') }}
				</a-button>
			</div>
		</div>
	</a-modal>
</template>

<script>
import moment from "moment";

export default {
	name: "AddDvpTest",
	components: {},
	props: {
		addFlag: {
			type: Boolean,
			default: false
		},
		addFormData: {
			type: Object,
			default() {
				return {
          node: "",
          nodeId: undefined,
          testId: "", // 试验id
          vehicleUse: "", // 试验车用途描述
          testType: "", // 试验类型
          vehicleState: "", // 车辆状态
          count: "", // 车辆数量
          testSite: "", // 试验地点
          testOwner: "", // 试验负责人
          projectNode: "", // 节点
          prototypePlanTime: "", // 样车计划提供时间
          planStartTime: "", // 计划开始时间
          planEndTime: "", // 计划结束时间
          columnDataModel: [] // 下拉选数据
				};
			}
		},
    performanceModule: {
      type: String,
      default: undefined
    },
		permissionFlag: {
			type: Number,
			default: 1
		}
	},
	data() {
		return {
      // 试验负责人ID
      testOwnerId: undefined,
      /** 动态下拉选框  */
      selectDataList: [],
      /** 试验类型字典  */
      testTypeList: [
        {
          label: this.$t("plan.dvp.test-type-mule-car"),
          value: "0"
        },
        {
          label: this.$t("plan.dvp.test-type-know-the-real-situation"),
          value: "1"
        },
        {
          label: this.$t("plan.dvp.test-type-alignment"),
          value: "2"
        },
        {
          label: this.$t("plan.dvp.test-type-check-and-accept"),
          value: "3"
        },
        {
          label: this.$t("plan.dvp.test-type-consistence"),
          value: "4"
        }
      ],
      /**试验负责人*/
      testOwnerList: [],
      /**项目节点*/
      projectNodeList: [],
      /** 动态下拉选框 选中数据存储 */
      searchSelectData: {},
      planStartTime: undefined,
      planEndTime: undefined,
      formData: {},
      /**项目节点是否必填 */
      nodeRequired: false,
      /** 用户 */
      userList: [],
		};
	},
	watch: {
    // 监听新增数据变化
    addFormData: {
      deep: true,
      immediate: true,
      handler(addFormData) {
        this.formData = {...this.formData, ...addFormData};
        //编辑时候，需要记录下计划开始时间和计划结束时间的初始值
        this.planStartTime = this.formData.planStartTime;
        this.planEndTime = this.formData.planEndTime;
      }
    }
	},
  mounted() {
    this.getProjectNodeList();
    this.getTestOwner();
  },
	methods: {
    /**
     * 获取项目节点下拉选项
     */
    getProjectNodeList() {
      let data = {
        dvpId: this.$store.getters.dvpId
      };
      this.$api.getProjectNodeList(data).then(res => {
        if (res.flag){
          let nodeList = res.data.dynamicConfig;
          if (nodeList && nodeList.length > 0) {
            nodeList.forEach(item => {
              let options = {
                label: item.name,
                value: item.id
              }
              this.projectNodeList.push(options);
            });
            this.nodeRequired = true;
          } else {
            this.nodeRequired = false;
          }
        }
      });
    },
    /**
     * 编辑时，回显动态列数据
     */
    initSearchSelectData() {
      let searchData = this.formData.columnDataModel;
      if (searchData && searchData.length > 0) {
        searchData.forEach(item => {
          // 由于vue不能监听数组和对象的变化, 所以这么写是错误的, 双向绑定无法取到这个值
          // this.searchSelectData[item.columnId] = item.columnValueId
          // 以下写法是正确的, $set(对象, 键, 值)
          this.$set(this.searchSelectData, item.columnId, item.columnValueId);
        });
      }
    },
    /**
     * 初始化下拉选数据
     */
    initSelectList(dvpId) {
      let data = {
        dvpId: dvpId
      };
      this.$api.initSelectList(data).then(res => {
        if (res.flag){
          let selectList = res.data;
          if (selectList && selectList.length > 0) {
            selectList.forEach(item => {
              let config = item.configOption;
              let selectData = {};
              selectData.id = item.id;
              selectData.name = item.name;
              selectData.configData = [];
              if (config && config.length > 0) {
                config.forEach(eachData => {
                  let eachOption = {};
                  eachOption.key = eachData.id;
                  eachOption.value = eachData.id;
                  eachOption.label = eachData.name;
                  selectData.configData.push(eachOption);
                });
              };
              this.selectDataList.push(selectData);
              this.initSearchSelectData();
            });
          };
        }
      });
    },
		/**
		 * 关闭模态框
		 */
		closeModal() {
			this.$emit("closeModal");
      this.selectDataList = [];
      this.searchSelectData = {};
      this.formData = {};
		},
		/**
		 * 非空校验 判断是否为空
		 * @returns {boolean}
		 */
		isNull() {
			let _this = this;
			let message = [];
      // 试验车用途描述
			if (!_this.formData.vehicleUse) {
				message.push(_this.$t('global-constant.please-enter') + _this.$t('plan.dvp.description-of-the-purpose-of-the-test-vehicle'));
			}
      // 车辆状态描述
			if (!_this.formData.vehicleState) {
				message.push(_this.$t('global-constant.please-enter') + _this.$t('plan.dvp.description-of-the-vehicle-status'));
			}
      // 试验类型
			if (!_this.formData.testType) {
				message.push(_this.$t('global-constant.please-select') + _this.$t('plan.dvp.test-type'));
			}
      // 车辆数量
			if (!_this.formData.count) {
				message.push(_this.$t('global-constant.please-select') + _this.$t('plan.dvp.number-of-vehicles'));
			}
      // 试验地点
      if (!_this.formData.testSite) {
        message.push(_this.$t('global-constant.please-enter') + _this.$t('plan.dvp.test-location'));
      }
      // 试验负责人
      if (!_this.testOwnerId) {
        message.push(_this.$t('global-constant.please-select') + _this.$t('plan.dvp.study-director'));
      }
      // 项目节点
      if (_this.nodeRequired && !_this.formData.node) {
        message.push(_this.$t('global-constant.please-select') + _this.$t('plan.dvp.project-node'));
      }
      // 样车试验提供时间
      if (!_this.formData.prototypePlanTime) {
        message.push(_this.$t('global-constant.please-select') + _this.$t('plan.dvp.sample-vehicle-plan-delivery-time'));
      }
      // 计划开始时间
      if (!_this.formData.planStartTime) {
        message.push(_this.$t('global-constant.please-select') + _this.$t('plan.dvp.scheduled-start-time'));
      }
      // 计划结束时间
      if (!_this.formData.planEndTime) {
        message.push(_this.$t('global-constant.please-select') + _this.$t('plan.dvp.scheduled-end-time'));
      }
      // 如果样车时间晚于计划结束时间
      if (Date.parse(_this.formData.prototypePlanTime) > Date.parse(_this.formData.planEndTime)) {
        message.push(_this.$t('plan.dvp.prototype-time-can-not-later-than-end-time'));
      }
      //动态下拉选框
      if (_this.searchSelectData) {
        let searchData = [];
        for(let [key, value] of Object.entries(_this.searchSelectData)) {
          let selectedDate = {};
          //如果value没有值，就添加提醒消息
          if (value === undefined) {
            message.push(_this.$t('global-constant.please-enter'));
          } else {
            //keys 是下拉选框的id，区分是哪个下拉选框； value 是下拉选框选中项的id；
            selectedDate.configId = parseInt(key);
            selectedDate.id = value;
            searchData.push(selectedDate);
          }
        }
        //动态下拉选框选中数据，存进查询数据中
        _this.formData.addTestConfig = searchData;
      }
			if (message && message.length > 0) {
				for (let i = 0; i < message.length; i++) {
					_this.$notification.warning({message: message[i]});
				}
				return false;
			}
			return true;
		},
    /**
     * 新建校验 判断新建时数据是否有改动
     * @returns {boolean}
     */
    isSame() {
      let _this = this;
      let message = [];
      // 试验车用途描述
      if (_this.addFormData.vehicleUse !== _this.formData.vehicleUse) {
        return false;
      }
      // 车辆状态描述
      if (_this.formData.vehicleState !== _this.addFormData.vehicleState) {
        return false;
      }
      // 试验类型
      if (_this.formData.testType !== _this.addFormData.testType) {
        return false;
      }
      // 车辆数量
      if (_this.formData.count !== _this.addFormData.vehicleCount) {
        return false;
      }
      // 试验地点
      if (_this.formData.testSite !== _this.addFormData.testSite) {
        return false;
      }
      // 试验负责人
      if (_this.testOwnerId !== _this.testOwnerId) {
        return false;
      }
      // 项目节点
      if (_this.formData.node !== _this.addFormData.node) {
        return false;
      }
      // 样车试验提供时间
      if (_this.formData.prototypePlanTime !== _this.addFormData.prototypePlanTime) {
        return false;
      }
      // 计划开始时间
      if (_this.formData.planStartTime !== _this.addFormData.planStartTime) {
        return false;
      }
      // 计划结束时间
      if (_this.formData.planEndTime !== _this.addFormData.planEndTime) {
        return false;
      }
      // 如果样车时间晚于计划结束时间
      if (Date.parse(_this.formData.prototypePlanTime) > Date.parse(_this.formData.planEndTime)) {
        message.push(_this.$t('plan.dvp.prototype-time-can-not-later-than-end-time'));
      }
      let flag = true;
      this.formData.addTestConfig.forEach(item => {
        const matchingItem = this.addFormData.columnDataModel.find(oldItem => item.configId === oldItem.columnId);
        if (matchingItem && item.id !== matchingItem.columnValueId) {
            flag = false;
        }
      });
      return flag;
    },
		/**
		 * 新建/编辑 保存
		 * @returns {boolean}
		 */
		save() {
			let _this = this;
			if (!_this.isNull()) {
				return false;
			}
      if (_this.isSame()) {
        _this.$notification.warning({message: _this.$t('plan.dvp.task-content-has-not-been-changed-unable-to-create-new-task')});
        return false;
      }
			_this.tableLoading = true;
			let data = {
				dvpId: _this.$store.getters.dvpId,
        testId: _this.formData.testId,
        vehicleUse: _this.formData.vehicleUse,
        vehicleState: _this.formData.vehicleState,
        testType: _this.formData.testType,
        vehicleCount: _this.formData.count,
        testSite: _this.formData.testSite,
        engineerUserId: _this.testOwnerId,
        prototypePlanTime: _this.formData.prototypePlanTime,
        planStartTime: _this.formData.planStartTime,
        planEndTime: _this.formData.planEndTime,
        addTestConfig: _this.formData.addTestConfig,
        projectNodeId: _this.formData.node
			};

			// 新建
			if (_this.permissionFlag === 1) {

				_this.$api.addTestSave(data).then(res => {
					if (res.flag) {
						_this.$message.success(_this.$t('plan.dvp.operation-succeeded'), 1);
            _this.closeModal();
						_this.$emit("initData");
					} else {
						_this.$notification.error({message: res.message});
					}
				}).finally(() => {
					_this.tableLoading = false;
				});
			} else if (_this.permissionFlag === 2) {
				// 编辑
        // 当是编辑的时候，用户没有用下拉选项更换负责人，那此时拿的是负责人的用户名，需要转换
        _this.testOwnerList.forEach(item => {
          if (item.label === data.engineerUserId) {
            data.engineerUserId = item.value;
          }
        });
				_this.$api.editTestSave(data).then(res => {
					if (res.flag) {
						_this.$message.success(_this.$t('plan.dvp.operation-succeeded'), 1);
						_this.closeModal();
						_this.$emit("initData");
					} else {
						_this.formData = res.data;
            _this.$forceUpdate();
						_this.$notification.error({message: res.message});
					}
				}).finally(() => {
					_this.tableLoading = false;
				});
			}
		},
    /**
     * 试验类型下拉改变
     */
    handleTestType(val) {
      this.formData.testType = val;
    },
    /**
     * 车辆数量下拉改变
     * @param val
     */
    handleCount(val) {
      this.formData.count = val;
    },
    /**
     * 试验负责人输入模糊检索
     * @param val
     */
    getTestOwner(val) {
      let _that = this;
      _that.$api.getUserPageList({
        userName: val
      }).then(res => {
        if (res.flag) {
          _that.userList = (res.data.data || []).map(v => {
            return {
              userId: v.userId,
              userName: v.userName,
              accountName: v.account + v.userName,
              account: v.account,
              departmentId: v.departmentId,
              departmentName: v.departmentName
            };
          });
        } else {
          _that.$notification.error({message: res.message});
        }
      });
    },
    /**
     * 试验负责人下拉选择
     * @param val
     */
    handleTestOwner(val) {
      if (!val) {
        this.getTestOwner();
      }
      this.testOwnerId = val;
    },
    /**
     * 试验负责人过滤配置
     * @param input
     * @param option
     * @returns {boolean}
     */
    handleOwnerFilterOption(input, option) {
      return (
        option.key.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    /**
     * 项目节点下拉改变
     * @param val
     */
    handleProjectNode(val) {
      this.formData.projectNode = val;
    },
    /**
     * 样车提供时间 时间选择器Change方法
     */
    handlePlanTime(date, dateString) {
      if (!dateString) {
        this.formData.prototypePlanTime = "";
        return;
      }
      this.formData.prototypePlanTime = dateString;
    },

    /**
     * 样车提供时间 不能选择当天以前 不能选择计划结束时间之后
     * @param current
     * @returns {boolean}
     */
    disabledPlanDate(current) {
      return current && current < moment().subtract(1,"day").endOf('day');
    },

    /**
     * 开始时间不能选择当天
     * @param current
     * @returns {boolean}
     */
    disabledStartDate(current) {
      return current && current < moment().subtract(1,"day").endOf('day');
    },

    /**
     * 结束时间不能选择开始时间前的时间
     * @param current
     * @returns {boolean}
     */
    disabledEndDate(current) {
      // 有开始时间，则返回不能选择日期为开始时间之前的日期
      if (this.formData.planStartTime) {
        return current && current < moment(this.formData.planStartTime).endOf('day');
      } else { // 无开始时间，则返回不能选择日期为当前时间之前的日期
        return current && current < moment().subtract(1,"day").endOf('day');
      }
    },

    /**
     * 计划开始时间 时间选择器Change方法
     */
    handleStartTime(date, dateString) {
      if (!dateString) {
        this.formData.planStartTime = "";
        return;
      }
      this.formData.planStartTime = dateString;
      // 当选择的开始时间大于结束时间时，清空结束时间，让用户重新选择结束时间
      if (Date.parse(this.formData.planStartTime) > Date.parse(this.formData.planEndTime)) {
        this.formData.planEndTime = undefined;
      }
    },
    /**
     * 计划结束时间 时间选择器Change方法
     */
    handleEndTime(date, dateString) {
      if (!dateString) {
        this.formData.planEndTime = "";
        return;
      }
      //新建时，无开始时间无需作比较
      this.formData.planEndTime = dateString;
    },
	}
};
</script>
<style lang='less' scoped>
.text-right {
	text-align: right;
}
</style>
