<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-04-13 15:27:46
 * @LastEditors: 无尘
 * @LastEditTime: 2020-08-27 10:39:53
 -->

<template>
  <section class="common-right-wrap" v-loading="loadingPage">
    <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="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>
          <div v-else 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 p-l-8">添加卡券</span></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" style="margin-left: 38px;" 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>
            <el-radio class="m-l-40 m-r-8" style="margin-left: 38px;" v-model="formData.sendRange" label="3" @change="changeRange">门店标签</el-radio>
            <div v-if="formData.sendRange == 3" class="w-240 inline-block  item-cell-select">
              <gic-select-tag :brandId="brandId" :selectData="formData.selectList" @returnTags="returnTags"> </gic-select-tag>
            </div>
            <div v-if="(formData.sendRange == '1' || formData.sendRange == '2' || formData.sendRange == '3') && !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" :precision="0" step-strictly :step="1" :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" :precision="0" step-strictly :step="1" :min="1" :max="999999999"></el-input-number>
            <div v-if="formData.sendType == 1 && !formData.totalSendTimes" class="el-form-item__error">
              请选择券发放总数
            </div>
          </div>
        </div> -->
        <!--<el-form-item label="转赠功能" prop="">
          <el-switch v-model="formData." active-text="" inactive-text=""> </el-switch>
        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" :loading="loadingBtn" @click="submitForm('ruleForm')">确认{{ $route.query.coupCardId && !addTag ? '编辑' : '新建' }}</el-button>
          <el-button v-if="!$route.query.coupCardId" 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 gicSelectTag from '@/components/app/card/gic-select-tag.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,
    gicSelectTag
  },
  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: {}, //已选卡券对象
      loadingPage: true,
      formData: {
        id: '',
        coupCardId: this.$route.query.coupCardId ? this.$route.query.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,
      addTag: true, // 默认是添加
      loadingBtn: false
    };
  },
  methods: {
    /**
     * 选择门店标签
     */
    returnTags: function(nodes) {
      const that = this;
      that.formData.selectList = JSON.parse(JSON.stringify(nodes));
    },
    /**
     * 选择门店
     */
    returnStores: function(nodes) {
      const that = this;
      that.formData.selectList = JSON.parse(JSON.stringify(nodes));
    },
    /**
     * 选择门店分组
     */
    checkGroupIds: function(nodes) {
      const that = this;
      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;
      that.$refs['ruleForm'].validate(valid => {
        if (valid) {
          return false;
        }
      });
    },
    /**
     * 确认新建
     */
    submitForm: _debounce(function(formName, flag) {
      const that = this;
      if ((that.formData.sendRange == '1' || that.formData.sendRange == '2' || that.formData.sendRange == '3') && !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.loadingBtn = true;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postSaveCard(flag);
        } else {
          that.loadingBtn = false;
        }
      });
    }, 300),
    postSaveCard(flag) {
      const that = this;
      let selectList = '';
      if (that.formData.sendRange == 1) {
        selectList = that.formData.selectList.map(item => item.storeGroupId).join(',');
      } else if (that.formData.sendRange == 2) {
        selectList = that.formData.selectList.join(',');
      } else if (that.formData.sendRange == 3) {
        selectList = that.formData.selectList.map(item => item.tagId).join(',');
      }
      let para = {
        id: that.formData.id,
        coupCardId: that.formData.coupCardId,
        sendRange: that.formData.sendRange,
        selectList: selectList,
        // eachSendTimes: that.formData.eachSendTimes || '0',
        // 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 && !that.addTag ? '/haoban-app-customer-web/cardCoupon/edit-card-coup' : '/haoban-app-customer-web/cardCoupon/add-card-coup', para)
        .then(res => {
          let resData = res.data;
          that.loadingBtn = false;
          if (resData.errorCode == 1) {
            showMsg.showmsg(that.$route.query.coupCardId ? '编辑卡券成功' : '新建卡券成功', 'success');
            if (!flag) {
              that.$router.push(`/cardList`);
            } else {
              // 编辑的时候确认没有新增
              that.addTag = true;
              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.loadingBtn = false;
          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;
      that.loadingPage = true;
      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.detail) {
              that.loadingPage = false;
              that.addTag = false;
              showMsg.showmsg('请先保存上一个商户的设置内容', 'warning');
              return false;
            }
            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) : '';
                // 门店标签
                if (resData.result.detail.sendRange == 3) {
                  ele.tagName = ele.name;
                  ele.tagId = 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
            };
            that.loadingPage = false;
            return false;
          }
          if (resData.errorCode == 100013) {
            that.formData.coupCardId = '';
            that.addTag = true;
          }
          that.loadingPage = false;
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loadingPage = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      if (!!newData && that.$route.query.coupCardId) {
        that.addTag = false;
      }
      if (!!newData && that.$route.query.coupCardId && !that.addTag) {
        that.activeBrand = newData;
        that.getCardData();
        return false;
      }
      if (!!newData) {
        // that.getCardData();
        that.addTag = true;
        that.formData = {
          id: '',
          coupCardId: '',
          sendRange: '0',
          selectList: [],
          eachSendTimes: 3,
          sendType: '0',
          totalSendTimes: 0
          // receiveType: '0',
          // totalReceiveTimes: 0
        };
        that.selectCoupCard = {};
      }
    },
    activeGroupId: function(newData, oldData) {
      const that = this;
      if (!!newData) {
        that.activeGroup = newData;
      }
    }
  },
  mounted() {
    const that = this;
    that.activeBrand = that.brandId;
    if (that.$route.query.coupCardId && that.brandId) {
      that.$emit('showTab', '1', '11');
      that.addTag = false;
      that.getCardData();
    } else {
      that.$emit('showTab', '1', '12');
      that.loadingPage = false;
    }
  }
};
</script>
<style type="text/scss" lang="scss" scoped>
.card-add-btn {
  width: 315px;
  height: 32px;
  line-height: 32px;
  background: rgba(255, 255, 255, 1);
  border-radius: 2px;
  border: 1px dashed rgba(196, 198, 207, 1);
  &:hover {
    border-color: #2f54eb;
    span {
      color: #2f54eb;
    }
  }
}
.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;
  .el-form {
    .el-form-item {
      margin-bottom: 50px;
    }
  }
}
.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 {
  >>> .el-input__inner {
    border-color: #dcdfe6;
    &:focus {
      border-color: #dcdfe6;
    }
  }
}

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