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

<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="6"> </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="gicEnterpriseId">
          <el-select class="" v-model="formData.gicEnterpriseId" placeholder="请选择" @change="changeEnterprise">
            <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 label="卡券适用渠道" prop="cardApplicationChannel">
          <!-- <el-radio v-model="formData.cardApplicationChannel" label="1">线下门店</el-radio>
          <el-radio v-model="formData.cardApplicationChannel" label="2">微盟微商城</el-radio>
          <el-radio v-model="formData.cardApplicationChannel" label="3">GIC微商城</el-radio> -->
          <el-checkbox-group v-model="formData.cardApplicationChannel">
            <el-checkbox v-for="(item, index) in chanelList" :key="index + 'chanel'" :label="item.value">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </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 v-if="formData.cardType == 0" 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 v-if="formData.cardType == 1" label="折扣额度" prop="cardDenomination"> <el-input-number v-model="formData.cardDenomination" controls-position="right" :precision="1" :min="1" :max="9.9" :step="0.1"></el-input-number><span class="font-14 color-303133 p-l-10">折</span><span class="font-12 color-909399 p-l-10">请填写1-9.9之间的数字</span> </el-form-item>
        <el-form-item v-if="formData.cardType == 1" label="优惠金额封顶" prop="">
          <el-radio v-model="formData.limitTopType" label="0" @change="changeTop">不封顶</el-radio>
          <el-radio v-model="formData.limitTopType" label="1">限制封顶</el-radio><el-input-number v-if="formData.limitTopType == 1" v-model="formData.limitTop" controls-position="right" :min="1" :max="99999999"></el-input-number> <span v-if="formData.limitTopType == 1" class="font-14 color-303133 p-l-10">元</span>
        </el-form-item>
        <el-form-item label="最低适用商品件数" prop="minGoodsType">
          <el-radio v-model="formData.minGoodsType" label="0">不限</el-radio>
          <el-radio v-model="formData.minGoodsType" label="1">限制</el-radio><el-input-number v-if="formData.minGoodsType == 1" v-model="formData.minApplicableGoods" controls-position="right" :min="1" :max="99999999"></el-input-number> <span v-if="formData.minGoodsType == 1" class="font-14 color-303133 p-l-10">件</span>
        </el-form-item>
        <el-form-item label="最高适用商品件数" prop="maxGoodsType">
          <el-radio v-model="formData.maxGoodsType" label="0">不限</el-radio>
          <el-radio v-model="formData.maxGoodsType" label="1">限制</el-radio><el-input-number v-if="formData.maxGoodsType == 1" v-model="formData.maxApplicableGoods" controls-position="right" :min="1" :max="99999999"></el-input-number> <span v-if="formData.maxGoodsType == 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" :precision="2" :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>
          <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() {
    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 : '',

      formData: {
        templateId: '',
        templateName: '',
        cardType: '0',
        cardApplicationChannel: ['offlineStore'],
        erpDemoCode: '',
        cardColor: '#2f54eb',
        cardDenomination: '1',
        minGoodsType: '0',
        minApplicableGoods: '1',
        maxGoodsType: '0',
        maxApplicableGoods: '1',
        useCondition: {
          sale_limit: { fee: 1 },
          goods: { ok: '', no: '' },
          only: 1,
          discount_amount_upper_limit: 0,
          goods_discounts_number_upper_limit: '1',
          goods_discounts_number_lower_limit: '1'
        },
        limitTopType: '0', // 优惠金额封顶
        limitTop: 0,
        minCostCheck: false,
        minCost: '1',
        shareCheck: false,
        fitGoodCheck: false,
        fitGoodDes: '',
        noFitGoodDes: '',

        cardLimitType: '0',
        cardLimit: '1',
        costValue: '1',
        useCustomCode: '0',
        cardExplain: '',
        applicationStoreType: '1',
        useDescript: '',
        gicEnterpriseId: ''
      },
      rules: {
        templateName: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        cardApplicationChannel: [{ type: 'array', required: true, message: '请至少选择一个卡券适用渠道', 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: [],
      chanelList: []
    };
  },
  methods: {
    /**
     *  选择商户改变渠道
     */
    changeEnterprise() {
      const that = this;
      that.formData.cardApplicationChannel = [];
      that.getChanel();
    },
    getChanel() {
      const that = this;
      let para = {
        gicEnterpriseId: that.formData.gicEnterpriseId
      };
      getRequest('/haoban-app-customer-web/inner/get-channel-type', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.chanelList = resData.result || [];
            if (!!resData.result.length) {
              that.formData.cardApplicationChannel = [resData.result[0].value];
            }
          }
          return false;

          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     *  封顶设置
     */
    changeTop(e) {
      const that = this;
      if (e == 0) {
        that.formData.limitTop = 0;
      }
    },
    cancelEdit() {
      const that = this;
      that
        .$confirm('是否确认返回，返回后当前页面内容将丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.$router.go(-1);
        })
        .catch(() => {});
    },
    /**
     * 确认新建
     */
    submitForm: _debounce(function(formName, flag) {
      const that = this;
      if (that.formData.fitGoodCheck && !that.formData.fitGoodDes && that.formData.noFitGoodDes) {
        that.$message.error({
          duration: 1000,
          message: '适用商品至少填写一项'
        });
        return false;
      }
      if (that.formData.minCostCheck && !that.formData.minCost) {
        that.$message.error({
          duration: 1000,
          message: '请输入最低消费'
        });
        return false;
      }
      if (that.formData.limitTopType == 1 && !that.formData.limitTop) {
        that.$message.error({
          duration: 1000,
          message: '请输入封顶金额'
        });
        return false;
      }
      if (that.formData.minGoodsType == 1 && !that.formData.minApplicableGoods) {
        that.$message.error({
          duration: 1000,
          message: '请输入最低适用商品件数'
        });
        return false;
      }
      if (that.formData.maxGoodsType == 1 && !that.formData.maxApplicableGoods) {
        that.$message.error({
          duration: 1000,
          message: '请输入最高适用商品件数'
        });
        return false;
      }
      if (that.formData.cardLimitType == 2 && !that.formData.cardLimit) {
        that.$message.error({
          duration: 1000,
          message: '请输入领券限制'
        });
        return false;
      }
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postSaveCard(flag);
        }
      });
    }, 300),
    postSaveCard(flag) {
      const that = this;
      let useCondition = {
        sale_limit: { fee: 0 },
        goods: { ok: that.formData.fitGoodDes, no: that.formData.noFitGoodDes },
        only: that.formData.shareCheck ? 1 : 0,
        discount_amount_upper_limit: that.formData.limitTopType == 1 ? that.formData.limitTop : 0,
        goods_discounts_number_upper_limit: that.formData.minGoodsType == 1 ? that.formData.minApplicableGoods : 0,
        goods_discounts_number_lower_limit: that.formData.maxGoodsType == 1 ? that.formData.maxApplicableGoods : 0
      };
      if (that.formData.minCostCheck) {
        useCondition.sale_limit = {
          fee: that.formData.minCost
        };
      }
      let para = {
        templateId: that.formData.templateId,
        templateName: that.formData.templateName,
        cardType: that.formData.cardType,
        cardApplicationChannel: that.formData.cardApplicationChannel.join(','),
        erpDemoCode: that.formData.erpDemoCode,
        cardColor: that.formData.cardColor,
        cardDenomination: that.formData.cardDenomination,
        minGoodsType: that.formData.minGoodsType,
        minApplicableGoods: that.formData.minApplicableGoods,
        maxGoodsType: that.formData.maxGoodsType,
        maxApplicableGoods: that.formData.maxApplicableGoods,
        limitTopType: that.formData.limitTopType, // 优惠金额封顶
        limitTop: that.formData.limitTop,
        useCondition: JSON.stringify(useCondition),
        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: [],
                erpDemoCode: '',
                cardColor: '#2f54eb',
                cardDenomination: '1',
                minGoodsType: '0',
                minApplicableGoods: '1',
                maxGoodsType: '0',
                maxApplicableGoods: '1',
                useCondition: {
                  sale_limit: { fee: 1 },
                  goods: { ok: '', no: '' },
                  only: 1,
                  discount_amount_upper_limit: 0,
                  goods_discounts_number_upper_limit: '1',
                  goods_discounts_number_lower_limit: '1'
                },
                limitTopType: '0', // 优惠金额封顶
                limitTop: 0,
                minCostCheck: false,
                minCost: '1',
                shareCheck: false,
                fitGoodCheck: false,
                fitGoodDes: '',
                noFitGoodDes: '',

                cardLimitType: '0',
                cardLimit: '1',
                costValue: '1',
                useCustomCode: '0',
                cardExplain: '',
                applicationStoreType: '1',
                useDescript: '',
                gicEnterpriseId: that.brandListData[0].enterpriseId
              };
              that.getChanel();
            }
          }
          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
      };
      getRequest('/haoban-app-customer-web/inner/find-template', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            const useCondition = JSON.parse(resData.result.useCondition);

            that.formData = {
              templateId: resData.result.templateId,
              templateName: resData.result.templateName,
              cardType: String(resData.result.cardType),
              cardApplicationChannel: resData.result.cardApplicationChannel.split(',') || [],
              erpDemoCode: resData.result.erpDemoCode,
              cardColor: resData.result.cardColor,
              cardDenomination: resData.result.cardDenomination,
              limitTopType: String(resData.result.limitTopType),
              limitTop: resData.result.limitTop,
              minGoodsType: String(resData.result.minGoodsType),
              minApplicableGoods: resData.result.minApplicableGoods,
              maxGoodsType: String(resData.result.maxGoodsType),
              maxApplicableGoods: resData.result.maxApplicableGoods,
              minCostCheck: !!useCondition.sale_limit.fee ? true : false,
              minCost: !!useCondition.sale_limit.fee ? useCondition.sale_limit.fee : '1',
              shareCheck: !!useCondition.only ? true : false,
              fitGoodCheck: !!useCondition.goods.ok || !!useCondition.goods.no ? true : false,
              fitGoodDes: useCondition.goods.ok,
              noFitGoodDes: useCondition.goods.no,
              cardLimitType: String(resData.result.cardLimitType),
              cardLimit: resData.result.cardLimit,
              costValue: resData.result.costValue,
              useCustomCode: String(resData.result.useCustomCode),
              cardExplain: resData.result.cardExplain,
              applicationStoreType: String(resData.result.applicationStoreType),
              useDescript: resData.result.useDescript,
              gicEnterpriseId: resData.result.gicEnterpriseId
            };
            that.getChanel();
            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 || [];
            if (resData.result.length) {
              that.formData.gicEnterpriseId = resData.result[0].enterpriseId;
              that.getChanel();
            }
            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>
