<template>
  <div class="dm-wrap" v-loading="loading">
    <el-form ref="form" :model="ruleForm" label-width="140px" :rules="rules">
      <el-form-item prop="name" label="活动名称">
        <dm-input v-model="ruleForm.name" class="w300" placeholder="请输入活动名称" :byteType="1" :maxlength="10"></dm-input>
      </el-form-item>
      <el-form-item prop="dateTime" label="活动时间">
        <el-date-picker :disabled="disabled" :picker-options="pickerOptions" v-model="ruleForm.beginDate" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="开始日期"></el-date-picker>
        <span style="color:#909299;margin-left:5px;margin-right:5px;">~</span>
        <el-date-picker :disabled="disabled" :picker-options="pickerOptions" v-model="ruleForm.endDate" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">确认{{ isAdd ? '新建' : '保存' }}</el-button>
      </el-form-item>
    </el-form>
    <ul style="padding-bottom:400px;margin-left:140px;color:#909399;font-size:14px;line-height:22px;">
      <li>* 应用中新建计划时可以使用营销活动：微信营销、短信营销、卡券营销、智能营销、游戏营销</li>
      <li>* 营销数据统计分析维度为：营销人次、活动覆盖人数、活动相关订单、活动销售额</li>
    </ul>
  </div>
</template>

<script>
import { _debounce } from '@/utils/index';
import { formatDateTimeByType } from '@/utils/index.js';
import { saveActivity, getActivityInfo } from '@/service/api/activityApi';
export default {
  name: 'activity-form',
  data() {
    const validateDateLessYear = (rule, value, callback) => {
      if (this.isEdit) {
        callback();
      }
      const date1 = this.ruleForm.beginDate;
      const date2 = this.ruleForm.endDate;
      if (!date1 || !date2) {
        callback(new Error('活动时间不能为空'));
      }
      if (new Date(date2).getTime() < new Date()) {
        callback(new Error('结束时间不能小于当前时间'));
      }
      if (new Date(date2).getTime() - new Date(date1).getTime() > 60 * 60 * 24 * 365 * 1000) {
        callback(new Error(rule.message || '时间跨度不能超过一年'));
      }
      callback();
    };
    return {
      loading: false,
      marketingActivityId: this.$route.params.id,
      ruleForm: {
        name: '',
        beginDate: '',
        endDate: ''
      },
      rules: {
        name: [{ required: true, message: '请输入活动名称', trigger: 'change' }],
        dateTime: [{ required: true, validator: validateDateLessYear, trigger: 'change' }]
      },
      pickerOptions: {
        disabledDate(val) {
          return Date.now() >= val.getTime() + 24 * 60 * 60 * 1000;
        }
      },
      isAdd: this.$route.meta.type === 'add',
      isEdit: this.$route.meta.type === 'edit'
    };
  },
  computed: {
    disabled() {
      return this.isEdit && new Date() > new Date(this.ruleForm.beginDate);
    }
  },
  methods: {
    submit: _debounce(function() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return;
        }
        let params = { ...this.ruleForm };
        if (this.isEdit) {
          params.marketingActivityId = this.marketingActivityId;
        }
        if (this.disabled) {
          // 不能改的时候不传活动时间
          delete params.beginDate;
          delete params.endDate;
        }
        this.loading = true;
        saveActivity(params)
          .then(res => {
            this.loading = false;
            this.$tips({ type: 'success', message: '操作成功' });
            this.$router.push('/activity/list');
          })
          .catch(() => {
            this.loading = false;
          });
      });
    }),
    getInfo() {
      this.loading = true;
      getActivityInfo({ marketingActivityId: this.marketingActivityId })
        .then(res => {
          const result = res.result || {};
          const { name, beginDate, endDate } = result;
          this.ruleForm.name = name;
          this.ruleForm.beginDate = formatDateTimeByType(beginDate, 'yyyy-MM-dd-HH-mm-ss');
          this.ruleForm.endDate = formatDateTimeByType(endDate, 'yyyy-MM-dd-HH-mm-ss');
          this.ruleForm.name = name;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    }
  },
  mounted() {
    if (this.isEdit) {
      this.getInfo();
    }
  },
  created() {
    // 设置面包屑
    let breadcrumbName = '智能营销编辑';
    if (this.isAdd) {
      breadcrumbName = '智能营销新增';
    }
    this.$store.commit('aside_handler', false);
    this.$store.commit('mutations_breadcrumb', [{ name: '营销活动列表', path: '/activity/list' }, { name: breadcrumbName, path: '' }]); // eslint-disable-line
  }
};
</script>
