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

<template>
  <section class="common-right-wrap">
    <div class="new-card-body border-box">
      <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="142px" class="demo-ruleForm">
        <el-form-item label="卡券模板名称" prop="templateName">
          <limitInput :inputWidth="307" :inputValue.sync="formData.templateName" :getByType="'word'" :holder="'请输入卡券模板名称'" :maxLength="9"> </limitInput>
        </el-form-item>
        <el-form-item label="卡券类型" prop="cardType">
          <el-radio v-model="formData.cardType" label="0">抵金券</el-radio>
          <el-radio v-model="formData.cardType" label="1">折扣券</el-radio>
        </el-form-item>
        <el-form-item label="卡券适用渠道" prop="cardChannel">
          <el-radio v-model="formData.cardChannel" label="0">好办内购券</el-radio>
        </el-form-item>
        <el-form-item label="demo券号" prop="demoCardNum">
          <limitInput :inputWidth="307" :inputValue.sync="formData.demoCardNum" :getByType="'word'" :holder="'请输入demo券号'" :maxLength="200"> </limitInput>
        </el-form-item>
        <el-form-item label="卡券颜色" prop="cardColor">
          <div class="card-color flex flex-space-between">
            <span>{{ formData.cardColor }}</span>
            <el-color-picker v-model="formData.cardColor"></el-color-picker>
          </div>
        </el-form-item>
        <el-form-item label="减免金额" prop="cardMoney"> <el-input-number v-model="formData.cardMoney" controls-position="right" :min="1" :max="99999999"></el-input-number><span class="font-14 color-303133 p-l-10">元</span><span class="font-12 color-909399 p-l-10">输入大于0的整数</span> </el-form-item>
        <el-form-item label="最低适用商品件数" prop="cardMinNum">
          <el-radio v-model="formData.cardMinNum" label="0">不限</el-radio>
          <el-radio v-model="formData.cardMinNum" label="1">限制</el-radio><el-input-number v-if="formData.cardMinNum == 1" v-model="formData.cardMinLimit" controls-position="right" :min="1" :max="99999999"></el-input-number> <span v-if="formData.cardMinNum == 1" class="font-14 color-303133 p-l-10">件</span>
        </el-form-item>
        <el-form-item label="最高适用商品件数" prop="cardMaxNum">
          <el-radio v-model="formData.cardMaxNum" label="0">不限</el-radio>
          <el-radio v-model="formData.cardMaxNum" label="1">限制</el-radio><el-input-number v-if="formData.cardMaxNum == 1" v-model="formData.cardMaxLimit" controls-position="right" :min="1" :max="99999999"></el-input-number> <span v-if="formData.cardMaxNum == 1" class="font-14 color-303133 p-l-10">件</span>
        </el-form-item>
        <el-form-item label="适用条件" prop="minCostCheck">
          <div><el-checkbox v-model="formData.minCostCheck">最低消费</el-checkbox><el-input-number class="m-l-10" v-model="formData.minCost" controls-position="right" :min="1" :max="99999999"></el-input-number><span class="font-14 color-303133 p-l-10">元可用</span></div>
          <div><el-checkbox v-model="formData.fitGoodCheck">适用商品</el-checkbox><span class="font-14 color-909399">（至少填写一项）</span></div>
          <div class="fit-good border-box m-b-20">
            <div>
              <div class="m-b-20 flex"><span class="font-14 color-606266 w-86 m-r-10">适用商品：</span><limitInput :inputWidth="300" :inputValue.sync="formData.fitGoodDes" :getByType="'word'" :holder="'请输入内容'" :maxLength="18"> </limitInput></div>
              <div class="flex"><span class="font-14 color-606266 w-86 m-r-10">不适用商品：</span><limitInput :inputWidth="300" :inputValue.sync="formData.noFitGoodDes" :getByType="'word'" :holder="'请输入内容'" :maxLength="18"> </limitInput></div>
            </div>
          </div>
          <div><el-checkbox v-model="formData.shareCheck">不与其他优惠共享</el-checkbox></div>
        </el-form-item>
        <el-form-item label="领券限制" prop="cardLimit">
          <el-radio v-model="formData.cardLimit" label="0">1张/人</el-radio>
          <el-radio v-model="formData.cardLimit" label="1">100张/人</el-radio>
          <el-radio v-model="formData.cardLimit" label="2">自定义</el-radio><el-input-number v-if="formData.cardLimit == 2" v-model="formData.cardLimitNum" controls-position="right" :min="1" :max="99999999"></el-input-number> <span v-if="formData.cardLimit == 2" class="font-14 color-303133 p-l-10">张/人</span>
        </el-form-item>
        <el-form-item label="成本费用" prop="cardCost"> <el-input-number v-model="formData.cardCost" controls-position="right" :min="1" :max="99999999"></el-input-number><span class="font-14 color-303133 p-l-10">元</span><span class="font-12 color-909399 p-l-10">请填写大于0的数字（限制两位小数）</span> </el-form-item>
        <el-form-item label="code类型" prop="cardCodeType">
          <el-radio v-model="formData.cardCodeType" label="0">随机生成</el-radio>
        </el-form-item>
        <el-form-item label="适用门店说明" prop="cardFitDes">
          <limit-textarea :inputWidth="450" :inputValue.sync="formData.cardFitDes" :holder="'请输入适用门店说明'" :getByType="'word'" :maxLength="50"></limit-textarea>
        </el-form-item>
        <el-form-item label="适用门店" prop="cardFitStore">
          <el-radio v-model="formData.cardFitStore" label="0">所有门店</el-radio>
        </el-form-item>
        <el-form-item label="使用说明" prop="cardUseDes">
          <limit-textarea :inputWidth="450" :inputValue.sync="formData.cardUseDes" :holder="'请输入使用说明'" :getByType="'word'" :maxLength="500"></limit-textarea>
        </el-form-item>
        <el-form-item label="选择商户" prop="cardUseDes">
          <el-select class="" v-model="formData.activeBrand" placeholder="请选择">
            <el-option v-for="item in brandListData" :key="item.enterpriseId" :label="item.enterpriseName" :value="item.enterpriseId"> </el-option>
          </el-select>
        </el-form-item>
        <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>
  </section>
