<template>
  <div class="right-wrap">
    <topNav :navpath="navpath"></topNav>
    <div class="right-content">
      <div class="right-box">
        <div class="attention-wrap">
          <div class="form-wrap">
            <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="策略名称" prop="" class="padding-0">
                 <el-input v-model="ruleForm.strategyName" class="w-340 padding-0" @keyup.native="(value) => toInput(value)">
                    <!-- <template slot="append"></template> -->
                 </el-input>
                 <label class="input-label">{{cateNameLength}}/20</label>
              </el-form-item>
              <el-form-item label="适用对象" prop="" class="margin-20">
                  <el-select v-model="ruleForm.useCrowd" placeholder="请选择">
                    <el-option
                      v-for="item in applyObjOption"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
              </el-form-item>

              <el-form-item label="人群定向" v-if="ruleForm.useCrowd==2" prop="" class="padding-0">
                <el-button>已设置0项筛选</el-button>
              </el-form-item>
              <el-form-item label="适用条件" class="padding-0">
                <div class="title-tip">该设置只对微信商城中的积分抵现起作用。</div>
              </el-form-item>
              <!-- 只获取微信的 -->
              <template v-for="(item,index) in ruleForm.channelList">
                <template v-if="item.channelType==1">
                  <div class="form-child margin-20 " >
                    <el-form-item label="选择商户">
                      <el-select v-model="item.enterpriseRelationIdArr" placeholder="请选择" multiple >
                        <el-option
                          v-for="item in mechantOption"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>

                    <el-form-item label="适用商品" class="padding-0">
                      <el-select v-model="item.channelRelationProType" placeholder="请选择"  @change="changeGood($event)">
                        <el-option
                          v-for="item in applyGoods"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                      <!-- 二级 -->
                       <span class="span-txt" ref="treeinput" v-if="item.channelRelationProType == 2" @click="toggle('wx')">已选择 {{item.strategyGoodsRelationIdArr? item.strategyGoodsRelationIdArr.length:0}} 个品牌 </span>
                      <span class="span-txt" ref="treeinput" v-if="item.channelRelationProType == 3" @click="toggle('wx')">已选择 {{item.strategyGoodsRelationIdArr? item.strategyGoodsRelationIdArr.length:0}} 个品类 </span>
                      <treeselect
                      v-if="item.channelRelationProType == 2||item.channelRelationProType == 3"
                      placeholder=""
                      noOptionsText="暂无数据"
                      noResultsText="无数据"
                      :multiple="true"
                      :options="treeOptions"
                      :always-open="wxOpen"
                      :value-consists-of="valueConsistsOf"
                      v-model="item.strategyGoodsRelationIdArr"
                      />
                      <el-button v-if="item.channelRelationProType == 4" @click="showGoodsDialog">已选0件商品</el-button>

                    </el-form-item>
                    <el-form-item label="折扣控制" prop="region">
                      <div class="radio-cell">
                        <el-radio  v-model="item.integralUseDiscountControl" label="1">所有折扣商品都适用</el-radio>
                      </div>
                      <div class="radio-cell margin-20" >
                        <el-radio v-model="item.integralUseDiscountControl"  label="2">折扣率</el-radio>
                        <el-input v-model="item.integralUseDiscountControlLower"></el-input>
                        <label>至</label>
                        <el-input v-model="item.integralUseDiscountControlUpper"></el-input>
                        <!-- <label>商品都适用</label> -->
                      </div>
                    </el-form-item>
                  </div>
                </template>
              </template>

              <el-form-item label="抵现规则" prop="" class="margin-20">
                <div>
                  <el-radio v-model="ruleForm.integralUseStatus" label="1">每使用</el-radio>
                  <el-input v-model="ruleForm.integralUse.integral"></el-input><label>积分,抵 </label>
                  <el-input v-model="ruleForm.integralUse.fee"></el-input><label>元</label>
                </div>
                <div>
                  <el-radio v-model="ruleForm.integralUseStatus" label="0" class="margin-20">不支持抵现</el-radio>
                </div>
              </el-form-item>
              <el-form-item label="比例限制" prop="name">
                  <label>最多可抵用商品金额的 </label>
                  <el-input v-model="ruleForm.channelList[0].useProportionalRestriction"><template slot="append">%</template></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">保 存</el-button>
                <el-button @click="goBack">返 回</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <vue-gic-footer></vue-gic-footer>
    <!-- 添加商品 -->
    <add-goods :goodShow="goodShow" :projectName="repProjectName" @selectGoods="selectGoods"></add-goods>
  </div>
