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

<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="cardApplicationChannel">
          <el-radio v-model="formData.cardApplicationChannel" label="1">好办内购券</el-radio>
        </el-form-item>
        <el-form-item label="demo券号" prop="erpDemoCode">
          <limitInput :inputWidth="307" :inputValue.sync="formData.erpDemoCode" :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="cardDenomination"> <el-input-number v-model="formData.cardDenomination" 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="minGoodType">
          <el-radio v-model="formData.minGoodType" label="0">不限</el-radio>
          <el-radio v-model="formData.minGoodType" label="1">限制</el-radio><el-input-number v-if="formData.minGoodType == 1" v-model="formData.minApplicableGoods" controls-position="right" :min="1" :max="99999999"></el-input-number> <span v-if="formData.minGoodType == 1" class="font-14 color-303133 p-l-10">件</span>
        </el-form-item>
        <el-form-item label="最高适用商品件数" prop="maxGoodType">
          <el-radio v-model="formData.maxGoodType" label="0">不限</el-radio>
          <el-radio v-model="formData.maxGoodType" label="1">限制</el-radio><el-input-number v-if="formData.maxGoodType == 1" v-model="formData.maxApplicableGoods" controls-position="right" :min="1" :max="99999999"></el-input-number> <span v-if="formData.maxGoodType == 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="cardLimitType">
          <el-radio v-model="formData.cardLimitType" label="0">1张/人</el-radio>
          <el-radio v-model="formData.cardLimitType" label="1">100张/人</el-radio>
          <el-radio v-model="formData.cardLimitType" label="2">自定义</el-radio><el-input-number v-if="formData.cardLimitType == 2" v-model="formData.cardLimit" controls-position="right" :min="1" :max="99999999"></el-input-number> <span v-if="formData.cardLimitType == 2" class="font-14 color-303133 p-l-10">张/人</span>
        </el-form-item>
        <el-form-item label="成本费用" prop="costValue"> <el-input-number v-model="formData.costValue" 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="useCustomCode">
          <el-radio v-model="formData.useCustomCode" label="0">随机生成</el-radio>
        </el-form-item>
        <el-form-item label="适用门店说明" prop="cardExplain">
          <limit-textarea :inputWidth="450" :inputValue.sync="formData.cardExplain" :holder="'请输入适用门店说明'" :getByType="'word'" :maxLength="50"></limit-textarea>
        </el-form-item>
        <el-form-item label="适用门店" prop="applicationStoreType">
          <el-radio v-model="formData.applicationStoreType" label="1">所有门店</el-radio>
        </el-form-item>
        <el-form-item label="使用说明" prop="useDescript">
          <limit-textarea :inputWidth="450" :inputValue.sync="formData.useDescript" :holder="'请输入使用说明'" :getByType="'word'" :maxLength="500"></limit-textarea>
        </el-form-item>
        <el-form-item label="选择商户" prop="gicEnterpriseId">
          <el-select class="" v-model="formData.gicEnterpriseId" 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.templateId ? '编辑' : '新建' }}</el-button>
          <el-button v-if="!$route.query.templateId" 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',
      commitName: !!localStorage.getItem('userInfos') && !!JSON.parse(localStorage.getItem('userInfos')).staffDTO ? JSON.parse(localStorage.getItem('userInfos')).staffDTO.staffName : '',
      wxEnterpriseId: localStorage.getItem('userInfos') ? JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId : '',
      selectCoupCard: {}, //已选卡券对象
      formData: {
        templateId: '',
        templateName: '',
        cardType: '0',
        cardApplicationChannel: '0',
        erpDemoCode: '',
        cardColor: '#2f54eb',
        cardDenomination: '1',
        minGoodType: '0',
        minApplicableGoods: '1',
        maxGoodType: '0',
        maxApplicableGoods: '1',
        minCostCheck: false,
        minCost: '1',
        shareCheck: false,
        fitGoodCheck: false,
        fitGoodDes: '',
        noFitGoodDes: '',
        cardLimitType: '0',
        cardLimit: '1',
        costValue: '1',
        useCustomCode: '0',
        cardExplain: '',
        applicationStoreType: '0',
        useDescript: '',
        gicEnterpriseId: ''
      },
      rules: {
        templateName: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        sendRange: [{ validator: validateRange, trigger: 'change' }],
        sendType: [{ validator: validateSendType, trigger: 'change' }],
        // receiveType: [{ validator: validateReceiveType, trigger: 'change' }],
        cardDenomination: [{ required: true, message: '请输入减免金额', trigger: 'blur' }],
        costValue: [{ required: true, message: '请输入成本费用', trigger: 'blur' }],
        cardExplain: [{ required: true, message: '请输入适用门店说明', trigger: 'blur' }],
        applicationStoreType: [{ required: true, message: '请选择适用门店', trigger: 'change' }],
        useDescript: [{ required: true, message: '请输入使用说明', trigger: 'blur' }],
        gicEnterpriseId: [{ 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.templateId = 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 = {
        templateId: that.formData.templateId,
        templateName: that.formData.templateName,
        cardType: that.formData.cardType,
        cardApplicationChannel: that.formData.cardApplicationChannel,
        erpDemoCode: that.formData.erpDemoCode,
        cardColor: that.formData.cardColor,
        cardDenomination: that.formData.cardDenomination,
        minGoodType: that.formData.minGoodType,
        minApplicableGoods: that.formData.minApplicableGoods,
        maxGoodType: that.formData.maxGoodType,
        maxApplicableGoods: that.formData.maxApplicableGoods,
        minCostCheck: false,
        minCost: '1',
        shareCheck: false,
        fitGoodCheck: false,
        fitGoodDes: '',
        noFitGoodDes: '',
        cardLimitType: that.formData.cardLimitType,
        cardLimit: that.formData.cardLimit,
        costValue: that.formData.costValue,
        useCustomCode: that.formData.useCustomCode,
        cardExplain: that.formData.cardExplain,
        applicationStoreType: that.formData.applicationStoreType,
        useDescript: that.formData.useDescript,
        gicEnterpriseId: that.formData.gicEnterpriseId,
        commitName: that.commitName,
        wxEnterpriseId: that.wxEnterpriseId
      };
      postRequest(that.$route.query.templateId ? '/haoban-app-customer-web/inner/save-template' : '/haoban-app-customer-web/inner/save-template', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg(that.$route.query.templateId ? '编辑卡券模板成功' : '新建卡券模板成功', 'success');
            if (!flag) {
              that.$router.push(`/cardTemplate`);
            } else {
              that.formData = {
                templateId: '',
                templateName: '',
                cardType: '0',
                cardApplicationChannel: '0',
                erpDemoCode: '',
                cardColor: '#2f54eb',
                cardDenomination: '1',
                minGoodType: '0',
                minApplicableGoods: '1',
                maxGoodType: '0',
                maxApplicableGoods: '1',
                minCostCheck: false,
                minCost: '1',
                shareCheck: false,
                fitGoodCheck: false,
                fitGoodDes: '',
                noFitGoodDes: '',
                cardLimitType: '0',
                cardLimit: '1',
                costValue: '1',
                useCustomCode: '0',
                cardExplain: '',
                applicationStoreType: '0',
                useDescript: '',
                gicEnterpriseId: ''
              };
              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 = {
        templateId: that.$route.query.templateId,
        gicEnterpriseId: that.brandId
      };
      getRequest('/haoban-app-customer-web/inner/find-template', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.formData = {
              templateId: resData.result.templateId,
              templateName: resData.result.templateName,
              cardType: resData.result.cardType,
              cardApplicationChannel: resData.result.cardApplicationChannel,
              erpDemoCode: resData.result.erpDemoCode,
              cardColor: resData.result.cardColor,
              cardDenomination: resData.result.cardDenomination,
              minGoodType: resData.result.minGoodType,
              minApplicableGoods: resData.result.minApplicableGoods,
              maxGoodType: resData.result.maxGoodType,
              maxApplicableGoods: resData.result.maxApplicableGoods,
              minCostCheck: false,
              minCost: '1',
              shareCheck: false,
              fitGoodCheck: false,
              fitGoodDes: '',
              noFitGoodDes: '',
              cardLimitType: resData.result.cardLimitType,
              cardLimit: resData.result.cardLimit,
              costValue: resData.result.costValue,
              useCustomCode: resData.result.useCustomCode,
              cardExplain: resData.result.cardExplain,
              applicationStoreType: resData.result.applicationStoreType,
              useDescript: resData.result.useDescript,
              gicEnterpriseId: resData.result.gicEnterpriseId
            };
            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.templateId) {
        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();
    if (that.$route.query.templateId) {
      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>