</template>
<script>
import limitInput from '@/components/limit-input.vue';
import limitTextarea from '@/components/limit-textarea.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,
    limitTextarea
  },
  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: '',
        templateName: '',
        cardType: '0',
        cardChannel: '0',
        demoCardNum: '',
        cardColor: '#2f54eb',
        cardMoney: '1',
        cardMinNum: '0',
        cardMinLimit: '1',
        cardMaxNum: '0',
        cardMaxLimit: '1',
        minCostCheck: false,
        minCost: '1',
        shareCheck: false,
        fitGoodCheck: false,
        fitGoodDes: '',
        noFitGoodDes: '',
        cardLimit: '0',
        cardLimitNum: '1',
        cardCost: '1',
        cardCodeType: '0',
        cardFitDes: '',
        cardFitStore: '0',
        cardUseDes: '',
        activeBrand: ''
      },
      rules: {
        templateName: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        sendRange: [{ validator: validateRange, trigger: 'change' }],
        sendType: [{ validator: validateSendType, trigger: 'change' }],
        // receiveType: [{ validator: validateReceiveType, trigger: 'change' }],
        cardMoney: [{ required: true, message: '请输入减免金额', trigger: 'blur' }],
        cardCost: [{ required: true, message: '请输入成本费用', trigger: 'blur' }],
        cardFitDes: [{ required: true, message: '请输入适用门店说明', trigger: 'blur' }],
        cardFitStore: [{ required: true, message: '请选择适用门店', trigger: 'change' }],
        cardUseDes: [{ required: true, message: '请输入使用说明', trigger: 'blur' }],
        activeBrand: [{ required: true, message: '请选择商户', trigger: 'change' }]
      },
      cardSelectShow: false,
      brandListData: []
    };
  },
  methods: {
    cancelEdit() {
      const that = this;
      that
        .$confirm('是否确认返回，返回后当前页面内容将丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.$router.go(-1);
        })
        .catch(() => {});
    },
    /**
     * 选择门店
     */
    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(`/cardTemplate`);
            } 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(`/cardTemplate`);
        })
        .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
          });
        });
    },
    /**
     * 获取品牌
     */
    getBrandData() {
      const that = this;
      postRequest('/haoban-manage3-web/wx-enterprise-list', {})
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.brandListData = resData.result || [];
            return;
          }
          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', '1');
    that.getBrandData();
    that.activeBrand = that.brandId;
    if (that.$route.query.coupCardId && that.brandId) {
      that.getCardData();
    }
  }
};
</script>
<style type="text/less" lang="less" scoped>
.w-307 {
  width: 307px;
}
.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-86 {
  width: 86px;
}
.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;
  }
}

.card-color {
  width: 110px;
  height: 32px;
  padding: 0 0 0 5px;
  border-radius: 2px;
  border: 1px solid rgba(196, 198, 207, 1);
  text-align: right;
  .el-color-picker {
    /deep/ .el-color-picker__trigger {
      border: none;
    }
  }
}
.fit-good {
  width: 424px;
  height: 125px;
  margin-left: 20px;
  background: rgba(245, 247, 250, 1);
  padding: 20px 20px 20px 10px;
}
</style>
