<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-04-13 15:27:46
 * @LastEditors: 无尘
 * @LastEditTime: 2020-04-22 16:57:49
 -->

<template>
  <section class="common-right-wrap">
    <div class="new-card-body border-box">
      <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="卡券策略名称" prop="cardStrategyName">
          <limitInput :inputWidth="340" :inputValue.sync="formData.cardStrategyName" :getByType="'word'" :holder="'请输入卡券策略名称'" :maxLength="20"> </limitInput>
        </el-form-item>
        <div class="item-title font-14 color-303133 font-w-600">卡券选择策略</div>
        <div class="el-form-item el-form-item--large is-required">
          <label for="name" class="el-form-item__label" style="width: 120px; cursor: pointer;">
            <el-tooltip class="item" effect="dark" content="支持多选，最多可选20个模板" placement="top-start"> <span style="cursor: pointer;padding-bottom: 2px; border-bottom: 1px dashed #2F54EB;">选择卡券模板</span></el-tooltip>
          </label>
          <div class="el-form-item__content" style="margin-left: 120px;">
            <div class="card-add-btn text-center cursor-pointer" @click="showCardTemp"><span class="font-14 color-606266">选择卡券模板</span></div>
            <div v-if="formData.cardTempData.length" class="m-t-20">
              <el-table class="select-table" height="450" :data="formData.cardTempData" tooltip-effect="dark" :style="{ width: '100%' }">
                <el-table-column label="卡券模板名称" show-overflow-tooltip>
                  <template slot-scope="scope">{{ scope.row.templateName }}</template>
                </el-table-column>
                <el-table-column prop="" label="卡券类型" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span v-if="scope.row.cardType == 0">抵金券</span>
                    <span v-if="scope.row.cardType == 1">折扣券</span>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="有效期" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.dataType" placeholder="">
                      <el-option label="固定日期" value="0"></el-option>
                      <el-option label="发送后" value="1"></el-option>
                    </el-select>
                    <el-date-picker v-if="scope.row.dataType == 0" class="m-l-10 m-r-10" prefix-icon="el-icon-time" :picker-options="pickerOptions" v-model="scope.row.dateRange" @change="changeDate" :editable="false" :value-format="'yyyy-MM-dd'" type="daterange" align="right" unlink-panels range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"> </el-date-picker>
                    <el-select v-if="scope.row.dataType == 1" v-model="scope.row.dateDay" placeholder="请选择"> <el-option v-for="item in dateOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option> </el-select><span class="font-14 color-606266 p-l-10" v-if="scope.row.dataType == 1">有效，有效天数</span><el-input-number v-if="scope.row.dataType == 1" v-model="scope.row.dateDayNum" controls-position="right" :min="1" :max="366"></el-input-number><span class="font-14 color-606266 p-l-10" v-if="scope.row.dataType == 1">天</span>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="发送总数" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.limitType" placeholder=""> <el-option label="限制总数" value="0"></el-option> </el-select><el-input-number v-model="scope.row.dateDayNum" controls-position="right" :min="1" :max="999999999"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="操作" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <el-button type="text" @click="toDelTemp(scope.$index, scope.row, formData.cardTempData)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <div class="item-title font-14 color-303133 font-w-600">执行策略</div>
        <div class="el-form-item el-form-item--large">
          <label for="name" class="el-form-item__label" style="width: 120px; cursor: pointer;">
            <el-tooltip class="item" effect="dark" content="卡券的发送范围设置" placement="top-start"> <span style="cursor: pointer;padding-bottom: 2px; border-bottom: 1px dashed #2F54EB;">发送范围</span></el-tooltip>
          </label>
          <div class="el-form-item__content" style="margin-left: 120px;">
            <el-radio v-model="formData.sendType" label="0" @change="changeSendType">全企业</el-radio><el-radio class="m-l-40" v-model="formData.sendType" label="1" @change="changeSendType"><span @click="clickSendType">部分部门</span></el-radio>
            <div v-if="formData.sendType == 0" class="position-select">
              <div class="position-check"><el-checkbox v-model="formData.filterCheck">按职务筛选</el-checkbox></div>
              <div class="position-check-tags">
                <el-checkbox v-model="formData.noPosition">无职务</el-checkbox>
                <el-tag :key="tag" v-for="tag in formData.filterData" closable :disable-transitions="false" @close="handleClose(tag)">
                  {{ tag }}
                </el-tag>
                <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" maxlength="20" show-word-limit @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm"> </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加职务</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="el-form-item el-form-item--large">
          <label for="name" class="el-form-item__label" style="width: 120px; cursor: pointer;">
            <el-tooltip class="item" effect="dark" content="每月该策略针对单一成员执行几次" placement="top-start"> <span style="cursor: pointer;padding-bottom: 2px; border-bottom: 1px dashed #2F54EB;">策略执行次数</span></el-tooltip>
          </label>
          <div class="el-form-item__content" style="margin-left: 120px;">
            <el-radio v-model="formData.executeType" label="0">每月循环</el-radio><el-radio v-model="formData.executeType" label="1">多月循环</el-radio>
            <div v-if="formData.executeType == 0"><span class="font-14 color-606266">每月</span><el-input-number v-model="formData.monthNum" controls-position="right" :min="1" :max="9999"></el-input-number></div>
            <div v-if="formData.executeType == 1">
              <span class="font-14 color-606266">第</span><el-select multiple v-model="formData.multMonth" placeholder="请选择"> <el-option v-for="item in monthOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option> </el-select><el-input-number v-model="formData.multMonthNum" controls-position="right" :min="1" :max="9999"></el-input-number>
            </div>
          </div>
        </div>
        <div class="el-form-item el-form-item--large">
          <label for="name" class="el-form-item__label" style="width: 120px; cursor: pointer;">
            策略有效期
          </label>
          <div class="el-form-item__content" style="margin-left: 120px;">
            <el-radio v-model="formData.vaildDateType" label="0">长期有效</el-radio><el-radio v-model="formData.vaildDateType" label="1">固定期限</el-radio>
            <div v-if="formData.vaildDateType == 1">
              <el-date-picker class="m-l-10 m-r-10" prefix-icon="el-icon-time" :picker-options="pickerOptions" v-model="formData.validDateRange" :editable="false" :value-format="'yyyy-MM-dd HH:mm:ss'" :default-time="['00:00:00', '23:59:59']" type="datetimerange" align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
            </div>
          </div>
        </div>
        <el-form-item>
          <el-button type="primary" @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确认{{ $route.query.coupCardId ? '编辑' : '新建' }}</el-button>
          <el-button type="primary" @click="submitForm('ruleForm', 'flag')">确认并继续新建</el-button>
        </el-form-item>
      </el-form>
    </div>
    <select-card-template v-if="cardTempShow" :selectTemp="formData.cardTempData" @returnData="returnData" @closeTemp="closeTemp"></select-card-template>
    <select-wx-depart v-if="departShow" :departArr="formData.departData" @refreshData="refreshData"></select-wx-depart>
  </section>
