<template>
  <div class="p20" v-loading="loading">
    <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-width="120px" class="group-form pt10 pb10">
      <el-form-item class="mass-input" label="计划名称" prop="name">
        <dm-input :disabled="isInfo" v-model="ruleForm.name" :byte-type="1" :maxlength="20" class="w380" />
      </el-form-item>
      <el-form-item label="数据对话">
        <activity-select :no-add="isInfo" :disabled="isInfo" :act-id.sync="ruleForm.mktActivityId" width="380"></activity-select>
      </el-form-item>
      <el-form-item class="is-required" label="发送时间" prop="putOnType">
        <el-radio-group :disabled="isInfo" v-model="ruleForm.putOnType">
          <el-radio v-for="item in putOnType" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="" prop="putOnTime" v-if="ruleForm.putOnType === 1">
        <el-date-picker :disabled="isInfo" class="w380" v-model="ruleForm.putOnTime" popper-class="hide-right-now" type="datetime" :picker-options="pickerOptions" placeholder="选择日期时间" />
      </el-form-item>
      <el-form-item label="发送人群" class="is-required">
        <dm-new-people force-show-save :disabled="isInfo" :waiting-save.sync="waitingSave" :region-id="currentAreaId" :resource="3" :reback-flag="rebackFlag" :re-id="ruleForm.memberSearchId" ref="newPeople" @pass-people-data="receivePeopleData" @reset-condition="ruleForm.memberSearchId = ''" />
      </el-form-item>
      <el-form-item label="通知内容">
        <dm-market-event-new :read-only="isInfo" ref="mk" v-if="ruleForm.couponPlanId && currentAreaIds.length" max="1" app-code="coupon-gic" fix-member-card :member-card-ids="currentAreaIds" :mode="mode" :relation-id="ruleForm.couponPlanId" dash-width="380" @saveBack="saveBack" />
      </el-form-item>
      <el-form-item class="pt10" v-if="isAdd">
        <el-button type="primary" @click="checkForm">{{ needCheck ? '新建并提交审核' : '确认新建' }}</el-button>
        <el-button @click="$router.go(-1)">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import activitySelect from '@/components/activity-select/index';
