<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-11-18 10:37:02
 * @LastEditors  : 无尘
 * @LastEditTime : 2020-01-08 18:13:10
 -->
<!--
<base-config  @submitNext="submitNext"></base-config>

import baseConfig from '@/components/active-config/base-config.vue';
-->
<template>
  <div class="base-config-content">
    <div class="config-title font-14 color-303133">基本信息</div>
    <el-form
      label-width="114px"
      :model="activeInfoData"
      ref="baseForm"
      :rules="rules"
    >
      <el-form-item
        v-if="$route.query.activityId"
        label="活动目的："
        prop=""
      > {{ activeInfoData.parentGoalName }} - {{ activeInfoData.goalName }} </el-form-item>
      <el-form-item
        v-if="$route.query.activityId"
        label="转化路径："
        prop=""
      >
        <div>{{ activeInfoData.router && activeInfoData.router.length ? activeInfoData.router.map(ele => ele.transName).join('→') : '' }}</div>
      </el-form-item>
      <el-form-item
        v-if="$route.query.activityId && activeInfoData.activityMarketPageName"
        label="活动营销页："
        prop="activityMarketPageName"
      > {{activeInfoData.activityMarketPageName}}</el-form-item>
      <el-form-item
        v-if="$route.query.activityId && activeInfoData.gamePlanName"
        label="游戏计划："
        prop="gamePlanName"
      > {{activeInfoData.gamePlanName}}</el-form-item>
      <el-form-item
        v-if="$route.query.activityId && activeInfoData.cardCoupName"
        label="卡券："
        prop="cardCoupName"
      >{{activeInfoData.cardCoupName}} </el-form-item>
      <el-form-item
        label="活动名称："
        prop="activityName"
      >
        <limitInput
          :inputWidth="350"
          :disflag="$route.query.editFlag ? true : false"
          :inputValue.sync="activeInfoData.activityName"
          :holder="'请输入活动名称'"
          :getByType="'char'"
          :maxLength="30"
        > </limitInput>
      </el-form-item>
      <el-form-item
        label="活动有效期："
        prop="dateRange"
        required
      >
        <!-- <el-date-picker
          class="m-l-10"
          prefix-icon="el-icon-time"
          :disabled="$route.query.editFlag"
          :picker-options="pickerOptions"
          v-model="activeInfoData.dateRange"
          @change="changeDate"
          :editable="false"
          :value-format="'yyyy-MM-dd HH:mm:ss'"
          :default-time="['00:00:00', '23:59:59']"
          :unlink-panels="false"
          type="daterange"
          align="right"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        > </el-date-picker> -->
        <el-date-picker
          class="m-l-10"
          :disabled="$route.query.editFlag || startDateDisabled"
          prefix-icon="el-icon-time"
          v-model="activeInfoData.startDate"
          :editable="false"
          :value-format="'yyyy-MM-dd'"
          type="date"
          align="right"
          placeholder="开始日期"
          :picker-options="pickerOptionsStart"
          @change="changeDate($event, true)"
        > </el-date-picker>
        <span style="margin:0 5px;color:#c0c4cc">-</span>
        <el-date-picker
          class="m-l-10"
          :disabled="$route.query.editFlag || endDateDisabled"
          prefix-icon="el-icon-time"
          v-model="activeInfoData.endDate"
          :editable="false"
          :value-format="'yyyy-MM-dd'"
          type="date"
          align="right"
          placeholder="结束日期"
          :picker-options="pickerOptionsEnd"
          @change="changeDate($event, false)"
        > </el-date-picker>
      </el-form-item>
      <el-form-item class="m-t-50">
        <el-button
          type="primary"
          @click="returnBack"
        >返回</el-button>
        <el-button
          type="primary"
          @click="submitForm('baseForm')"
        >下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import limitInput from '@/components/limit-input.vue';
