<template>
  <el-dialog :title="`${ type === 'add' ? '新建' : '编辑' }数据对话`" :visible.sync="dialogVisible" width="630px" @close="handleClose" @closed="closed" append-to-body>
    <div v-loading="loading">
      <el-form ref="ruleForm" :model="ruleForm" label-width="130px" :rules="rules" class="activity-form pt10 pb10">
        <el-form-item prop="name" label="数据对话名称">
           <el-input show-word-limit v-model="ruleForm.name" style="width:450px" placeholder="请输入数据对话名称"   :maxlength="10" />
        </el-form-item>
        <el-form-item prop="dateTime" label="有效时间">
          <el-date-picker :picker-options="pickerOptions" :disabled="disabled" style="width:450px" :default-time="['00:00:00', '23:59:59']" v-model="dateTime" type="datetimerange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          <!-- <el-date-picker style="width:220px" :disabled="disabled" :picker-options="pickerOptions" v-model="ruleForm.beginDate" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="开始日期"></el-date-picker>
          <span class="gray03 ml5 mr5">~</span>
          <el-date-picker style="width:220px" :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>
      <ul class="tips mt30">
        <li>* 应用中新建计划时可以使用数据对话：微信营销、短信营销、卡券营销、智能营销、游戏营销</li>
        <li>* 营销数据统计分析维度为：营销人次、活动覆盖人数、活动相关订单、活动销售额</li>
      </ul>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <dm-perm-button type="primary" @click="submit" :disabled="$itemPerm($itemCode.actToAdd1)">{{ type === 'add' ? '确认新建' : '保存' }}</dm-perm-button>
    </span>
  </el-dialog>
</template>

<script>
import commonApi from '@/api/common';
import { formatDateTimeByType } from '@/utils/index.js';
const { saveActivity, getActivityInfo } = commonApi;
const defaultRuleform = {
  name: '',
  beginDate: '',
  endDate: ''
};
export default {
  name: 'AddActivityDialog',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
  },
  data() {
    const validateDateLessYear = (rule, value, callback) => {
      if (this.type == 'edit') {
        callback();
        return;
      }
      if(!this.dateTime || this.dateTime.length != 2) {
        callback(new Error('活动时间不能为空'));
        return;
      }
      const date1 = this.dateTime[0];
      const date2 = this.dateTime[1];
      if (!date1 || !date2) {
        callback(new Error('活动时间不能为空'));
        return;
      }
      if (new Date(date2).getTime() < new Date(date1).getTime()) {
        callback(new Error('结束时间不能小于开始时间'));
        return;
      }
      if (new Date(date2).getTime() < new Date()) {
        callback(new Error('结束时间不能小于当前时间'));
        return;
      }
      if (new Date(date2).getTime() - new Date(date1).getTime() > 60 * 60 * 24 * 365 * 1000) {
        callback(new Error(rule.message || '时间跨度不能超过一年'));
        return;
      }
      callback();
    };
    return {
      loading: false,
      type: 'add', // add edit
      mktActivityId: this.$route.query.id,
      ruleForm: {
        ...defaultRuleform
      },
      dateTime: [],
      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;
        }
      },
    };
  },
  methods: {
    submit() {
      if(this.loading) {
        return;
      }
      this.$refs.ruleForm.validate(valid => {
        if (!valid) {
          return;
        }
        let params = { ...this.ruleForm };
        if (this.isEdit) {
          params.mktActivityId = this.mktActivityId;
        }
        params.beginDate = formatDateTimeByType(this.dateTime[0], 'yyyy-MM-dd-HH-mm-ss');
        params.endDate = formatDateTimeByType(this.dateTime[1], 'yyyy-MM-dd-HH-mm-ss');
        if (this.disabled) {
          // 不能改的时候不传活动时间
          delete params.beginDate;
          delete params.endDate;
        }
        this.loading = true;
        saveActivity(params, { type: this.type == 'add' ? 'insert' : 'update' })
          .then(res => {
            this.loading = false;
            this.$tips({ type: 'success', message: this.type === 'add' ? '新建成功' : '保存成功' });
            this.$emit('saveSuccess'); // 通知父组件操作成功
            this.handleClose();
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    edit(mktActivityId) {
      this.type = 'edit';
      this.mktActivityId = mktActivityId;
      this.loading = true;
      getActivityInfo({ mktActivityId })
        .then(res => {
          this.loading = false;
          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.dateTime = [ beginDate, endDate ];
        })
        .finally(() => {
          this.loading = false;
        });
    },
    closed() {
      // 重置数据
      this.ruleForm = { ...defaultRuleform };
      this.dateTime = [ , ];
      this.type = 'add';
    },
    handleClose() {
      this.$emit('update:dialogVisible', false);
    },
  },
  computed: {
    disabled() {
      return this.type == 'edit' && new Date() > new Date(this.ruleForm.beginDate);
    }
  },
  watch: {
    dialogVisible(val) {
      if(val && this.$refs.ruleForm) {
        this.$refs.ruleForm.clearValidate();
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.tips {
  color:#909399;
  font-size:13px;
  line-height:22px;
}
</style>