<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="">
                 <el-input v-model="ruleForm.strategyName" class="w-340" @keyup.native="(value) => toInput(value)">
                   <!-- <template slot="append"><label class="input-label">{{cateNameLength}}/20</label></template> -->
                 </el-input>
                 <label class="input-label">{{cateNameLength}}/20</label>
              </el-form-item>

              <template v-for="(item,index) in ruleForm.channelList">
                <!-- 线下渠道 -->
                <template v-if="item.channelType==3">
                  <el-form-item label="适用线下渠道" prop="">
                    <el-switch
                      v-model="item.openStatus"
                      active-text="启用"
                      inactive-text="停用">
                    </el-switch>
                  </el-form-item>
                  <div class="form-child" v-if="item.openStatus">
                    <el-form-item label="门店选择" prop="region">
                      <el-select v-model="item.channelRelationStoreType" placeholder="请选择" @change="selStore($event,index,item)">
                        <el-option
                          v-for="item in StoreOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                      <!-- 二级 -->
                      <!-- <el-input readonly ref="treeinput" class="w-230" v-if="item.channelRelationStoreType == 2" v-model="item.channelRelationStoreType" placeholder="" @focus="toggle" ></el-input> -->
                      <span class="span-txt" ref="treeinput" v-if="item.channelRelationStoreType == 2" @click="toggle('store')">已选择 {{item.storeRelationIdArr? item.storeRelationIdArr.length:0}} 个门店分组 </span>
                      <treeselect
                        ref="treediv"
                        v-if="item.channelRelationStoreType == 2"
                        placeholder="请选择"
                        noOptionsText="暂无数据"
                        noResultsText="无数据"
                        noChildrenText="暂无数据"
                        :multiple="true"
                        :options="treeOptions"
                        :open-on-focus="openOnFocus"
                        :always-open="alwaysOpen"

                        :normalizer="storeNormalizer"
                        :searchable="false"
                        :clearable="false"
                        :value-consists-of="valueConsistsOf"
                        @select= "selectStore($event,item)"
                        v-model="item.storeRelationIdArr"
                      />
                      <!-- 搜素下拉 -->
                      <el-select
                        v-if="item.channelRelationStoreType == 3"
                        v-model="item.storeRelationIdArr"
                        multiple
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入关键词"
                        :remote-method="remoteMethod"
                        @focus="searchFocus(index,item)"
                        >
                        <el-option
                          v-for="item in storeListOptions"

                          :label="item.value"
                          :value="item.key">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="门店类型" prop="name" class="padding-0">
                      <el-select v-model="item.channelStoreType" placeholder="请选择">
                        <el-option
                          v-for="item in StoreTypeOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="适用商品" prop="name" 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('brand')">已选择 {{item.strategyGoodsRelationIdArr? item.strategyGoodsRelationIdArr.length:0}} 个品牌 </span>
                      <span class="span-txt" ref="treeinput" v-if="item.channelRelationProType == 3" @click="toggle('brand')">已选择 {{item.strategyGoodsRelationIdArr? item.strategyGoodsRelationIdArr.length:0}} 个品类 </span>
                      <treeselect
                        v-if="item.channelRelationProType==2||item.channelRelationProType==3"
                        placeholder=""
                        noOptionsText="暂无数据"
                        noResultsText="无数据"
                        noChildrenText = "暂无数据"
                        :multiple="true"
                        :flat="true"

                        :always-open="goodsOpen"
                        :options="goodsTreeOptions"
                        :load-options="loadOptions"
                        :normalizer="goodNormalizer"

                        :value-consists-of="valueConsistsOf"
                        v-model="item.strategyGoodsRelationIdArr"
                      /><!--:default-expand-level="1":load-options="loadOptions" :normalizer="normalizer" :always-open="goodsOpen" -->
                      <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" @focus="inputFocus(item)"  @keyup.native="formatInput($event)"></el-input>
                         <label>至</label>
                         <el-input v-model="item.integralUseDiscountControlUpper" @focus="inputFocus(item)"  @keyup.native="formatInput($event)"></el-input>
                         <!-- <label>商品都适用</label> -->
                      </div>
                    </el-form-item>
                  </div>
                </template>

                <template v-if="item.channelType==1">
                  <!-- 微信商城 -->
                  <el-form-item label="适用微信商城" prop="">
                    <el-switch
                      v-model="item.openStatus"
                      active-text="启用"
                      inactive-text="停用">
                    </el-switch>
                  </el-form-item>
                  <div class="form-child margin-20" v-if="item.openStatus==true">
                    <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.goodsRelationIds? item.goodsRelationIds.length:0}} 个品牌 </span>
                      <span class="span-txt" ref="treeinput" v-if="item.channelRelationProType == 3" @click="toggle('wx')">已选择 {{item.goodsRelationIds? item.goodsRelationIds.length:0}} 个品类 </span>
                      <treeselect
                        v-if="item.channelRelationProType==2||item.channelRelationProType==3"
                        placeholder=""
                        noOptionsText="暂无数据"
                        noResultsText="无数据"
                        noChildrenText = "暂无数据"
                        :multiple="true"
                        :always-open="wxOpen"
                        :options="goodsTreeOptions"

                        :value-consists-of="valueConsistsOf"
                        v-model="item.goodsRelationIds"
                        :normalizer="goodNormalizer"
                        @select="selectWx($event,index,item)"
                      /> <!--model=item.strategyGoodsRelationIds和上一个相同会有问题 -->
                      <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" @focus="inputFocus(item)"  @keyup.native="formatInput($event)"></el-input>
                        <label>至</label>
                        <el-input v-model="item.integralUseDiscountControlUpper" @focus="inputFocus(item)"  @keyup.native="formatInput($event)"></el-input>
                        <!-- <label>商品都适用</label> -->
                      </div>
                    </el-form-item>
                  </div>
                </template>

                <template v-if="item.channelType==8">
                  <!-- 第三方 -->
                  <el-form-item label="第三方电商渠道" prop="">
                    <el-switch
                      v-model="item.openStatus"
                      active-text="启用"
                      inactive-text="停用">
                    </el-switch>
                  </el-form-item>
                  <div class="form-child margin-20" v-if="item.openStatus==true">
                    <el-form-item label="选择店铺">
                      <el-select v-model="item.channelRelationStoreType" placeholder="请选择" >
                        <el-option
                          v-for="item in allShopOption"
                          :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="请选择">
                        <el-option
                          v-for="item in allGoodOption"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                      <!-- 二级 -->
                     <!--  <treeselect
                      v-if="item.thirdApplyTmallGoods==1||item.thirdApplyTmallGoods==2"
                      placeholder="所有分类"
                      noOptionsText="暂无数据"
                      noResultsText="无数据"
                      :multiple="true"
                      :options="wxTreeOptions"
                      :value-consists-of="valueConsistsOf"
                      v-model="item.thirdApplyTmallGoodsIds"
                      />
                      <el-button v-if="item.thirdApplyTmallGoods==3" @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" @focus="inputFocus(item)"  @keyup.native="formatInput($event)"></el-input>
                        <label>至</label>
                        <el-input v-model="item.integralUseDiscountControlUpper" @focus="inputFocus(item)"  @keyup.native="formatInput($event)"></el-input>
                        <!-- <label>商品都适用</label> -->
                      </div>
                    </el-form-item>
                  </div>
                </template>
              </template>

              <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="获取规则" prop="">
                <div>
                  <el-radio v-model="ruleForm.integralGetStatus" label="1">每消费</el-radio>
                  <el-input v-model="ruleForm.integralGet.fee" @blur="formatInputNumBlur($event)"></el-input><label>元，获取 </label>
                  <el-input v-model="ruleForm.integralGet.integral" @blur="formatInputNumBlur($event)"></el-input><label>积分。取整策略为</label>
                  <el-select v-model="ruleForm.integralGetStrategy" placeholder="请选择">
                    <el-option
                      v-for="item in cateOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </div>
                <div>
                  <el-radio v-model="ruleForm.integralGetStatus" label="0" class="margin-20">不获取积分</el-radio>
                </div>
              </el-form-item>
              <el-form-item label="积分冻结期" v-if="ruleForm.integralGetStatus==1">
                <el-input v-model="ruleForm.integralGetFreezeDays" @keyup.native="formatInputNum($event)"></el-input><label>天</label>
              </el-form-item>
               <el-form-item label="积分有效期" v-if="ruleForm.integralGetStatus==1">
                <el-input v-model="ruleForm.integralGetEffectiveDays" @keyup.native="formatInputNum($event)"></el-input><label>天</label>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click.stop="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 { getRequest, postRequest, postJsonRequest, postJson, postForm } from '@/api/api';
