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

<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="coupCardId">
          <div v-if="!formData.coupCardId" class="card-add-btn text-center cursor-pointer" @click="showCard"><span class="el-icon-plus font-12 color-909399"></span><span class="font-14 color-909399">添加卡券</span></div>
          <div v-if="formData.coupCardId" class="selected-card-body flex">
            <div class="selected-card font-14 color-909399">{{ selectCoupCard.cardName }} | {{ selectCoupCard.effectDateString }} | 限制{{ selectCoupCard.cardLimit }}张/人 | 适用门店：{{ selectCoupCard.storeMode == 0 ? '所有门店' : selectCoupCard.storeMode == 1 ? '部分分组' : '部分门店' }} | 库存：{{ selectCoupCard.couponStock }}</div>
            <el-button class="m-l-10" type="text" @click="showCard">重新选择</el-button>
          </div>
        </el-form-item>
        <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.sendRange" label="0" @change="changeRange">所有门店</el-radio>
            <el-radio class="m-l-40 m-r-8" v-model="formData.sendRange" label="1" @change="changeRange">部分分组</el-radio>
            <div v-if="formData.sendRange == 1" class="w-240 inline-block item-cell-select">
              <gic-select-group :brandId="brandId" class="m-l-10" :width="213" :selectData="formData.selectList" @checkGroupIds="checkGroupIds"> </gic-select-group>
            </div>
            <el-radio class="m-l-40 m-r-8" v-model="formData.sendRange" label="2" @change="changeRange">部分门店</el-radio>
            <div v-if="formData.sendRange == 2" class="w-240 inline-block  item-cell-select">
              <gic-select-store :brandId="brandId" :selectData="formData.selectList" @returnStores="returnStores"> </gic-select-store>
            </div>
            <div v-if="(formData.sendRange == '1' || formData.sendRange == '2') && !formData.selectList.length" class="el-form-item__error">请选择发送范围</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-input-number class="w-90" v-model="formData.eachSendTimes" controls-position="right" :min="0" :max="20"></el-input-number><span class="font-14 color-c0c4cc p-l-20">最多20张每人</span></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.sendType" label="0">无限制</el-radio>
            <el-radio class="m-l-40" v-model="formData.sendType" label="1">限制总数</el-radio><el-input-number v-if="formData.sendType == 1" class="m-l-10" v-model="formData.totalSendTimes" controls-position="right" :min="1" :max="999999999"></el-input-number>
          </div>
        </div>
        <el-form-item>
          <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 v-if="cardSelectShow" :coupCardId="formData.coupCardId" :brandId="brandId" @closeCard="closeCard" @returnId="returnId"></select-card>
  </section>
</template>
<script>
import gicSelectStore from '@/components/common/gic-select-store.vue';
import gicSelectGroup from '@/components/common/gic-select-group.vue';
import selectCard from '@/components/app/card/select-card.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: {
    selectCard,
    gicSelectGroup,
    gicSelectStore
  },
  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: {
        id: '',
        coupCardId: '',
        sendRange: '0',
        selectList: [],
        eachSendTimes: 3,
        sendType: '0',
        totalSendTimes: 0
        // receiveType: '0',
        // totalReceiveTimes: 0
      },
      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
    };
  },
  methods: {
    /**
     * 选择门店
     */
    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;
      if ((that.formData.sendRange == '1' || that.formData.sendRange == '2') && !that.formData.selectList.length) {
        return false;
      }
      if (that.formData.sendType == '1' && !that.formData.totalSendTimes) {
        return false;
      }
      if (that.formData.receiveType == '1' && !that.formData.totalReceiveTimes) {
        return false;
      }
      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
          });
        });
    },
    toReturn() {
      const that = this;
      that
        .$confirm('是否确认返回，返回后当前页面内容将丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.$router.push(`/onlineChatSet?activeTab=${that.$route.query.activeTab}&appIcon=${that.$route.query.appIcon}`);
        })
        .catch(() => {});
    },

    /**
     * 改变选择范围
     */
    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', '3');
    that.activeBrand = that.brandId;
    if (that.$route.query.coupCardId) {
      that.getCardData();
    }
  }
};
</script>
<style type="text/less" lang="less" scoped>
.card-add-btn {
  width: 315px;
  height: 32px;
  line-height: 32px;
  background: rgba(255, 255, 255, 1);
  border-radius: 2px;
  border: 1px solid rgba(196, 198, 207, 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;
  }
}
</style>
