<template>
  <section class="dm-wrap" v-loading="loading">
    <el-form :model="form" ref="form" :rules="rules" label-suffix="：" label-width="110px">
      <el-form-item label="计划名称" prop="storeSignName">
        <el-input v-model="form.storeSignName" class="long-input" type="text" maxlength="20" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="签到日期">
        <el-radio-group v-model="form.dateType" class="pick-radio" @change="dateTypeChange">
          <el-radio :label="1">长期生效</el-radio>
          <el-radio :label="2">指定日期</el-radio>
        </el-radio-group>
        <!-- 签到日期选择指定日期 -->
        <el-form-item prop="date" class="date_picker_item">
          <el-date-picker v-if="form.dateType === 2" v-model="date" :picker-options="pickerOptions" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width:294px;"></el-date-picker>
        </el-form-item>
      </el-form-item>
      <el-form-item label="签到时段" prop="timeType">
        <el-radio-group v-model="form.timeType" class="pick-radio" @change="timeTypeChange">
          <el-radio :label="1">长期生效</el-radio>
          <el-radio :label="2">指定时段</el-radio>
        </el-radio-group>
        <!-- 签到时段选择指定时段 -->
        <el-form-item prop="time" class="date_picker_item" v-if="form.timeType === 2">
          <el-time-picker v-model="form.timeStart" :picker-options="{ selectableRange: `00:00:00 - ${maxTime}` }" class="store-sign-timepicker" placeholder="开始时间" style="width:135px;" value-format="HH:mm:ss" format="HH:mm"></el-time-picker><span style="margin: 0 5px;">至</span>
          <el-time-picker v-model="form.timeEnd" :picker-options="{ selectableRange: `${minTime} - 23:59:59` }" class="store-sign-timepicker" placeholder="结束时间" style="width:135px;" value-format="HH:mm:ss" format="HH:mm"></el-time-picker>
          <!-- <el-time-picker v-model="form.timeStart" :picker-options="{ selectableRange: `00:00:00 - ${maxTime}` }" class="store-sign-timepicker" align="center" placeholder="开始时间" style="width:135px;" value-format="HH:mm:ss">
          <el-time-picker v-model="form.timeEnd" :picker-options="{ selectableRange: `${minTime} - 23:59:59` }" align="center" placeholder="结束时间" style="width:135px;" value-format="HH:mm:ss"> </el-time-picker> -->
        </el-form-item>
      </el-form-item>
      <el-form-item label="签到间隔" prop="signInterval">
        <el-radio-group v-model="form.signInterval" class="sign-time">
          <el-radio :label="1">每天<span v-if="form.signInterval === 1" class="tips">每个用户每天可在门店签到一次。每天0:00刷新签到次数</span></el-radio>
          <el-radio :label="2">每周<span v-if="form.signInterval === 2" class="tips">每个用户每周可在门店签到一次。每周一0:00刷新签到次数</span></el-radio>
          <el-radio :label="3">每月<span v-if="form.signInterval === 3" class="tips">每个用户每月可在门店签到一次。每月1号0:00刷新签到次数</span></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="签到门店" prop="storeFilterId" v-if="showStoreCard">
        <vue-gic-store-card :options="options" :uuid.sync="uuid" ref="storeCard"></vue-gic-store-card>
      </el-form-item>
      <el-form-item label="签到距离" prop="signDistance">
        <el-input-number v-model="form.signDistance" controls-position="right" class="shortInput" @change="handleChange" :min="100" :max="5000" :step="1" :step-strictly="true"></el-input-number><span style="margin-left:9px;">米</span>
        <span class="tips">*为了保证用户体验，建议设置签到距离为100米，设置范围为100-5000米。</span>
      </el-form-item>
      <el-form-item label="签到人群" prop="memberSearchType">
        <el-radio-group class="pb20" v-model="form.memberSearchType">
          <el-radio :label="0">全部会员</el-radio>
          <el-radio :label="1">自定义人群</el-radio>
          <el-radio :label="2">会员分组</el-radio>
        </el-radio-group>
        <div style="width:984px" v-if="form.memberSearchType === 1">
          <vue-gic-people projectName="marketing" :isAdd="isAdd" :hasSearchData="hasSearchData" :sceneValue="sceneValue" ref="peopleFilter" @findFilter="findFilter" @getBackData="getBackData" @editHide="editHide" @editShow="editShow" @hideBtn="hideBtn" />
          <div class="gic-people--button" v-show="toggleTag">
            <el-button size="small" type="primary" @click="getData">确 定</el-button>
            <el-button size="small" @click="cancelFilter">取 消</el-button>
          </div>
        </div>
        <div v-if="form.memberSearchType === 2">
          <vue-gic-member-group v-bind="form.memberSearchId" :defaltSelected="hasSearchData" :height="500" projectName="marketing" :headerList="headerList" @handleDataTransferred="handleDataTransferred" @handleDataLeft="handleDataLeft"></vue-gic-member-group>
        </div>
      </el-form-item>
      <el-form-item label="签到规则说明" prop="remark">
        <el-input v-model="form.remark" class="long-input textarea-input" type="textarea" resize="none" rows="4" maxlength="1000" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="签到福利">
        <section class="dm-marketing">
          <div class="dm-marketing__opt--wrap" style="margin-bottom:10px;" v-if="!itemCom">
            <i class="el-icon-plus dm-marketing__opt--icon" @click="optTopShow = !optTopShow"></i>
            <transition name="fade">
              <opt @addItem="addItem" :options="prizeOptions" v-if="optTopShow"></opt>
            </transition>
          </div>
          <component :is="dialogCom" :show.sync="showDialog" :item="prizeItem" @sendItem="saveToList"></component>
          <div class="dm-marketing__content__item" style="padding:0;margin:0 0 20px" v-if="itemCom && prizeItem">
            <component :is="itemCom" :item="prizeItem"></component>
            <i class="el-icon-edit dm-marketing__opt--icon" @click="editItem"></i>
            <dm-delete @confirm="delItem">
              <i class="el-icon-delete dm-marketing__opt--icon"></i>
            </dm-delete>
          </div>
          <span class="tips">*支持每人限领张数≥100张的卡券。</span>
        </section>
        <el-form-item prop="prizeType">
          <el-input type="text" v-model="form.prizeType" style="display:none;"></el-input>
        </el-form-item>
      </el-form-item>
      <div v-if="canEdit" style="font-size:0;">
        <el-button type="primary" @click="onSubmit('form')" style="margin:24px 0 50px 111px;">保存</el-button>
        <span class="tips">（若使用多个计划需小程序版本升级到3.8.2以上)</span>
      </div>
    </el-form>
  </section>