import commonApi from '@/api/common.js';
import { showConfirm } from '@/utils/common';
const { getRelationId, getMemberCount } = commonApi;
import { formatDateTimeByType } from '@/utils/index';
import api from '@/api/gic-card.js';
const { groupSendAdd, groupSendInfo } = api;
export default {
  name: 'GroupSend',
  components: {
    activitySelect
  },
  data() {
    const validTime = (rule, value, callback) => {
      if (new Date(value).getTime() < new Date().getTime()) {
        callback(new Error('发送时间不能小于当前时间'));
      }
      callback();
    };

    return {
      couponId: this.$route.query.couponId,
      loading: false,
      mode: [ 10 ],
      putOnType: [ { label: '立即发送', value: 0 }, { label: '定时发送', value: 1 } ],
      selectedScenes: '',
      ruleForm: {
        couponPlanId: '',
        name: '',
        putOnType: 0,  // （0：立即发送，1：定时发送）
        putOnTime: '',  // 定时发送时间格式
        memberSearchId: '',
        mktActivityId: '',
      },
      rebackFlag: false,
      waitingSave: true, // 人群筛选器是否在保存中
      rules: {
        name: [ { required: true, message: '请输入计划名称', trigger: 'blur' } ],
        // memberSearchId: [{ required: true, message: '请筛选人群筛选器数据', trigger: 'change' }],
        putOnTime: [ { required: true, message: '请输入发送时间', trigger: 'blur' }, { validator: validTime, trigger: 'blur' } ]
      },
      needCheck: false, // 是否需要审核
      pickerOptions: {
        disabledDate(val) {
          return Date.now() >= val.getTime() + 24 * 60 * 60 * 1000;
        }
      },
      saveByAuto: false, // 是否通过query 自动调取mk的数据默认选中卡券
      isAdd: this.$route.meta.type === 'add',
      isInfo: this.$route.meta.type === 'info',
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券' }, { breadName: '卡券投放', breadPath: '/gic-card/group-send/list' }, { breadName: `${this.isInfo ? '卡券投放详情' : '新建卡券投放'}` } ]);
  },
  mounted() {
    if(this.currentAreaId) {
      if(this.isAdd) {
        this.getNeedCheck();
        this.getRelationId();
      }
      if(this.isInfo) {
        this.getInfo();
      }
    }
  },
  methods: {
    // 获取详情
    getInfo() {
      if(this.loading) {
        return;
      }
      this.loading = true;
      groupSendInfo({ couponPlanId: this.$route.query.id }).then(res => {
        this.loading = false;
        this.ruleForm = res.result || {};
        if(res.result.memberCardId) {
          this.rebackFlag = true;
          this.waitingSave = false;
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    receivePeopleData(data) {
      this.ruleForm.memberSearchId = data.peopleId;
      this.$refs.ruleForm.validateField('memberSearchId');
    },
    // 新建
    submitForm() {
      if(this.loading) {
        return;
      }
      this.loading = true;
      let params = { ...this.ruleForm, memberCardId: this.currentAreaId };
      // params.couponId = mkList[0].revealData.couponId;
      if (params.putOnType === 0) {
        delete params.putOnTime;
      } else {
        params.putOnTime = formatDateTimeByType(params.putOnTime);
      }
      groupSendAdd(params).then(res => {
        this.loading = false;
        this.$tips({ message: '新建成功', type: 'success' });
        this.$router.push('/gic-card/group-send/list');
      }).finally(() => {
        this.loading = false;
      });
    },
    checkForm(){
      this.$refs.ruleForm.validate((valid) => {
        if(!valid){
          PublicMethods.jumpToFormError(); // eslint-disable-line
          return;
        } else {
          if(!this.ruleForm.memberSearchId) {
            this.$tips({ message: '请保存人群筛选器', type: 'error' });
            return;
          } else if(this.waitingSave) {
            this.$tips({ message: '人群筛选器处于编辑状态，请保存', type: 'error' });
            return;
          }
          const mkList = this.$refs.mk.getSaveList();
          if(mkList.length != 1) {
            this.$tips({ message: '请保存通知内容', type: 'error' });
            return;
          }
          this.loading = true;
          getMemberCount({ memberSearchId: this.ruleForm.memberSearchId, appCode: this.$store.getters.moduleCode, areaId: this.currentAreaId }).then(res => {
            this.loading = false;
            const count = res.result || 0;
            if(!count) {
              // 人数为0定时可以新建，实时不可以this.ruleForm.putOnType === 0 &&
              this.$tips({ message: '发送人数为0，请重新选择发送人群', type: 'warning' });
              return;
            }
            showConfirm(`<div>合计发送 ${count} 人，确认发送？</div>`, () => {
              this.submitForm();
            }, ()=> {
              return;
            });
          }).finally(() => {
            this.loading = false;
          });

        }
      });
    },
    // 获取审核配置
    getNeedCheck() {
      // getAuditInfo({ memberCardId: this.currentAreaId }).then(res => {
      //   if(res.result) {
      //     this.needCheck = res.result || false; // true：需要审核，false：不需要审核
      //   }
      // })
    },
    getRelationId() {
      getRelationId().then(res => {
        this.ruleForm.couponPlanId = res.result || '';
      });
    },
    // ***营销事件通知****
    saveBack() {
      // type: 10-gic卡券 1: 9-微信卡券
      if(this.$route.query.couponId && !this.saveByAuto) {
        this.saveByAuto = true; // 通过url的query保存过
        this.$refs.mk.saveItem({ prizeNoticeFlag: 1, prizeId: this.$route.query.couponId, type: 10 });
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.w380 {
  /deep/ {
    .ev-select, .el-input {
      width: 380px;
    }
  }
}
</style>