import strLength from '@/common/js/strlen';

export default {
  name: "editPointSytem",
  data() {
    return {
      repProjectName: 'gic-clique',
      navpath: [{
          name: '首页',
          path: '/'
        },
        {
          name: '编辑积分获取策略',
          path: ''
        }
      ],
      // 添加商品弹窗
      goodShow: false,
      // 输入字限制
      inputFlagNum: 20,

      // 门店
      StoreOptions: [
        {
          label: '所有门店',
          value: '1',
        },
        {
          label: '门店分组',
          value: '2',
        },
        {
          label: '部分门店',
          value: '3',
        },
      ],
      StoreTypeOptions: [
        {
          label: '所有门店',
          value: '-1',
        },
        {
          label: '自营',
          value: '0',
        },
        {
          label: '联营',
          value: '1',
        },
        {
          label: '加盟',
          value: '2',
        },
        {
          label: '代销',
          value: '3',
        },
        {
          label: '托管',
          value: '4',
        },
      ],
      applyGoods:[
        {
          label: '所有商品',
          value: '1',
        },
        {
          label: '按商品品牌',
          value: '2',
        },
        {
          label: '按商品品类',
          value: '3',
        },
        {
          label: '按单件商品',
          value: '4',
        },
      ],
      // tree
      openOnFocus: true,
      alwaysOpen: false,
      goodsOpen: false,
      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',
        //     } ],
        //   }],
        // }
      ],
      storeNormalizer(node) {
        return {
          id: node.storeGroupId,
          label: node.storeGroupName,
          children: node.children,
        }
      },
      // 适用商品
      goodsTreeOptions: [
        {
          id: 'a',
          label: 'a',
          children: [
            {
              id: 'aa',
              label: 'aa',
            }
          ]
        }
      ],
      goodNormalizer(node/*, id */) {
        // there is an extra `id` argument,
        // which could be useful if you have multiple instances
        // of vue-treeselect that share the same `normalizer` function
        console.log(node)
        return {
          id: node.key,
          label: node.name,
          children: node.subOptions,
        }
      },

      // wxTreeOptions
      wxTreeOptions: [ {
        id: 'company1',
        label: 'Company1',
        children: [ {
          id: 'team-i',
          label: 'Team I',
          children: [ {
            id: 'person-a',
            label: 'Person A',
          }, {
            id: 'person-b',
            label: 'Person B',
          } ],
        }],
      }],
      // 商户
      mechantOption:[
        // {
        //   label: '尊兴网络',
        //   value: '0',
        // },
        // {
        //   label: '江南布衣服饰有限公司',
        //   value: '1',
        // },
      ],
      // 第三方下拉
      allShopOption: [
       {
          label: '所有店铺',
          value: '1',
        },
      ],
      allGoodOption: [
        {
          label: '所有商品',
          value: '1',
        },
      ],

      storeListOptions: [], //下拉搜索出现的门店列表


      // 适用对象
      applyObjOption:[
        {
          label: '所有会员',
          value: '1',
        },
        // {
        //   label: '自定义人群',
        //   value: '2',
        // },
      ],
      // 长度
      cateNameLength: 0,

      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: null, // 积分抵现 {fee:5,integral:5}
        channelList: [
          {
            integralStrategyChannelId: "ff808081649321d20164a1fafbdd01df", //id
            enterpriseId: "ff8080815dacd3a2015dacd3ef5c0000",
            integralStrategyId: "ff80808163a7a09b0163b01171e202db", //策略id
            channelType: "1", //渠道类型 1微信 3:线下 5淘宝 6京东 7唯品会 8天猫
            openStatus: "0", //渠道配置是否启用 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: null, // 商品
            goodsRelationIdArr: null,
            storeRelationIdArr: null, //门店
            enterpriseRelationIdArr: null //商户
          },
          {
            integralStrategyChannelId: "ff808081649321d20164a1fafbdd01df", //id
            enterpriseId: "ff8080815dacd3a2015dacd3ef5c0000",
            integralStrategyId: "ff80808163a7a09b0163b01171e202db", //策略id
            channelType: "3", //渠道类型 1微信 3:线下 5淘宝 6京东 7唯品会 8天猫
            openStatus: "0", //渠道配置是否启用 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: null, // 商品
            storeRelationIdArr: null, //门店
            enterpriseRelationIdArr: null //商户
          },
          {
            integralStrategyChannelId: "ff808081649321d20164a1fafbdd01df", //id
            enterpriseId: "ff8080815dacd3a2015dacd3ef5c0000",
            integralStrategyId: "ff80808163a7a09b0163b01171e202db", //策略id
            channelType: "8", //渠道类型 1微信 3:线下 5淘宝 6京东 7唯品会 8天猫
            openStatus: "0", //渠道配置是否启用 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: null, // 商品
            storeRelationIdArr: null, //门店
            enterpriseRelationIdArr: null //商户
          },
        ],
      },
      cateOptions: [
        {
          value: '1',
          label: '四舍五入'
        },
        {
          value: '2',
          label: '抹零'
        },
        {
          value: '3',
          label: '进位制'
        }
      ],

    }
  },

  methods: {
    // 返回
    goBack() {
      this.$router.go(-1)
    },

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

    // input focus
    inputFocus(obj){
      var that = this
      that.tempData = obj
    },

    // 输入框输入校验数字
    formatInput(e){
      var that = this
      console.log(e,e.target.value,that.tempData.integralUseDiscountControlLower)
      that.tempData.integralUseDiscountControlLower = Number(String(that.tempData.integralUseDiscountControlLower).replace(/[^\.\d]/g,'')).toFixed(2) == 'NaN'? '0.00': Number(String(that.tempData.integralUseDiscountControlLower).replace(/[^\.\d]/g,'')).toFixed(2);
      that.tempData.integralUseDiscountControlUpper = Number(String(that.tempData.integralUseDiscountControlUpper).replace(/[^\.\d]/g,'')).toFixed(2) == 'NaN'? '0.00': Number(String(that.tempData.integralUseDiscountControlUpper).replace(/[^\.\d]/g,'')).toFixed(2);
    },
    formatInputNum(e){
      var that = this
      that.ruleForm.integralGetEffectiveDays = strLength.getCharVal(String(that.ruleForm.integralGetEffectiveDays).replace(/[^\d]/g,''),4)
      that.ruleForm.integralGetFreezeDays = strLength.getCharVal(String(that.ruleForm.integralGetFreezeDays).replace(/[^\d]/g,''),4)

    },

    formatInputNumBlur(){
      var that = this
      that.ruleForm.integralGet.fee = Number(strLength.getCharVal(String(that.ruleForm.integralGet.fee).replace(/[^\.\d]/g,''),6)).toFixed(1)
      that.ruleForm.integralGet.integral = Number(strLength.getCharVal(String(that.ruleForm.integralGet.integral).replace(/[^\.\d]/g,''),8)).toFixed(1)
    },

    checkListValue(data) {
      var that = this
      var obj = {
        flag : true,
        text: ''
      }
      data.channelList.forEach(function(ele,index){
        if (!!ele.openStatus && ele.integralUseDiscountControl == 2) {
          if (!ele.integralUseDiscountControlUpper||!ele.integralUseDiscountControlLower) {
            obj.flag = false
            obj.text = '请填写折扣率'
          }

          if (parseInt(ele.integralUseDiscountControlUpper)>10||parseInt(ele.integralUseDiscountControlLower)>10 || Number(ele.integralUseDiscountControlUpper)<=Number(ele.integralUseDiscountControlLower)) {
            obj.flag = false
            obj.text = '折扣率格式有误'
          }
        }

        if (ele.channelType==1 && !ele.enterpriseRelationIdArr.length) {
           obj.flag = false
           obj.text = '请选择商户'
        }

      })

      console.log(obj.flag)
      return obj;
    },

    // 保存
    submitForm(formName) {
      var that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 处理数据
          var data = JSON.parse(JSON.stringify(that.ruleForm))
          console.log(data)

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

          if (data.integralGetStatus == 1 &&(!Number(data.integralGet.fee)||!Number(data.integralGet.integral))) {
            showMsg.showmsg('请填写获取规则','error')
            return;
          }

          if (data.integralGetStatus == 1 && !Number(data.integralGetFreezeDays)) {
            showMsg.showmsg('请填写积分冻结期','error')
            return;
          }

          if (data.integralGetStatus == 1 && !Number(data.integralGetEffectiveDays)) {
            showMsg.showmsg('请填写积分有效期','error')
            return;
          }

          var returnObj = that.checkListValue(data)
          if (!returnObj.flag) {
            showMsg.showmsg(returnObj.text,'error')
            return;
          }

          // return;
          // 设置开启状态 1-->true
          data.channelList.forEach(function(ele,index){
            ele.openStatus = ele.openStatus== true? 1: 0
            delete ele.strategyGoodsRelationIds;
            delete ele.enterpriseRelationIds;
            delete ele.storeRelationIds;

            if (ele.channelType == 1) {
              ele.strategyGoodsRelationIdArr = ele.goodsRelationIdArr
              // console.log(ele.strategyGoodsRelationIds)
              delete ele.goodsRelationIdArr;
            }
            if (!ele.enterpriseRelationIdArr||!ele.enterpriseRelationIdArr.length) {
              ele.enterpriseRelationIdArr = []
            }
            if (!ele.storeRelationIdArr||!ele.storeRelationIdArr.length) {
              ele.storeRelationIdArr = []
            }
            if (!ele.strategyGoodsRelationIdArr||!ele.strategyGoodsRelationIdArr.length) {
              ele.strategyGoodsRelationIdArr = []
            }
          })
          console.log(JSON.stringify(data.channelList))

          data.integralGet.fee = parseInt(data.integralGet.fee*10)
          data.integralGet.integral = parseInt(data.integralGet.integral*10)
          data.integralGet = JSON.stringify(data.integralGet)
          // data.channelList = JSON.stringify(data.channelList)
          that.saveForm(data);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    // 保存数据
    saveForm(data) {
      var that = this

      var para = data
      // var para = that.ruleForm;
      console.log("策略编辑:",para)

      console.log("保存数据:",para)
      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.updateData()
          that.changeRoute('/pointSystem');
          return;
        }
        errMsg.errorMsg(resData)

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

     // 更新数据
    updateData() {
      var that = this
      // that.ruleForm.integralGet = JSON.parse(that.ruleForm.integralGet)
      that.ruleForm.integralGet.fee = parseInt(that.ruleForm.integralGet.fee/10)
      that.ruleForm.integralGet.integral = parseInt(that.ruleForm.integralGet.integral/10)

    },

    // 树形结构
    toggle(flag) {
      var that = this
      that.treeFlag = flag
      if (flag=='store') {
        that.alwaysOpen = true;
        console.log(that.alwaysOpen)
      }
      if(flag== 'brand'){
        that.goodsOpen = true
      }
      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,typeof(e.target.className),that.treeFlag)
      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.includes('vue-treeselect__list-item vue-treeselect__indent-level') && 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.includes('vue-treeselect__checkbox vue-treeselect__checkbox--')&& 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'&& e.target.className !='vue-treeselect__option-arrow vue-treeselect__option-arrow--rotated';
        console.log(tag)
      if (tag){
        if (that.treeFlag == 'store') {
          that.alwaysOpen = false;
        }
        if(that.treeFlag== 'brand'){
          that.goodsOpen = false
        }
        if(that.treeFlag== 'wx'){
          that.wxOpen = false
        }
      }
    },
    // 选择节点的方法
    selectStore(e,item) {
      var that = this
      console.log(e,item)
      console.log(e,item.useCrowd)
    },

    // 微信
    selectWx(e,index,item) {
      var that = this
      console.log(e,index,item,item.goodsRelationIds)
      item.strategyGoodsRelationIds = item.goodsRelationIds
      console.log(item.goodsRelationIds)
      var data = that.ruleForm.channelList[index]
      data.strategyGoodsRelationIds = [];
      data.goodsRelationIds.forEach(function(ele,index) {
        data.strategyGoodsRelationIds.push(ele)
      })
      // data.strategyGoodsRelationIds = data.goodsRelationIds

      console.log(data)
    },


    // 搜索后出现下拉列表
    // 点击
    searchFocus(index,item) {
      var that = this
      console.log(index,item)
    },
    // 搜索
    remoteMethod(query) {
      var that = this;
      console.log("query:",query)

      if (query !== '') {
        // 获取搜索列表数据
        that.getStoreList(query);
      }else {

        that.storeListOptions = [];
      }
    },

    // 获取门店列表
    getStoreList(query) {
      var that = this
      console.log(query)
      var para = {
        searchParam: query,
        flag: null,
        requestProject: that.repProjectName
      }

      postRequest('/api-plug/query-store-by-code-name',para)
      .then((res) => {
        console.log(res,res.data,res.data.errorCode)
        var resData = res.data
        if (resData.errorCode == 0) {
          resData.result.forEach(function(ele,index){
            ele.id = ele.storeId;
            ele.value = ele.storeName;
            ele.key = ele.storeId
          })
          that.storeListOptions= resData.result
          return;
        }

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

    // 获取门店分组
    getStoreGroup() {
      var that = this
      var para = {

      }

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

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

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

    // 输入
    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);
    // }

    selStore(e,index,item) {
      var that = this
      console.log(e,index,item)
      item.storeRelationIdArr = []
    },

    // 微信选择商品类别
    wxChange(e) {
      var that = this
      console.log("微信选择商品类别:",e)
      that.getGoodsCategory()
    },

    // 线下渠道选择商品类别
    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 item = res.data.result.strategy;
          // 商户列表
          var prise = res.data.result.enterpriseList
          prise.forEach(function(ele,index){
            ele.label = ele.enterpriseName;
            ele.value = ele.enterpriseId;
          })
          that.mechantOption = prise

          that.ruleForm = that.formatData(item)

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

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

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

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

      item.integralGet = JSON.parse(item.integralGet);
      // 获取规则需要除以 10
      console.log(item.integralGet)
      item.integralGet.fee = Number(item.integralGet.fee/10).toFixed(1)
      item.integralGet.integral = Number(item.integralGet.integral/10).toFixed(1)
      if (!!item.channelList.length) {
        item.channelList.forEach(function(ele,index) {
          ele.openStatus = ele.openStatus == 0? false: true;
          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.enterpriseRelationIdArr||!ele.enterpriseRelationIdArr.length || ele.enterpriseRelationIdArr[0]=='[]') {
            ele.enterpriseRelationIdArr = []
          }
          if (!ele.storeRelationIdArr||!ele.storeRelationIdArr.length) {
            ele.storeRelationIdArr = []
          }
          if (!ele.strategyGoodsRelationIdArr||!ele.strategyGoodsRelationIdArr.length) {
            ele.strategyGoodsRelationIdArr = []
          }

          if (ele.channelType == 1) {
            ele.goodsRelationIdArr = [];
            ele.goodsRelationIdArr = ele.strategyGoodsRelationIdArr || [] // 复制商品字段
          }

        })
      }
      console.log(item.channelList[0])
      return item;
    },

    // 获取商品品类
    getGoodsCategory() {
      var that = this
      var para = {
        filterGoods: 1,
        parentId: '',
      }
      postRequest('/api-mall/list_mall_goods_category',para)
      .then((res) => {
        console.log(res,res.data,res.data.errorCode)
        var resData = res.data;
        var onelevelCategory = '';
        if (resData.errorCode == 0) {
          resData.result.forEach(function(ele,index){
            if (ele.parentId == '-1') {
              ele.children = [];
              ele.key = ele.mallCategoryId
              ele.id = ele.mallCategoryId
              ele.label = ele.name
              onelevelCategory = ele;
              resData.result.splice(index,1);
            }
          })
          console.log("resdata: ",resData)
          var list = resData.result, lists = resData.result;

          // list.forEach(function(ele,index) {
          //   if (ele.isLeaf == 0) {
          //     ele.subOptions = null;
          //   }
          //   ele.key = ele.mallCategoryId;
          //   lists.forEach(function(el,ind) {
          //       el.key = el.mallCategoryId;
          //       if(el.parentId == ele.mallCategoryId ){
          //         console.log(index,ind)
          //         ele.subOptions = []
          //         ele.subOptions.push(el)
          //         list.splice(ind,1)
          //       }
          //   })

          // })
          console.log("list:",list,onelevelCategory)

          list.forEach(function(ele,index){
            onelevelCategory.children.push(ele)
          })
          that.goodsTreeOptions = [];
          that.goodsTreeOptions.push(onelevelCategory);

          console.log("list:",that.categoryOptions)
          return false;
        }

        errMsg.errorMsg(resData)
      })
      .catch(function (error) {
        console.log(error);
        // that.toLogin()
        that.$message.error({
          duration: 1000,
          message: error.message
        })
      });
    },

    loadOptions({ action, parentNode, callback }) {

      var that = this
      console.log(action,parentNode,callback)
      if (action === "LOAD_CHILDREN_OPTIONS") {
        if (parentNode.id) {
          that.getChildrenNode(parentNode,parentNode.id)
        }

      }
    },

    // 获取子节点方法
    getChildrenNode(parentNode,parentId) {
      var that = this
      var para = {
        filterGoods: 1,
        parentId: parentId,
        requestProject: that.repProjectName
      }
      postRequest('/api-mall/list_mall_goods_category',para)
      .then((res) => {
        console.log(res,res.data,res.data.errorCode)
        var resData = res.data
        if (resData.errorCode == 0) {
          resData.result.forEach(function(ele,index){
            if (ele.isLeaf == 0) {
              ele.subOptions = null;
            }else{
              ele.subOptions = []
            }
            ele.key = ele.mallCategoryId
          })
          parentNode.subOptions = resData.result
          return;
        }
        errMsg.errorMsg(resData)

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

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

    // 获取门店分组
    that.getStoreGroup()
  },
  destoryed() {

  }
}

</script>
<style lang="scss" scoped>
.attention-wrap {
  padding: 24px 32px;
  background: #fff;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  .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;
  }
  .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;
    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-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;
    }

    .vue-treeselect__multi-value-item-container,.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;
    }

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