</template>

<script>
/* eslint-disable */
import { saveStoreSignSetting, getStoreSignDetail } from '@/service/api/storeSign.js';
import { formatDateTimeByType } from '@/utils/index.js';
// 页面item组件
import itemCard from './components/item-card.vue';
import itemIntegral from './components/item-integral.vue';
//弹窗组件
import libCard from './components/lib-card.vue';
import libIntegral from './components/lib-integral.vue';
// 操作组件
import opt from './components/opt.vue';
const defaultForm = {
  storeSignName: '', // 计划名称
  dateType: 1, // 签到日期 1长期2日期段
  date: [ '', '' ],
  dateStart: null, // 签到指定日期(开始)
  dateEnd: null, // 签到指定日期(结束)
  timeType: 1, // 签到时段 1所有时间段2指定时间段
  time: [ '', '' ], // 签到指定时段
  timeStart: 0, // 签到指定时段(开始)
  timeEnd: 0, // 签到指定时段(结束)
  signInterval: 1, // 签到间隔 签到间隔1每天2每周3每月
  storeFilterId: '', // 签到门店
  signDistance: 0, // 签到距离
  memberSearchType: 0, //  0-全部会员 1-自定义人群 2-会员分组
  memberSearchId: '', // 签到人群id
  remark: '', // 签到规则说明
  prizeType: null, // 签到奖品类型1积分2卡券
  prizeValue: '', // 积分值
  prizeId: null // 卡券id
};
export default {
  name: 'sign-setting',
  components: {
    opt: opt,
    'item-card': itemCard,
    'item-integral': itemIntegral,
    'lib-card': libCard,
    'lib-integral': libIntegral
  },
  data() {
    const validStoreSignName = (rule, value, callback) => {
      if (!this.form.storeSignName) {
        return callback(new Error('请填写计划名称'));
      } else {
        callback();
      }
    };
    const validDate = (rule, value, callback) => {
      if (this.form.dateType === 2 && !this.date[ 0 ]) {
        return callback(new Error('请选择指定日期'));
      } else {
        callback();
      }
    };
    const validTime = (rule, value, callback) => {
      if (this.form.timeType === 2 && (!this.form.timeStart || !this.form.timeEnd)) {
        return callback(new Error('请选择指定时段'));
      } else {
        callback();
      }
    };
    const validPrize = (rule, value, callback) => {
      if (!this.form.prizeType) {
        return callback(new Error('请选择签到福利'));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      // 门店筛选器
      uuid: '', // 新增传空，编辑必传,
      creatorId: '',
      showStoreCard: false,
      isAdd: false,
      canEdit: false,
      // 需要的下拉 默认为全部[0,1,2,3,4,5]
      // 0 全部 1 门店类型 2门店标签 3 门店区域 4 门店分组 5 部分门店
      options: [ 0, 1, 2, 3, 4, 5 ],
      storeConfig: null,
      // 人群筛选器
      getSaveData: '',
      brandLogo: '', // 公司logo
      hasSearchData: '', // 当前页回显的数据(接口返回)
      toggleTag: false, // 控制(确认取消)按钮显示的参数,仅供参考,可自行修改
      saveTag: false, // 控制(保存)按钮显示的参数,仅供参考,可自行修改
      // 门店分组
      headerList: [ 'isRealTime', 'latestUpdateTime', 'updateType', 'effectiveStatus', 'effectiveDate' ],// 表头配置，默认全部，分组名称默认显示不可配置
      form: Object.assign({}, defaultForm),
      date: [],
      time: [],
      prizeOptions: [
        // eslint-disable-next-line
        { name: '卡券', value: 'card', key: 1, img: require('./assets/img/card.svg') }, // eslint-disable-next-line
        { name: '积分', value: 'integral', key: 2, img: require('./assets/img/integral.svg') }
      ],
      optTopShow: true,
      dialogCom: '', // 签到福利弹窗组件
      itemCom: '', // 签到福利组件
      prizeItem: {},
      showDialog: false, // 弹窗显示隐藏
      rules: {
        storeSignName: { validator: validStoreSignName, trigger: 'blur' },
        date: { validator: validDate, trigger: 'blur' },
        time: { validator: validTime, trigger: 'blur' },
        prizeType: { validator: validPrize, trigger: 'change' }
      },
      pickerOptions: {
        disabledDate: time => {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        }
      }
    };
  },
  created() {
    this.$store.commit('mutations_breadcrumb', [ { name: '门店签到' }, { name: '计划列表', path: '/sign/plan' }, { name: `${this.$route.query.id ? '编辑' : '新建'}计划`, path: '' } ]);
    if (this.$route.query.id) {
      this.canEdit = this.$route.query.canEdit ? true : false
      this.getDetail();
    } else {
      this.canEdit = true;
      this.isAdd = true
      this.showStoreCard = true;
    }
  },
  methods: {
    async getDetail() {
      const res = await getStoreSignDetail({ storeSignId: this.$route.query.id });
      if (res.errorCode === 0 && res.result) {
        this.form = { ...res.result };
        this.uuid = res.result.storeFilterId;
        this.brandLogo = res.result.brandLogo;
        if (this.form.memberSearchType === 1) {
          this.hasSearchData = this.form.memberSearchId || '{}';
        } else if (this.form.memberSearchType === 2) {
          this.hasSearchData = this.form.memberTagGroupList;
        }
        if (this.form.dateType && this.form.dateStart && this.form.dateEnd) {
          this.date[ 0 ] = formatDateTimeByType(this.form.dateStart, 'yyyy-MM-dd');
          this.date[ 1 ] = formatDateTimeByType(this.form.dateEnd, 'yyyy-MM-dd');
        }
        if (this.form.prizeType === 1) {
          this.prizeItem.integralCount = this.form.prizeValue;
          this.itemCom = 'item-integral';
        } else {
          this.prizeItem = { ...this.form.coupon };
          this.itemCom = 'item-card';
        }
      }
      this.showStoreCard = true;
    },
    onSubmit() {
      this.$refs[ 'form' ].validate(valid => {
        if (valid) {
          const params = { ...this.form };
          console.log(params);
          if (this.uuid) {
            params.storeFilterId = this.uuid;
          }
          if (params.dateType===2) {
            params.dateStart = this.date[ 0 ];
            params.dateEnd = this.date[ 1 ];
            delete params.date
          }
          if (params.timeType===2) {
            params.timeStart =params.timeStart.substring(0,params.timeStart.lastIndexOf(':'))+':00';
            params.timeEnd = params.timeEnd.substring(0,params.timeEnd.lastIndexOf(':'))+':59';
            delete params.time
          }
          if (params.prizeType === 1) {
            delete params.prizeId;
          } else {
            delete params.prizeValue;
          }
          saveStoreSignSetting(params).then(res => {
            if (res.errorCode === 0) {
              this.$message.success('保存成功');
              this.$router.replace('/sign/plan')
            }
          });
        } else {
          this.$message.error('请完善信息');
          return false;
        }
      });
    },
    /*-------人群筛选器的方法-------*/
    getData() {
      this.$refs.peopleFilter.confirmSet();
    },
    // 签到人群 取消
    cancelFilter() {
      this.$refs.peopleFilter.cancelSet();
    },
    // 获取需要回显的数据, 供保存时候使用
    getBackData(value) {
      this.getSaveData = value;
    },
    // 子组件触发父组件事件,返回过滤条件数据
    findFilter(value) {
      this.form.memberSearchId = value;
    },
    // 显示编辑,保存按钮隐藏,确认按钮显示 (子组件会调用)
    editShow() {
      this.toggleTag = true;
      this.saveTag = false;
    },
    // 显示保存按钮,隐藏确认按钮显示  (子组件会调用)
    editHide() {
      this.toggleTag = false;
      this.saveTag = true;
    },
    // 隐藏保存按钮和确认按钮  (子组件会调用)
    hideBtn() {
      this.toggleTag = false;
      this.saveTag = false;
    },
    handleDataTransferred(data) {
      // 会员分组 情况下 memberSearchDTO 传数组字符串
      // 只有新增时处理数据
      this.form.memberSearchId = data
        .map(v => v.memberTagGroupId)
        .filter(v => v)
        .join(',');
    },
    handleDataLeft(selectedData, selectionToRemove) {
      // 不可编辑
      this.form.memberSearchId = selectedData
        .map(v => v.memberTagGroupId)
        .filter(v => v)
        .join(',');
    },

    // 签到福利
    showPrizeDialog(type) {
      this.dialogCom = type ? 'lib-card' : 'lib-integral';
      this.showDialog = true;
    },
    // 签到福利保存
    saveToList(val) {
      if (val.comName === 'integral') {
        this.form.prizeType = 1;
        this.itemCom = 'item-integral';
        this.form.prizeValue = val.integralCount;
        this.prizeItem = val;
        this.form.prizeId = null;
      } else {
        this.form.prizeType = 2;
        this.itemCom = 'item-card';
        this.form.prizeId = val.coupCardId;
        this.prizeItem = { ...val, brandLogo: this.brandLogo };
        this.form.prizeValue = '';
      }
    },
    // 编辑
    editItem() {
      this.dialogCom = this.itemCom === 'item-card' ? 'lib-card' : 'lib-integral';
      this.showDialog = true;
    },
    // 删除操作
    delItem() {
      this.itemCom = '';
      this.prizeItem = {};
      this.form.prizeType = 0;
      this.form.prizeValue = '';
      this.form.prizeId = '';
    },
    // 新增前置 不能超过营销事件限制数量
    addItem(v) {
      this.dialogCom = 'lib-' + v.value;
      // 新增的时候设置为空对象
      this.form.prizeValue = '';
      this.form.prizeId = '';
      this.prizeItem = {};
      this.showDialog = true;
    },
    gointegralService() {
      window.location.href = window.location.origin + '/gic-web/#/integralService';
    },
    timeTypeChange(val) {
      this.$refs[ 'form' ].clearValidate('time')
      if (val === 2) {
        this.form.timeStart = '';
        this.form.timeEnd = '';
      }
    },
    dateTypeChange(v) {
      this.$refs[ 'form' ].clearValidate('date')
      this.date = v === 1 ? null : []
    }
  },
  watch: {},
  computed: {
    minTime() {
      if (!!this.form.timeStart) {
        const strTime = this.form.timeStart.split(':');
        const second = (+strTime[ 0 ]) * 60 * 60 + (+strTime[ 1 ]) * 60;
        const hh = (second / 3600) >> 0;//把秒除得时间
        const mm = (second % 3600) / 60 >> 0;//把余数用于除得分钟
        const ss = (second % 3600) % 60 >> 0;//最后的余数直接就是秒钟
        const tss = ss < 10 ? "0" + ss : ss + "";
        const tmm = mm < 10 ? "0" + mm : mm + "";
        const thh = hh < 10 ? "0" + hh : hh + "";
        return thh + ":" + tmm + ":" + tss;
      } else {
        return '00:00:00'
      }
    },
    maxTime() {
      if (!!this.form.timeEnd) {
        const strTime = this.form.timeEnd.split(':');
        const second = (+strTime[ 0 ]) * 60 * 60 + (+strTime[ 1 ]) * 60;
        const hh = (second / 3600) >> 0;//把秒除得时间
        const mm = (second % 3600) / 60 >> 0;//把余数用于除得分钟
        const ss = (second % 3600) % 60 >> 0;//最后的余数直接就是秒钟
        const tss = ss < 10 ? "0" + ss : ss + "";
        const tmm = mm < 10 ? "0" + mm : mm + "";
        const thh = hh < 10 ? "0" + hh : hh + "";
        return thh + ":" + tmm + ":" + tss;
      } else {
        return '23:59:59'
      }
    },
  }
};
</script>
<style lang="scss" scoped>
@import url('./assets/style/index.css');
/deep/.el-scrollbar__wrap {
  margin-right: -5px !important;
}
/deep/.el-form-item {
  margin-bottom: 28px;
  .el-form-item__label,
  .el-form-item__content {
    line-height: 22px;
    vertical-align: top;
    .pick-radio {
      height: 27px;
      .el-radio {
        line-height: 22px;
      }
    }
  }
}
.date_picker_item {
  display: inline-block;
  margin: 0 0 0 20px;
}
/deep/.el-date-editor {
  margin: -5px 0 0;
  vertical-align: top;
  // height: 22px;
}
.el-radio {
  margin-right: 0;
}
/deep/.el-input-number {
  width: 90px;
  .el-input-number__increase,
  .el-input-number__decrease {
    width: 20px;
    background: #fff;
  }
}
.long-input {
  width: 500px;
}
.textarea-input {
  padding-bottom: 23px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  /deep/ .el-textarea__inner {
    border: none;
  }
}
/deep/.el-textarea .el-input__count {
  bottom: 0 !important;
}
/deep/.el-radio-group {
  display: inline-block;
  vertical-align: middle;
  .el-radio-button {
    margin-right: 10px;
  }
  &:first-child .el-radio-button__inner,
  &:last-child .el-radio-button__inner {
    border-radius: 0 !important;
    border: 1px solid #dcdfe6 !important;
  }
}
.tips {
  color: #606266;
  font-size: 14px;
}
.sign-time {
  vertical-align: top;
  margin-bottom: -18px;
  .el-radio {
    margin: 0 0 18px;
    display: block;
  }
}
</style>
<style lang="scss">
.store-sign-timepicker {
  width: 158px;
  .el-input__inner {
    text-align: center;
    padding-right: 17px;
  }
}
</style>
