<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-tooltip slot="label" open-delay="200" placement="top">
          <!-- <div slot="content">可选内容，详细使用内容详见<a target="_blank" style="color:#1890ff" href="https://demogic.udesk.cn/hc/articles/226671">《数据对话运营复盘流程》</a></div> -->
          <div slot="content">可选内容，详细使用内容详见《数据对话运营复盘流程》</div>
          <span class="tooltip-icon">会员分组</span>
        </el-tooltip>
        <div style="width:600px">
          <vue-gic-member-group :readonly="disabled" onlyFixedType v-if="initMemberGroup" :defaltSelected="defaltSelected" :height="500" projectName="marketing" @handleDataTransferred="handleDataTransferred" @handleDataLeft="handleDataLeft"></vue-gic-member-group>
        </div>
      </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: '',
        memberGroup: ''
      },
      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;
        }
      },
      // 会员分组
      defaltSelected: [],
      initMemberGroup: false,
      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 { activityInfo, tagGroupList } = result;
          const { name, beginDate, endDate, memberGroup } = activityInfo;
          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.memberGroup = memberGroup;
          this.defaltSelected = tagGroupList;
          this.ruleForm.name = name;
          this.loading = false;
          this.$nextTick(() => {
            this.initMemberGroup = true;
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // *********会员分组**********
    handleDataTransferred(data) {
      // 会员分组 情况下 memberSearchDTO 传数组字符串
      this.ruleForm.memberGroup = data
        .map(v => v.memberTagGroupId)
        .filter(v => v)
        .join(',');
    },
    handleDataLeft(selectedData, selectionToRemove) {
      // 不可编辑
      if (!this.disabled) {
        this.ruleForm.memberGroup = selectedData
          .map(v => v.memberTagGroupId)
          .filter(v => v)
          .join(',');
      } else {
        this.$message.warning('数据对话已生效，分组数据编辑无效');
      }
    }
  },
  mounted() {
    if (this.isAdd) {
      this.initMemberGroup = true;
    }
    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>

<style lang="scss" scoped>
/deep/ .group-set-transfer {
  margin: 0;
  padding: 0;
}
</style>