import { getRequest, postRequest } from '@/api/api';
import { _debounce } from '@/common/js/public';
// import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import timeFormat from '@/common/js/timeFormat';
import moment from 'moment'
export default {
  name: 'base-config',
  props: {
    endDate: {
      type: Number,
      default: new Date().getTime()
    }
  },
  components: {
    limitInput
  },
  data() {
    const checkDate = (rule, value, callback) => {
      // console.log(value[0].split(' ')[0] ,timeFormat.timeStampToYmd(new Date().getTime()));
      // if (!value || !value.length) {
      //   callback(new Error('请选择活动有效期'));
      // } else if (value[0].split(' ')[0] == timeFormat.timeStampToYmd(new Date().getTime()) && value[0].split(' ')[0] == value[1].split(' ')[0]) {
      //   callback(new Error('不能选择今天'));
      // }else if (this.editDate && !!this.$route.query.activityId && (value[0].split(' ')[0] != timeFormat.timeStampToYmd(new Date().getTime()) || timeFormat.timeStampToYmd(new Date().getTime()) == value[1].split(' ')[0])) {
      //   callback(new Error('开始时间无法改到当前时间之后，结束时间无法改到当前时间之前'));
      // } else {
      //   callback();
      // }
      if(!value || !value.length || (!value[0] && !value[1])) {
        callback(new Error('请选择活动有效期'));
      } else if(!value[0]) {
        callback(new Error('请选择开始日期'));
      } else if(!value[1]) {
        callback(new Error('请选择结束日期'));
      } else if(value[1]&&new Date(this.activeInfoData.endDate).getTime()> this.endDate){
        callback(new Error(`您的分享有礼功能${moment(this.endDate).format('YYYY年MM月DD日')}到期，活动结束时间无法超过该日期。`));
      } else {
        callback();
      }
    };
    return {
      activeInfoData: {
        activityId: '',
        parentGoalId: '',
        parentGoalName: '',
        goalName: '',
        goalId: '',
        activityMarketPageId: '',
        gamePlanId: '',
        cardCoupId: '',
        activityMarketPageName: '',
        gamePlanName: '',
        gamePlanUrl: '',
        cardCoupName: '',
        router: '',
        activityName: '',
        dateRange: [],
        editDate: false,
        startDate: '',
        endDate: '',
        startDateDisabled: false,
        endDateDisabled: false
      },
      rules: {
        activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        dateRange: [{ validator: checkDate, trigger: 'change' }]
      },
      choiceDateCopy: [],
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.choiceDateCopy = [minDate.getTime()];
          if (maxDate) {
            this.choiceDateCopy = [];
          }
        },
        disabledDate: time => {
          if (this.choiceDateCopy.length) {
            const one = 365 * 24 * 3600 * 1000;
            const minTime = this.choiceDateCopy[0] - one;
            const maxTime = this.choiceDateCopy[0] + one;
            return time.getTime() < minTime || time.getTime() > maxTime || time.getTime() < Date.now() - 8.64e7;
          }
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      pickerOptionsStart: {
        disabledDate: time => {
          let disabled = time.getTime() < Date.now() - 8.64e7;
          // if(this.activeInfoData.endDate) {
          //   disabled = disabled || (time.getTime() > new Date(this.activeInfoData.endDate).getTime());
          // }
          return disabled;
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          let disabled = time.getTime() < Date.now() - 8.64e7;
          if(this.activeInfoData.startDate) {
            disabled = disabled || (time.getTime() < new Date(this.activeInfoData.startDate).getTime());
          }
          if(!this.activeInfoData.startDate || (new Date(this.activeInfoData.startDate).toDateString() === new Date().toDateString())) {
            disabled = disabled || (time.getTime() <= new Date().setHours(0,0,0));
          }
          return disabled;
        }
      },
    };
  },
  methods: {
    /**
     * 日期
     */
    changeDate(e, isStartDate) {
      const that = this;
      that.editDate = true;
      // if (!e) {
      //   that.choiceDateCopy = [];
      //   that.activeInfoData.dateRange = [];
      // }
      isStartDate && (this.activeInfoData.endDate = '');
      this.activeInfoData.startDate && (this.activeInfoData.startDate = timeFormat.timeToDateTime(new Date(this.activeInfoData.startDate).setHours(0,0,0,0)));
      this.activeInfoData.endDate && (this.activeInfoData.endDate = timeFormat.timeToDateTime(new Date(this.activeInfoData.endDate).setHours(23,59,59,999)));
      this.activeInfoData.dateRange = [ this.activeInfoData.startDate || '', this.activeInfoData.endDate || '' ]
    },
    /**
     * 返回
     */
    returnBack() {
      this.$router.go(-1);
    },
    /**
     * 下一步
     */
    submitForm: _debounce(function(formName) {
      const that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.$store.dispatch('clearIndexData'); // 清空首页暂存数据
          if (that.$route.query.hasOwnProperty('editFlag')) {
            that.$emit('submitNext', that.activeInfoData);
            that.$store.dispatch('saveBaseInfo', that.activeInfoData);
          }else {
            that.postSave();
          }
        } else {
          return false;
        }
      });
    },500),
    postSave() {
      const that = this;
      if (!that.activeInfoData.dateRange) {
        that.activeInfoData.dateRange = [];
      }
      that.activeInfoData.startDate = that.activeInfoData.dateRange[0];
      let para = {
        activityId: that.activeInfoData.activityId,
        activityName: that.activeInfoData.activityName,
        startDate: that.activeInfoData.dateRange[0],
        endDate: that.activeInfoData.dateRange[1],
        parentGoalId: that.activeInfoData.parentGoalId,
        goalId: that.activeInfoData.goalId,
        activityMarketPageId: that.activeInfoData.activityMarketPageId,
        activityMarketPageName: that.activeInfoData.activityMarketPageName,
        gamePlanId: that.activeInfoData.gamePlanId,
        gamePlanUrl: that.activeInfoData.gamePlanUrl,
        gamePlanName: that.activeInfoData.gamePlanName,
        cardCoupId: that.activeInfoData.cardCoupId,
        cardCoupName: that.activeInfoData.cardCoupName,
        router: JSON.stringify(that.activeInfoData.router)
      };
      postRequest('/sharing-core-web/edit-activity-base-info', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.activeInfoData.activityId = resData.result;
            that.$emit('submitNext', that.activeInfoData);
            that.$store.dispatch('saveBaseInfo', that.activeInfoData);
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 获取基础信息
     * /sharing-core-web/get-activity-base-info
     */
    getBaseData() {
      const that = this;
      let para = {
        activityId: that.$route.query.activityId
      };
      getRequest('/sharing-core-web/get-activity-base-info', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (resData.result && resData.result.router) {
              resData.result.router = JSON.parse(resData.result.router);
            }
            resData.result.router.sort(function(a,b){
              return (a.transId - b.transId);
            })
            this.startDateDisabled = Date.now() > resData.result.startDate;
            this.endDateDisabled = Date.now() > resData.result.endDate
            resData.result.startDate = timeFormat.timeToDateTime(resData.result.startDate);
            resData.result.endDate = timeFormat.timeToDateTime(resData.result.endDate);
            resData.result.dateRange = [resData.result.startDate, resData.result.endDate];
            that.activeInfoData = resData.result;
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  mounted() {
    const that = this;
    if (that.$route.query.hasOwnProperty('activityId')) {
      that.getBaseData();
    }
    if (Object.keys(that.$store.state.activeInfo).length) {
      const info = JSON.parse(JSON.stringify(that.$store.state.activeInfo));
      that.activeInfoData.parentGoalId = info.firstGoal.goalId;
      that.activeInfoData.goalId = info.secondGoal.goalId;
      that.activeInfoData.goalName = info.secondGoal.goalName; // 消费门店控制需要用到
      that.activeInfoData.activityMarketPageId = info.markingValue;
      that.activeInfoData.activityMarketPageName = info.activityMarketPageName;
      that.activeInfoData.gamePlanId = info.gameValue[1];
      that.activeInfoData.gamePlanName = info.gamePlanName;
      that.activeInfoData.gamePlanUrl = info.gamePlanUrl;
      that.activeInfoData.cardCoupId = info.cardValue;
      that.activeInfoData.cardCoupName = info.cardCoupName;
      that.activeInfoData.router = info.pathArr;
    }
    // 上一步获取状态内数据
    if (Object.keys(that.$store.state.baseInfo).length) {
      that.$nextTick(() => {
        that.activeInfoData = JSON.parse(JSON.stringify(that.$store.state.baseInfo));
      });
    }
  }
};
</script>
<style lang="less" scoped>
.base-config-content {
  padding: 48px 0 0 0;
  .config-title {
    font-weight: 600;
    margin-bottom: 30px;
  }
  .m-t-50 {
    margin-top: 50px;
  }
  .el-form-item {
    /deep/ .el-form-item__label {
      color: #606266;
    }
  }
}
</style>