</template>
<script>
import limitInput from '@/components/limit-input.vue';
import selectCardTemplate from '@/components/app/protectCard/select-card-template.vue';
import selectWxDepart from '@/components/app/protectCard/select-wx-depart.vue';
import { getRequest, postRequest } from '@/api/api';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
export default {
  name: 'chat-log',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  components: {
    limitInput,
    selectCardTemplate,
    selectWxDepart
  },
  data() {
    const validateRange = (rule, value, callback) => {
      if (value == '') {
        return callback(new Error('请选择发送范围'));
      } else if ((value == '1' || value == '2') && !this.formData.selectList.length) {
        return callback(new Error('请选择发送范围'));
      } else {
        callback();
      }
    };
    const validateSendType = (rule, value, callback) => {
      if (value == '') {
        return callback(new Error('请选择券发放总数'));
      } else if (value == '1' && !this.formData.totalSendTimes) {
        return callback(new Error('请选择券发放总数'));
      } else {
        callback();
      }
    };
    /* const validateReceiveType = (rule, value, callback) => {
      if (value == '') {
        return callback(new Error('请选择券领取总数'));
      } else if (value == '1' && !this.formData.totallReceiveTimes) {
        return callback(new Error('请选择券领取总数'));
      } else {
        callback();
      }
    }; */
    return {
      activeBrand: this.brandId, // 商户(品牌) id
      activeGroup: this.activeGroupId, // 商户(品牌) groupId
      activeId: '3',
      wxEnterpriseId: localStorage.getItem('userInfos') ? JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId : '',
      selectCoupCard: {}, //已选卡券对象
      formData: {
        cardStrategyId: '',
        cardStrategyName: '',
        cardTempData: [
          {
            templateName: '',
            cardType: 0,
            dataType: 0,
            dateRange: [],
            dateDay: '',
            dateDayNum: '50000',
            limitType: 0,
            limitCount: ''
          }
        ],
        sendType: 0,
        filterCheck: false,
        noPosition: false,
        filterData: [],
        departData: [],
        executeType: 0,
        monthNum: '',
        multMonth: [],
        multMonthNum: '',
        vaildDateType: '',
        validDateRange: []
      },
      rules: {
        coupCardId: [{ required: true, message: '请选择卡券', trigger: 'change' }],
        sendRange: [{ validator: validateRange, trigger: 'change' }],
        sendType: [{ validator: validateSendType, trigger: 'change' }],
        // receiveType: [{ validator: validateReceiveType, trigger: 'change' }],
        eachSendTimes: [{ required: true, message: '请输入券发放张数', trigger: 'blur' }]
      },
      cardSelectShow: false,
      choiceDateCopy: [],
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.choiceDateCopy = [minDate.getTime()];
          if (maxDate) {
            this.choiceDateCopy = [];
          }
        },
        disabledDate: time => {
          if (this.choiceDateCopy.length) {
            const one = 365 * 24 * 3600 * 1000;
            const minTime = this.choiceDateCopy[0] - one;
            const maxTime = this.choiceDateCopy[0] + one;
            return time.getTime() < minTime || time.getTime() > maxTime || time.getTime() > Date.now() - 8.64e6;
          }
          return time.getTime() < Date.now() - 8.64e6;
        }
      },
      dateOptions: [],
      monthOptions: [],
      inputVisible: false,
      inputValue: '',
      cardTempShow: false,
      departShow: false
    };
  },
  methods: {
    /**
     *  修改发送类型
     */
    changeSendType() {
      const that = this;
      if (that.formData.sendType == 1) {
        that.departShow = true;
      } else {
        that.departShow = false;
      }
    },
    clickSendType() {
      const that = this;
      that.departShow = true;
    },
    refreshData(data) {
      const that = this;
      that.departShow = false;
      if (data == 'close') {
        return false;
      }
      that.formData.departData = data;
    },
    /**
     *  取消
     */
    cancelEdit() {
      const that = this;
      that
        .$confirm('是否确认返回，返回后当前页面内容将丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.$router.go(-1);
        })
        .catch(() => {});
    },
    /**
     *  选择卡券模板
     */
    showCardTemp() {
      const that = this;
      that.cardTempShow = true;
    },
    /**
     *  选择卡券模板弹窗返回数据
     */
    returnData(data) {
      const that = this;
      data.forEach(ele => {
        ele.dataType = 0;
        ele.dateRange = [];
        ele.dateDay = '';
        ele.dateDayNum = '50000';
        ele.limitType = 0;
        ele.limitCount = '';
      });
      that.formData.cardTempData = JSON.parse(JSON.stringify(data));
      that.cardTempShow = false;
    },
    /**
     *  选择卡券模板弹窗关闭
     */
    closeTemp() {
      const that = this;
      that.cardTempShow = false;
    },
    /**
     *  添加职务
     */
    handleClose(tag) {
      const that = this;
      that.formData.filterData.splice(that.formData.filterData.indexOf(tag), 1);
    },

    showInput() {
      const that = this;
      that.inputVisible = true;
      that.$nextTick(_ => {
        that.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      const that = this;
      let inputValue = that.inputValue;
      if (inputValue) {
        that.formData.filterData.push(inputValue);
      }
      that.inputVisible = false;
      that.inputValue = '';
    },
    /**
     *  删除已选卡券
     */
    toDelTemp(index, row, arr) {
      arr.splice(index, 1);
      // 还要把已选的卡券模板数据处理
    },
    /**
     *  第多少天处理
     */
    handleDay() {
      const that = this;
      let arr = [];
      for (let index = 0; index < 91; index++) {
        if (index == 0) {
          arr.push({
            label: `当天`,
            value: String(index)
          });
        } else {
          arr.push({
            label: `第${index}天`,
            value: String(index)
          });
        }
      }
      that.dateOptions = arr;
      that.monthOptions = [];
      for (let index = 1; index < 13; index++) {
        that.monthOptions.push({
          label: `${index}月`,
          value: String(index)
        });
      }
    },
    /**
     * 选择门店
     */
    returnStores: function(nodes) {
      const that = this;
      console.log('store:', nodes);
      that.formData.selectList = JSON.parse(JSON.stringify(nodes));
    },
    /**
     * 选择门店分组
     */
    checkGroupIds: function(nodes) {
      const that = this;
      console.log(nodes);
      that.formData.selectList = JSON.parse(JSON.stringify(nodes));
    },
    /**
     *  打开选择卡券
     */
    showCard() {
      const that = this;
      that.cardSelectShow = true;
    },
    /**
     *  closeCard
     */
    closeCard() {
      const that = this;
      that.cardSelectShow = false;
    },
    returnId(id, row) {
      const that = this;
      that.formData.coupCardId = id;
      that.selectCoupCard = row;
      that.cardSelectShow = false;
    },
    /**
     * 确认新建
     */
    submitForm: _debounce(function(formName, flag) {
      const that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postSaveCard(flag);
        }
      });
    }, 300),
    postSaveCard(flag) {
      const that = this;
      let para = {
        id: that.formData.id,
        coupCardId: that.formData.coupCardId,
        sendRange: that.formData.sendRange,
        selectList: that.formData.sendRange == 1 ? that.formData.selectList.map(item => item.storeGroupId).join(',') : that.formData.sendRange == 2 ? that.formData.selectList.join(',') : '',
        eachSendTimes: that.formData.eachSendTimes,
        sendType: that.formData.sendType,
        totalSendTimes: that.formData.totalSendTimes,
        // receiveType: that.formData.receiveType,
        // totalReceiveTimes: that.formData.totalReceiveTimes,
        gicEnterpriseId: that.brandId,
        wxEnterpriseId: that.wxEnterpriseId
      };
      postRequest(that.$route.query.coupCardId ? '/haoban-app-customer-web/cardCoupon/edit-card-coup' : '/haoban-app-customer-web/cardCoupon/add-card-coup', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg(that.$route.query.coupCardId ? '编辑卡券策略成功' : '新建卡券策略成功', 'success');
            if (!flag) {
              that.$router.push(`/cardList`);
            } else {
              that.formData = {
                id: '',
                coupCardId: '',
                sendRange: '0',
                selectList: [],
                eachSendTimes: 3,
                sendType: '0',
                totalSendTimes: 0
                // receiveType: '0',
                // totalReceiveTimes: 0
              };
              that.selectCoupCard = {};
            }
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 改变选择范围
     */
    changeRange(e) {
      const that = this;
      that.formData.selectList = [];
    },
    /**
     * 获取卡券策略数据
     */
    getCardData() {
      const that = this;
      let para = {
        coupCardId: that.$route.query.coupCardId,
        gicEnterpriseId: that.brandId
      };
      getRequest('/haoban-app-customer-web/cardCoupon/find-card-coup-detail', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (resData.result.list) {
              resData.result.list.forEach(ele => {
                ele.label = ele.name;
                ele.departmentId = ele.id; // 门店分组的时候
                ele.storeGroupId = ele.id; // 门店分组的时候
                ele.storeGroupName = ele.name;
                ele.departmentName = ele.name;
                resData.result.detail.sendRange == 2 ? (ele.storeId = ele.id) : '';
              });
            }
            that.selectCoupCard = resData.result.gicDetail;
            that.formData = {
              id: resData.result.detail.id,
              coupCardId: resData.result.detail.coupCardId,
              sendRange: String(resData.result.detail.sendRange),
              selectList: resData.result.detail.sendRange != 0 ? (resData.result.detail.sendRange == 2 ? resData.result.list.map(item => item.id) : resData.result.list) : [],
              eachSendTimes: resData.result.detail.eachSendTimes,
              sendType: String(resData.result.detail.sendType),
              totalSendTimes: resData.result.detail.totalSendTimes
              // receiveType: String(resData.result.detail.receiveType),
              // totalReceiveTimes: resData.result.detail.totalReceiveTimes
            };
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      if (!!newData && that.$route.query.coupCardId) {
        that.activeBrand = newData;
        that.getCardData();
      }
    },
    activeGroupId: function(newData, oldData) {
      const that = this;
      if (!!newData) {
        that.activeGroup = newData;
      }
    }
  },
  mounted() {
    const that = this;
    that.$emit('showTab', '2');
    that.$nextTick(() => {
      that.handleDay();
    });

    that.activeBrand = that.brandId;
    if (that.$route.query.coupCardId && that.brandId) {
      that.getCardData();
    }
  }
};
</script>
<style type="text/less" lang="less" scoped>
.card-add-btn {
  width: 143px;
  height: 32px;
  border: 1px solid rgba(192, 196, 204, 1);
}
.selected-card {
  height: 32px;
  line-height: 32px;
  text-align: center;
  padding: 0 15px;
  background: rgba(245, 247, 250, 1);
  border-radius: 2px;
}
.new-card-body {
  padding: 30px;
}
.w-240 {
  width: 240px;
}
.w-90 {
  width: 90px;
}
.m-l-40 {
  margin-left: 40px;
}
.m-r-8 {
  margin-right: 8px;
}
.depart-item-content {
  width: 213px;
  height: 32px;
  overflow: hidden;
  white-space: nowrap;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  .el-select__tags {
    overflow: hidden;
    white-space: nowrap;
  }
}

.el-form-item.is-error {
  /deep/ .el-input__inner {
    border-color: #dcdfe6;
    &:focus {
      border-color: #dcdfe6;
    }
  }
}

.w-103 {
  width: 103px;
}
.w-369 {
  width: 369px;
}
.el-input {
  /deep/ .el-input-group__prepend {
    background-color: #fff;
  }
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  min-width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