</template>
<script>
import topNav from 'components/nav/nav'
import addGoods from 'components/memberShip/add-goods'
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import showMsg from '@/common/js/showmsg';
import errMsg  from '@/common/js/error';
import strLength from '@/common/js/strlen';

import { getRequest, postRequest, postJsonRequest, postJson, postForm } from '@/api/api';

export default {
  name: "addIntegralSytem",
  data() {
    return {
      repProjectName: 'gic-clique',
      navpath: [{
          name: '首页',
          path: '/'
        },
        {
          name: '添加积分抵现策略',
          path: ''
        }
      ],
      // 添加商品弹窗
      goodShow: false,

      // 长度
      cateNameLength: 0,
      // 输入字限制
      inputFlagNum: 20,


      // 商户
      mechantOption:[],
      // 适用对象
      applyObjOption:[
        {
          label: '所有会员',
          value: '1',
        },
        // {
        //   label: '自定义人群',
        //   value: '2',
        // },
      ],

      applyGoods:[
        {
          label: '所有商品',
          value: '1',
        },
        {
          label: '按商品品牌',
          value: '2',
        },
        {
          label: '按商品品类',
          value: '3',
        },
        {
          label: '按单件商品',
          value: '4',
        },
      ],

      // tree
      wxOpen: false,
      valueConsistsOf: 'ALL',
      treeOptions: [ {
        id: 'company',
        label: 'Company',
        children: [ {
          id: 'team-i',
          label: 'Team I',
          children: [ {
            id: 'person-a',
            label: 'Person A',
          }, {
            id: 'person-b',
            label: 'Person B',
          } ],
        }],
      }],

      ruleForm: {
        // 积分获取规则
        // 积分获取规则
        integralStrategyId: "", //策略id
        enterpriseId: "",
        strategyName: '', //策略名称
        strategyType: 2, // 策略类型 1消费积分 2积分抵现
        useCrowd: '1', // 策略类型 1所有 2人群筛选
        crowdJson: '', //人群筛选器内容
        integralGetStatus: '1', // 积分获取开启 1是0否
        integralGetStrategy: '1', // 取整策略 1四舍五入 2抹零 3向上取整
        integralGetFreezeDays: 1, // 获取积分冻结天数
        integralGetEffectiveDays: 1, // 获取积分有效天
        integralUseStatus: '0', // 积分抵现开启 1是0否
        integralUse: {fee:'',integral:''}, // 积分抵现 {fee:5,integral:5}
        channelList: [
          {
            integralStrategyChannelId: "", //id
            enterpriseId: "",
            integralStrategyId: "", //策略id
            channelType: "1", //渠道类型 1微信 3:线下 5淘宝 6京东 7唯品会 8天猫
            channelRelationEnterpriseType: "1", // 策略关联企业 1所有企业 2部分企业
            channelRelationStoreType: "1", //策略关联门店类型 1所有门店 2门店分组 3部分门店
            channelStoreType: "0", // 策略选择门店类型 （-1:所有 0:自营 1:联营 2:加盟,3代销4托管）
            channelRelationProType: "1", // 策略关联商品类型 1所有商品 2商品品牌 3商品类目 4部分商品
            integralUseDiscountControl: "1", // 折扣控制 1所有折扣商品适用 2折扣范围
            integralUseDiscountControlUpper: "0.0",
            integralUseDiscountControlLower: "0.0",
            useProportionalRestriction: "0.0", // 抵现比例限制
            strategyGoodsRelationIdArr: [], // 商品
            storeRelationIdArr: [], //门店
            enterpriseRelationIdArr: [], //商户
            useProportionalRestriction: '0', //  抵现比例限制
          },
        ],


      },
    }
  },
  created() {
    // this.selectReplayStyle()
  },
  methods: {
    // 返回
    goBack() {
      this.$router.go(-1)
    },
    // 保存
    submitForm(formName) {
      var that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var data = JSON.parse(JSON.stringify(that.ruleForm))

          // 非空验证
          if (!data.strategyName) {
            showMsg.showmsg('请填写策略名称','error')
            return;
          }

          if (!data.channelList[0].enterpriseRelationIdArr.length) {
            showMsg.showmsg('请填写选择商户','error')
            return;
          }


          if (data.channelList[0].integralUseDiscountControl==2 &&(!data.channelList[0].integralUseDiscountControlLower||!data.channelList[0].integralUseDiscountControlUpper)) {
            showMsg.showmsg('请填写折扣率','error')
            return;
          }

          if (data.integralUseStatus==1 && (!Number(data.integralUse.integral)||!Number(data.integralUse.fee))) {
            showMsg.showmsg('请填写抵现规则','error')
            return;
          }

          if (!data.channelList[0].useProportionalRestriction) {
            showMsg.showmsg('请填写比例限制','error')
            return;
          }
          // 规则需要乘以 10
          data.integralUse.fee = parseInt(data.integralUse.fee*10)
          data.integralUse.integral = parseInt(data.integralUse.integral*10)
          data.integralUse = JSON.stringify(data.integralUse)
          data.channelList.forEach(function(ele,index) {

          })

          that.saveForm(data)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

     // 保存数据
    saveForm(data) {
      var that = this
      console.log("添加积分抵现策略:" ,data)
      var para = data;

      postJson('/api-admin/save-member-integral-strategy',para)
      .then((res) => {
        console.log(res.data.result)
        var resData = res.data
        if (resData.errorCode == 0) {

          that.$message({
            message: '添加成功',
            type: 'success'
          });
          that.changeRoute('/pointSystem');
          return;
        }
        errMsg.errorMsg(resData)
        // that.updateData()

      })
      .catch(function (error) {
        console.log(error);
        // that.updateData()
        that.$message.error({
          duration: 1000,
          message: error.message
        })
      });
    },

    // 去空值
    bouncer(arr) {

      return arr.filter(function(val){
        return !(!val || val === "");
      });
    },


    // 树形结构
    toggle(flag) {
      var that = this
      that.treeFlag = flag

      if(flag== 'wx'){
        that.wxOpen = true
      }
      document.addEventListener('click', that.hidePanel, false)
    },

    hidePanel(e) {
      var that = this
      console.log(that.$refs.treeinput,e.target.className)
      if (typeof(e.target.className)== 'object') {return;}
      var tag = e.target.className !='span-txt' && e.target.className !='vue-treeselect__list' && e.target.className != 'vue-treeselect__label' && e.target.className != 'vue-treeselect__list-item vue-treeselect__indent-level-1' && e.target.className != 'vue-treeselect__minus-mark' && e.target.className !='vue-treeselect__option' && e.target.className !='vue-treeselect__option vue-treeselect__option--highlight' && e.target.className !='vue-treeselect__checkbox vue-treeselect__checkbox--unchecked'&& e.target.className != 'vue-treeselect__option-arrow-placeholder' && e.target.className!='el-form demo-ruleForm' && e.target.className!='vue-treeselect__option vue-treeselect__option--selected vue-treeselect__option--highlight' && e.target.className !='vue-treeselect__list-item vue-treeselect__indent-level-1' && e.target.className!= 'vue-treeselect__list-item vue-treeselect__indent-level-0' && e.target.className !='vue-treeselect__checkbox-container' && e.target.className !='vue-treeselect__option-arrow-container';
        console.log(tag)
      if (tag){

        if(that.treeFlag== 'wx'){
          that.wxOpen = false
        }
      }
    },

    // 输入
    toInput: function(value) {
      var that = this;
      console.log(value)

      var temp = '';
      var temp = strLength.getByteVal(value.target.value,that.inputFlagNum)
      console.log(temp)
      that.ruleForm.strategyName = temp.trim()

      that.cateNameLength = strLength.getZhLen(that.ruleForm.strategyName);

      console.log(that.ruleForm)
    },

    // 路由跳转
    changeRoute(route) {
      this.$router.push(route);
    },

    // 选择商品类别
    changeGood(e){
      var that = this
      console.log("线下渠道选择商品类别:",e)
      if (e==2) {
        that.getGoodsBrand()
      }
      if (e==3) {
         that.getGoodsCategory()
      }
    },

    // 获取商品品牌
    getGoodsBrand(){
      var that = this
      var para = {

      }

      postRequest('/api-admin/',para)
      .then((res) => {
        console.log(res.data.result)
        var resData = res.data
        if (resData.errorCode == 0) {
          var data = resData.result
          that.goodsTreeOptions = data
          return;
        }
        errMsg.errorMsg(resData)

      })
      .catch(function (error) {
        console.log(error);

        that.$message.error({
          duration: 1000,
          message: error.message
        })
      });
    },

    // 获取商品分类
    getGoodsCategory(){
      var that = this
      var para = {

      }

      postRequest('/api-admin/',para)
      .then((res) => {
        console.log(res.data.result)
        var resData = res.data
        if (resData.errorCode == 0) {
          var data = resData.result
          that.goodsTreeOptions = data
          return;
        }
        errMsg.errorMsg(resData)

      })
      .catch(function (error) {
        console.log(error);

        that.$message.error({
          duration: 1000,
          message: error.message
        })
      });
    },

    // 子组件显示方法
    showGoodsDialog() {
      var that = this
      console.log("show")
      that.goodShow = true;
    },

    // 子组件触发方法
    selectGoods(val){
      var that = this
      console.log(val)
      that.goodShow = false
    },

    // 获取商户列表
    getCliqueInfo() {
      var that = this
      var para = {

      }
      postRequest('/api-admin/list-enterprise',para)
      .then((res) => {
        console.log( res.data)
        var resData = res.data
        if (resData.errorCode == 0) {
          var data = resData.result.listEnterprise
          data.forEach(function(ele,index) {
            ele.label = ele.brandName
            ele.value = ele.enterpriseId
          })
          that.mechantOption = data
          console.log("商户列表:",that.mechantOption)
          // 默认选择商户
          that.ruleForm.channelList[0].enterpriseRelationIdArr = [data[0].enterpriseId]
          return;
        }
        errMsg.errorMsg(resData)

      })
      .catch(function (error) {
        console.log(error);

        that.$message.error({
          duration: 1000,
          message: error.message
        })
      });
    },
  },
  components: {
    topNav,
    Treeselect,
    addGoods
  },
  mounted() {
    var that = this
    that.getCliqueInfo();

  }
}

</script>
<style lang="less" scoped>
.right-box{
  padding: 24px 32px;
}
.attention-wrap {
  .item-label {
    font-size: 14px;
    color: #606266;
    margin-bottom: 30px;
    span {
      display: inline-block;
      width: 80px;
    }
  }

  .vue-treeselect {
    display: inline-block;
    vertical-align: top;
    width: 300px;
  }

  .title-tip {
    font-size: 12px;
    color: #888;
  }
  .attention-content-wrap {}
}

.form-wrap {

  .el-input {
    width: 178px;
    padding: 0 10px;
    &.w-300 {
      width: 300px;
    }
    &.w-340 {
      width: 340px;
    }
  }

  /deep/ .input-label {
    position: absolute;
    left: 303px;
    color: #ccc;
    font-size: 12px;
  }

  .el-select {
    vertical-align: top;
  }

  .span-txt {
    position: absolute;
    left: 222px;
    z-index: 2;
    width: 300px;
    text-align: center;
  }

  .padding-0 {
    padding: 0;
  }

  .form-child {
    padding: 15px 20px 10px 0px;
    background: #f5f6f9;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;

  }

  .margin-l-120 {
    margin-left: 120px;
  }

  .margin-20 {
    margin-top: 20px;
  }

  .tinymce-wrap {
    width: 780px;
  }
}

/*树形*/
.vue-treeselect /deep/ {

    /deep/ .vue-treeselect__control {
      height: 36px;
      /*line-height: 36px;*/
      cursor: pointer;
    }

    .vue-treeselect__placeholder {
      line-height: 36px;
      font-size: 12px;
    }

    /deep/ .vue-treeselect__multi-value-item-container,/deep/ .vue-treeselect__multi-value {
      line-height: 1;
      height: 0;
      opacity: 0;
    }

    span.vue-treeselect__multi-value-label {
      line-height: 1;
    }

    .vue-treeselect__multi-value-item {
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      box-sizing: border-box;
      background-color: #f0f2f5;
      color: #909399;
    }

    .vue-treeselect__value-remove {
      color: #909399;
    }

    &:not(.vue-treeselect--disabled) .vue-treeselect__multi-value-item:not(.vue-treeselect__multi-value-item-disabled):hover {
      background-color: #f0f2f5;
      color: #909399;
    }

    .vue-treeselect--searchable:not(.vue-treeselect--disabled) .vue-treeselect__value-container {
      cursor: pointer;
    }

    /deep/.vue-treeselect__x-container {
      /*display: none;*/
    }

    /deep/ .vue-treeselect__x {
      display: none;
    }

    .vue-treeselect__control-arrow {
      display: none;
    }

    .vue-treeselect__control-arrow-container {
      position: relative;
    }

    /deep/ .vue-treeselect__value-container{
      line-height: 34px;
    }

    /deep/.vue-treeselect__control-arrow-container:after, .vue-treeselect__control-arrow-container:before {
      border: 6px solid transparent;
      border-left: 6px solid #fff;
      width: 0;
      height: 0;
      position: absolute;
      top: 49%;
      left: 50%;
      margin-left: -6px;
      content: ' ';
      margin-top: -3px;
      -webkit-transform: rotate(90deg);
      -moz-transform: rotate(90deg);
      -o-transform: rotate(90deg);
      transform: rotate(90deg);
      -webkit-transition: -webkit-transform .3s;
      transition: -webkit-transform .3s;
      transition: transform .3s;
      transition: transform .3s, -webkit-transform .3s;
      transition: transform .3s,-webkit-transform .3s;
    }

    /deep/ .vue-treeselect__control-arrow-container:before {
      border-left-color: #c0c4cc;
      top: 52%;
    }

    &.vue-treeselect--focused .vue-treeselect__control-arrow-container:after, &.vue-treeselect--focused .vue-treeselect__control-arrow-container:before {
      margin-top: -6px;
      -webkit-transform: rotateZ(-90deg);
      -moz-transform: rotateZ(-90deg);
      -o-transform: rotateZ(-90deg);
      transform: rotateZ(-90deg);
      -webkit-transition: -webkit-transform .3s;
      transition: -webkit-transform .3s;
      transition: transform .3s;
      transition: transform .3s, -webkit-transform .3s;
      transition: transform .3s,-webkit-transform .3s;
    }

    &.vue-treeselect--focused .vue-treeselect__control-arrow-container:before {
      border-left-color: #c0c4cc;
      top: 47%;
    }

    .vue-treeselect--has-value .vue-treeselect__multi-value {
      margin-bottom: 0;
    }
  }
  .el-select .el-input--suffix .el-input__inner{
    height: 32px;
  }
</style>
