<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="120px" 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)">
                 </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 margin-l-120" >
                    <el-form-item label="选择商户">
                      <el-select v-model="item.enterpriseRelationIdArr" placeholder="请选择" multiple >
                        <el-option
                          v-for="item in mechantOption"

                          :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:[
        // {
        //   label: '尊兴网络',
        //   value: '0',
        // },
        // {
        //   label: '江南布衣服饰有限公司',
        //   value: '1',
        // },
      ],
      // 适用对象
      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: 'ff8080815d699a44015d69c6884a002b-a',
            label: 'Person A',
          }, {
            id: 'person-b',
            label: 'Person B',
          } ],
        }],
      }],

      ruleForm: {
        // 积分获取规则
        integralStrategyId: "ff80808163a7a09b0163b01171e202db", //策略id
        enterpriseId: "ff8080815dacd3a2015dacd3ef5c0000",
        strategyName: 1, //策略名称
        strategyType: 1, // 策略类型 1消费积分 2积分抵现
        useCrowd: '1', // 策略类型 1所有 2人群筛选
        crowdJson: '', //人群筛选器内容
        integralGetStatus: '1', // 积分获取开启 1是0否
        integralGet: {fee:11,integral:12},
        integralGetStrategy: '1', // 取整策略 1四舍五入 2抹零 3向上取整
        integralGetFreezeDays: 1, // 获取积分冻结天数
        integralGetEffectiveDays: 1, // 获取积分有效天
        integralUseStatus: '0', // 积分抵现开启 1是0否
        integralUse: {fee:'',integral:''}, // 积分抵现 {fee:5,integral:5}
        channelList: [
          {
            integralStrategyChannelId: "ff808081649321d20164a1fafbdd01df", //id
            enterpriseId: "ff8080815dacd3a2015dacd3ef5c0000",
            integralStrategyId: "ff80808163a7a09b0163b01171e202db", //策略id
            channelType: "1", //渠道类型 1微信 3:线下 5淘宝 6京东 7唯品会 8天猫
            openStatus: true, //渠道配置是否启用 1启用 0停用
            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) {
          console.log(typeof(that.ruleForm.integralUse))
          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.updateData()
          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
        })
      });
    },

    // 树形结构
    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
    },

    // 获取策略信息
    getInfo() {
      var that = this
      var para = {
        strategyId: that.ruleForm.integralStrategyId
      }

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

          // 商户列表
          var prise = res.data.result.enterpriseList
          prise.forEach(function(ele,index){
            ele.label = ele.enterpriseName;
            ele.value = ele.enterpriseId;
          })
          that.mechantOption = prise

          var item = res.data.result.strategy;

          item.integralUse = JSON.parse(item.integralUse)
          if (!item.integralUse) {
            item.integralUse = {}
            item.integralUse.fee = '';
            item.integralUse.integral = '';
          }
          // 规则需要先除以10
          if (item.integralUse.fee !='') {
            item.integralUse.fee = parseInt(item.integralUse.fee/10)
          }
          if (item.integralUse.integral) {
            item.integralUse.integral = parseInt(item.integralUse.integral/10)
          }

          that.ruleForm = that.formatData(item)
          // 字数控制
          that.cateNameLength = strLength.getZhLen(that.ruleForm.strategyName)
          console.log(that.ruleForm)
          return;
        }
        errMsg.errorMsg(resData)

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

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

    // 去空值
    bouncer(arr) {

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

    formatData(item) {
      var that = this
      item.integralGetStatus = String(item.integralGetStatus);
      item.integralUseStatus = String(item.integralUseStatus);
      item.useCrowd = String(item.useCrowd);

      item.integralGet = JSON.parse(item.integralGet);


      item.channelList.forEach(function(ele,index) {
        ele.channelType = String(ele.channelType);
        // ele.useCrowd = String(ele.useCrowd);
        ele.channelRelationStoreType = String(ele.channelRelationStoreType)
        ele.channelStoreType = String(ele.channelStoreType)
        ele.channelRelationProType = String(ele.channelRelationProType)
        ele.integralUseDiscountControl = String(ele.integralUseDiscountControl)
        ele.integralUseDiscountControlUpper = String(ele.integralUseDiscountControlUpper)
        ele.integralUseDiscountControlLower = String(ele.integralUseDiscountControlLower)
        ele.useProportionalRestriction = String(ele.useProportionalRestriction)

        if (!ele.strategyGoodsRelationIdArr || !ele.strategyGoodsRelationIdArr.length) {

          ele.strategyGoodsRelationIdArr = []
        }
        if (!ele.storeRelationIdArr || !ele.storeRelationIdArr.length) {
          ele.storeRelationIdArr = []
        }
        if (!ele.enterpriseRelationIdArr || !ele.enterpriseRelationIdArr.length) {
          ele.enterpriseRelationIdArr = []
        }

      })
      console.log(item.channelList)
      return item;
    },

    // 获取商品品类

  },
  components: {
    topNav,
    Treeselect,
    addGoods
  },
  mounted() {
    var that = this
    console.log(that.$route.query.integralStrategyId)
    // 获取策略 id
    var id = that.$route.query.integralStrategyId;
    that.ruleForm.integralStrategyId = id;
    that.getInfo();
  }
}

</script>
<style lang="less" scoped>
.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;

      /*/deep/ .el-input-group__append{
        background-color: #fff;
        border-left: 0px;
      }
      /deep/ .el-input__inner {
        border-right: 0px;
      }*/
    }
    &.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 {
    width: 900px;
    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;
    }

    .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;
    }
  }

</style>
