<template>
  <!-- 链接小工具 -->
  <div class="link-tools-contain">
    <el-dialog :class="activeName == 'first' ? 'min-1026' : 'min-720'" title="链接小工具" :close-on-click-modal="false" :visible.sync="mylinkToolsVisible" @close="changeVisible" :modal-append-to-body="false">
      <!-- 链接类型 -->
      <div class="links-types">
        <label class="types-title">链接类型</label>
        <el-select v-model="linksType" class="w200" placeholder="请选择" @change="linksTypeChange">
          <el-option v-for="item in linksTypeOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <!-- 滚动加载更多 -->
        <!-- 二级下拉 -->
        <el-select v-model="twoLevelValue" v-loadmore="getMore" class="w200" placeholder="请选择" v-if="twoLevelVisible" @change="twoLevelValueChange">
          <el-option v-for="item in twoLevelOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <!-- 三级下拉 -->
        <div class="three-level-wrap w200" v-if="threeLevelVisible">
          <!-- 三级单选 -->
          <el-select v-model="threeLevelValue" placeholder="请选择" v-if="threeLeveloneVisible" @change="threeSingleValueChange">
            <el-option v-for="item in threeLevelOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>

          <goods-tree v-if="goodsTreeVisible" @pass-mall="getMallId" :current-good-id="cardUrl" :tree-data="treeData"></goods-tree>

          <!-- 商品分类链接 -->
          <!-- <treeselect
            v-if="threeLevelTreeVisible"
            v-model="threeLevelValue"
            :options="goodsCategoryOptions"
            :normalizer="normalizer"
            :default-expand-level="1"
            placeholder="所有分类"
            noOptionsText="暂无数据"
            noResultsText="无数据"
            @select="goodsCategorySelect"
            /> -->
          <!-- 搜索后出现下列 -->
          <el-select v-if="threeLevelSearchVisible" v-model="threeLevelValue" multiple filterable remote reserve-keyword placeholder="请输入关键词" :remote-method="remoteMethod" @change="threeLevelValueChange">
            <el-option v-for="item in threeLevelOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </div>
        <!-- 第三方小程序 -->
        <div class="h5link-contain" v-if="thirdlinkVisible">
          <!-- <div class="h5link-row">
          <label class="h5link-title">名称</label>
          <el-input v-model="thirdObj.name" placeholder="请输入名称"></el-input>
        </div>
        -->
          <div class="h5link-row">
            <label class="h5link-title">跳转路径(非必填)</label>
            <el-input v-model="thirdObj.pagePath" placeholder="输入跳转路径"></el-input>
          </div>
          <!-- <div class="h5link-row">
          <label class="h5link-title h5link-dynamic-title">动态参数（选填）</label>
          <div class="h5-table">
            <table cellspacing="0" cellpadding="0" border="0" class=" el-table el-table__header">
              <colgroup>
                <col name="el-table_1_column_1" width="359">
                <col name="el-table_1_column_2" width="359">
                <col name="el-table_1_column_3" width="359">
                <col name="gutter" width="0">
              </colgroup>
              <thead class="has-gutter">
                <tr class="">
                  <th colspan="1" rowspan="1" class="el-table_1_column_1     is-leaf">
                    <div class="cell">GIC参数</div>
                  </th>
                  <th colspan="1" rowspan="1" class="el-table_1_column_2     is-leaf">
                    <div class="cell">第三方H5</div>
                  </th>
                  <th colspan="1" rowspan="1" class="el-table_1_column_3     is-leaf">
                    <div class="cell">操作</div>
                  </th>
                  <th class="gutter" style="width: 0px; display: none;"></th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>
                    <el-select size="small" class="dynamic-param-select" v-model="dynamicRow.key" clearable placeholder="请选择参数" @change="dynamicChange($event)">
                      <el-option
                      v-for="item in h5linkObj.dynamicParaOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                      </el-option>
                    </el-select>
                  </td>
                  <td>
                    <el-input size="small" class="h5-el-input" v-model="dynamicRow.value" clearable type="text" @keyup.native="(value) => dynamicBlur(value)" placeholder="请输入参数"></el-input>
                  </td>
                  <td><el-button type="text" @click.stop="addDynamic()">添加</el-button></td>
                </tr>
                <template v-for="(dynamicItem,index) in dynamicList">
                  <tr>
                    <td>
                      <template v-if="!dynamicItem.editAble">{{dynamicItem.key}}</template>
                      <template v-if="dynamicItem.editAble">
                        <el-select size="small" class="dynamic-param-select" v-model="dynamicItem.selectKey" placeholder="请选择参数">
                          <el-option
                          v-for="item in h5linkObj.dynamicParaOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                          </el-option>
                        </el-select>
                      </template>
                    </td>
                    <td>
                      <template v-if="!dynamicItem.editAble">{{dynamicItem.value}}</template>
                      <template v-if="dynamicItem.editAble">
                         <el-input size="small" class="h5-el-input" v-model="dynamicItem.inputValue" type="text" placeholder="请输入参数"></el-input>
                      </template>
                    </td>
                    <td>
                      <template v-if="dynamicItem.editAble">
                        <el-button type="text" @click.stop="confirmDynamic(index,dynamicItem)">确认</el-button>
                        <el-button type="text" @click.stop="cancleDynamic(index,dynamicItem)">取消</el-button>
                      </template>
                      <template v-if="!dynamicItem.editAble">
                        <el-button type="text" @click.stop="editDynamic(index,dynamicItem)">编辑</el-button>
                        <el-button type="text" @click.stop="delDynamic(index)">删除</el-button>
                      </template>
                    </td>
                  </tr>
                </template>
              </tbody>
            </table>
          </div>
        </div> -->
        </div>
      </div>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="cancelLinkSelect">取 消</el-button> -->
        <el-button type="primary" @click="confirmLinkSelect">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import qs from 'qs';
export default {
  name: 'links-tool-full',
  props: ['linkVisible', 'showType', 'projectName', 'linkData'],
  data() {
    return {
      // 回显数据
      rewriteData: {},
      treeData: [],
      goodsTreeVisible: false,
      cardUrl: '',
      // 项目名
      cardLimit: 1,
      disabledList: [],
      pname: 'marketing',
      repProjectName: 'marketing', // 项目名
      linkShowType: 0, //传参数判断显示类型
      activeName: 'first',
      // ---------------------------
      twoLevelVisible: false, // 二级下拉
      threeLevelVisible: false, // 三级整个

      cardLinksVisible: false, // 积分商城礼品或卡券
      cardType: '', // 积分商城礼品或卡券 true 表示卡券 否则就是礼品
      giftName: '', // 礼品名称
      cardName: '', // 卡券名称
      cardOptions: [], // 卡券分类
      giftOptions: [], // 礼品分类
      cardVal: '',
      giftVal: '',
      cardList: [], // 优惠券

      // 链接类型
      linksType: '',
      linksTypeOptions: [
        // {
        //   id: '1',
        //   value: 'shoplink',
        //   label: '商城链接'
        // },
        // {
        //   id: '2',
        //   value: 'memberlink',
        //   label: '会员功能链接'
        // },
        // {
        //   id: '3',
        //   value: 'definelink',
        //   label: '自定义页面'
        // },
        // {
        //   id: '4',
        //   value: 'h5link',
        //   label: 'H5页面'
        // },
        // {
        //   id: '5',
        //   value: 'otherlink',
        //   label: '其他小程序'
        // }
      ],
      // 二级数据
      twoLevelValue: '',
      twoLevelOptions: [
        // {
        //   id: '1',
        //   value: 'shoplink',
        //   label: '商城链接'
        // },
      ],
      // 三级数据
      threeLeveloneVisible: false, // 三级中第一个下拉单选
      threeLevelTreeVisible: false, // 三级中第二个下拉树形结构
      threeLevelSearchVisible: false, // 三级中第三个搜索下拉
      threeLevelValue: '',
      threeLevelOptions: [
        // {
        //   id: '1',
        //   value: 'shoplink',
        //   label: '商城链接'
        // },
      ],
      // h5link
      h5linkVisible: false,
      h5linkObj: {
        name: '',
        url: '',
        fixParam: '',
        share: false, // 分享开关默认false->0: 关闭; true->1: 开启
        shareWebType: '0', // 0：当前展示的页面, 1：分享出去的页面
        shareUrl: '', // 分享的页面链接
        dynamicPara: '',
        dynamicParaOptions: [
          // 2018.6.12 动态参数目前让写页面
          {
            value: 'openid',
            label: 'openid'
          },
          {
            value: 'unionid',
            label: 'unionid'
          },
          {
            value: 'wxOpenid',
            label: 'wxOpenid'
          },
          {
            value: 'appkey',
            label: 'appkey'
          },
          {
            value: 'enterpriseId',
            label: 'enterpriseId'
          },
          {
            value: 'appid',
            label: 'appid'
          },
          {
            value: 'memberId',
            label: 'memberId'
          }
        ],
        // 进入条件
        conditionType: '0',
        conditionTypeOptions: [
          {
            value: '0',
            label: '不限'
          },
          {
            value: '1',
            label: '开卡会员'
          },
          {
            value: '2',
            label: '认证会员'
          }
        ]
      },

      dynamicRow: {
        key: '',
        value: '',
        selectKey: '',
        inputValue: '',
        editAble: false
      },

      dynamicList: [],

      // ---------------------------
      //第三方小程序
      thirdlinkVisible: false,
      thirdObj: {
        name: '',
        pagePath: '',
        appid: ''
      },

      // ---------------------------
      // 父组件传递的 props
      mylinkToolsVisible: false,

      // 商品链接
      goodsLinksVisible: false,
      searchGoods: '',
      category: null,
      // 品类
      categoryOptions: [
        // {
        //   key: 'a',
        //   name: 'a',
        //   subOptions: [ {
        //     key: 'aa',
        //     name: 'aa',
        //   } ],
        // }
      ],
      normalizer(node /*, id */) {
        // there is an extra `id` argument,
        // which could be useful if you have multiple instances
        // of vue-treeselect this share the same `normalizer` function
        return {
          id: node.key,
          label: node.name,
          children: node.subOptions
        };
      },

      // 商品列表数据
      selectGoodId: '',
      goodsList: [
        // {
        //   id:'111',
        //   proName: '美商海盗船Gaming系列 K70 RGB Rapidfire',
        //   proCode: "errerr",
        //   mallProImageUrl: 'https://pic01-10001430.image.myqcloud.com/adb6387e-a3f4-4b7f-a7dd-1b7fe242f9f7',
        //   mallProSpuPrice: 567
        // }
      ],
      // 分页
      currentPage: 1, // 当前页
      pageSize: 9, // 一页显示的个数
      total: 0, // 总数

      // 分类
      classify: null,
      classifyOptions: [
        // {
        //   key: 'b',
        //   name: 'b',
        //   subOptions: [ {
        //     key: 'bb',
        //     name: 'bb',
        //   } ],
        // }
      ],

      // 商品分类
      goodsCategory: null,
      goodsCategoryOptions: [
        // {
        //   key: 'a',
        //   name: 'a',
        //   subOptions: [
        //     {
        //       key: 'aa',
        //       name: 'aa',
        //     }
        //   ],
        // }
      ],

      // 保存需要的参数
      oneLevelTypeValue: '',
      twoLevelSelectValue: '',
      threeLevelSelectValue: '',

      // 触发传递的对象
      selectLinkObj: {
        id: '',
        name: '',
        url: '',
        params: '',
        share: 0,
        pagePath: ''
      },
      // 获取 location origin
      baseUrl: '',

      // 会员认证
      pageBound: 1,
      callback: {},
      // 选择自定义页面时，二级菜单需要分页查询
      definePageCurrent: 1, // 二级菜单分页页面
      definePageTotal: 1, // 二级菜单分页总页数
      // 跳转链接
      documentHref: 'http://doc.demogic.com/doc/web/#/41?page_id=6449'
    };
  },
  directives: {
    loadmore: {
      inserted(el, binding) {
        const SELECTDOWN_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
        SELECTDOWN_DOM.addEventListener('scroll', function() {
          const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight;
          if (CONDITION) {
            binding.value();
          }
        });
      }
    }
  },
  beforeMount() {
    this.chooseFlag = false;
    this.giftFlag = false;
    var host = window.location.origin;
    this.baseUrl = host.indexOf('localhost') > -1 ? 'http://gicdev.demogic.com' : host;
  },
  methods: {
    // H5对接文档
    checkDocument() {
      //
    },
    getMore() {
      // 以后如果其他类型的二级下拉列表也需要加载更多，可以在这里执行查询数据的请求
      if (this.oneLevelTypeValue == 6) {
        if (this.definePageCurrent + 1 <= this.definePageTotal) {
          this.definePageCurrent++;
          this.getDefinePage();
        }
      }
    },
    changeVisible() {
      // 因为确认之后弹窗关闭也是会触发close事件
      // 如果直接close会有id 如果确认之后是没有id
      if ('id' in this.selectLinkObj) {
        this.$emit('linkSelect', {});
      }
      this.$emit('update:linkVisible', false);
      this.resetAll();
    },
    handlePaddGift(list) {
      // 拼接id
      this.giftFlag = true;
      this.giftName = list.proName;
      this.giftUrl = list.integralMallProId;
    },

    handlePassId(row) {
      this.chooseFlag = true;
      // 先保存下来
      this.cardName = row.cardName;
      this.cardUrl = row.integralMallProId;
    },
    // --------------------------------------------------
    // 选择类型改变 (一级选择,保存选择类型)
    linksTypeChange: function(e) {
      console.log(e);
      this.linkId = e;
      if (this.linkId == 50) {
        // 直播间
        this.axios.get(`${this.baseUrl}/api-plug/list-wx-lives?requestProject=gic-web`).then(res => {
          if (res.data.errorCode === 0) {
            const data = res.data.result.result;
            if (data && data.length) {
              this.twoLevelOptions = data.map(el => ({
                ...el,
                label: el.name,
                value: el.roomid
              }));
            } else {
              this.twoLevelOptions = [];
            }
          } else {
            this.twoLevelOptions = [];
          }
        });
      }
      var selectOneItem = '';
      this.linksTypeOptions.forEach(function(ele, inde) {
        if (ele.linkId == e) {
          selectOneItem = ele;
        }
      });
      // 保存选择的类型
      this.oneLevelTypeValue = selectOneItem.type;

      // 判断出现下拉内容/h5部分

      // 每次修改选择类型,清空已选择的值
      this.dynamicRow = {
        key: '',
        value: '',
        selectKey: '',
        inputValue: '',
        editAble: false
      };
      this.dynamicList = [];

      this.thirdObj = {
        name: '',
        appid: '',
        pagePath: ''
      };
      this.selectLinkObj.name = '';
      this.selectLinkObj.url = '';
      this.selectLinkObj.params = '';
      this.twoLevelSelectValue = '';
      this.threeLevelSelectValue = '';
      this.twoLevelValue = '';
      this.h5linkObj.pagePath = '';
      this.h5linkObj.name = '';
      this.h5linkObj.url = '';
      this.goodType = '';

      // 如果是 h5,二级,三级隐藏,
      var type = selectOneItem.type == 5 || selectOneItem.type == 14 ? true : false;
      if (this.linkId !== 'yueshi') {
        this.setOneLevelVisible(type, selectOneItem);
        this.h5linkObj = Object.assign({}, this.h5linkObj, {
          name: this.rewriteData.name || '',
          url: this.rewriteData.url || '',
          conditionType: this.rewriteData.conditionType,
          share: this.rewriteData.share == 1,
          shareWebType: isNaN(Number(this.rewriteData.shareWebType)) ? '0' : String(this.rewriteData.shareWebType),
          shareUrl: this.rewriteData.shareUrl || ''
        });
        this.rewriteData = Object.assign({}, this.rewriteData, {
          name: '',
          url: '',
          conditionType: '0',
          share: 0,
          shareWebType: 0,
          shareUrl: ''
        });
      } else {
        this.twoLevelVisible = false;
        this.thirdlinkVisible = false;
        this.h5linkVisible = false;
      }
      this.pageBound = 1;
      this.callback = {};
    },

    // set onelevel visible
    setOneLevelVisible(type, selectOneItem) {
      this.visibleType = null;
      this.cardLinksVisible = false;
      // 设置选择的 id
      this.selectLinkObj.id = selectOneItem.linkId;
      if (type) {
        if (selectOneItem.type == 5 || selectOneItem.type == 14) {
          this.h5linkVisible = true; // h5 链接参数输入部分显示
          this.thirdlinkVisible = false; // 第三方小程序
        }
        if (selectOneItem.type == 7) {
          this.h5linkVisible = false; // h5 链接参数输入部分显示
          this.thirdlinkVisible = true; // 第三方小程序
        }

        this.twoLevelVisible = false; // 二级部分隐藏
        this.threeLevelVisible = false; // 三级部分隐藏
        this.goodsLinksVisible = false; // 商品链接列表部分
      } else {
        // 不是 h5,显示二级,隐藏三级
        this.h5linkVisible = false; // h5 链接参数输入部分隐藏
        this.thirdlinkVisible = false; // 第三方小程序
        this.twoLevelVisible = true; // 二级部分显示
        this.twoLevelOptions = [];
        this.threeLevelVisible = false; // 三级部分隐藏
        this.goodsLinksVisible = false; // 商品链接列表部分
        this.twoLevelValue = ''; // 清空二级数据
        this.threeLevelValue = ''; // 清空三级数据

        // 如果是自定义
        if (selectOneItem.type == 6) {
          this.selectLinkObj.id = selectOneItem.linkId;
          // this.selectLinkObj.name = selectOneItem.label;
          this.selectLinkObj.url = selectOneItem.content;
          this.definePageCurrent = 1;
          this.getDefinePage();
          return false;
        } else if (selectOneItem.type == 7) {
          this.h5linkVisible = false; // h5 链接参数输入部分显示
          this.thirdlinkVisible = true; // 第三方小程序
          this.threeLevelVisible = false; // 三级部分隐藏
          this.getAppList();
        }
        // 清空设置选择的 id
        if (this.oneLevelTypeValue !== 7) {
          this.selectLinkObj.id = '';
        }

        // 获取二级列表数据
        this.getLinksList(selectOneItem.linkId, 2);
      }
    },

    // twoLevelValueChange (二级选择,保存选择类型)
    twoLevelValueChange(e) {
      console.log(e, this.linkId);
      if (this.linksType == 50) {
        // 直播间
        this.threeLevelVisible = false;
        return;
      }
      if (e == 'product_category_link') {
        // 商品分类链接
        this.middleGoodId = e;
        this.goodType = 10;
        this.threeLevelVisible = true;
        this.threeLeveloneVisible = false;
        this.goodsTreeVisible = true;
        this.cardUrl = null;
      } else if (e == 'mall_customize_page') {
        // 自定义页面
        this.middleGoodId = e;
        this.goodType = 11;
        this.threeLevelVisible = true;
        this.threeLeveloneVisible = true;
        this.goodsTreeVisible = false;
        this.pageId = null;
      } else if (e == 1) {
        this.goodType = 1;
        this.threeLevelVisible = false;
        this.goodsTreeVisible = false;
        this.threeLeveloneVisible = true;
      } else {
        this.threeLevelVisible = false;
        this.threeLeveloneVisible = true;
        this.goodsTreeVisible = false;
      }

      this.goodsLinksVisible = false;
      this.visibleType = null;
      // 清空已经选择
      this.selectLinkObj.name = '';
      this.selectLinkObj.url = '';
      this.cardLinksVisible = false;
      // 判断自定义
      if (this.oneLevelTypeValue == 6) {
        let selectDefineItem = '';
        this.twoLevelOptions.forEach(function(ele, index) {
          if (e == ele.id) {
            selectDefineItem = ele;
          }
        });
        this.selectLinkObj.name = selectDefineItem.label;
        this.selectLinkObj.params = {
          pageId: e
        };
        return;
      }
      var selectTwoItem = '';
      this.twoLevelOptions.forEach(function(ele, index) {
        if (e == ele.linkId) {
          selectTwoItem = ele;
        }
      });
      // 每次选择清空原有选择参数
      this.selectLinkObj.params = '';
      // 设置选择的 id
      if (this.oneLevelTypeValue !== 7) {
        this.selectLinkObj.id = e;
      }
      this.threeLevelValue = '';
      this.cardUrl = '';
      this.tagName = '';
      this.selectGoodId = '';
      this.pageBound = 1;
      this.callback = {};

      // 判断是否结束, 1:结束;
      if (selectTwoItem.type == 1 || selectTwoItem.type == 4 || selectTwoItem.type == 6 || this.oneLevelTypeValue == 7) {
        this.threeLevelVisible = false; // 三级部分隐藏
        this.threeLevelValue = ''; // 清空三级数据
        this.twoLevelSelectValue = ''; // 清空门店签到
        this.threeLevelSelectValue = ''; //清空商品分类
        // 清空已经选择
        this.selectLinkObj.name = '';
        this.selectLinkObj.url = '';
        // 如果选择商品链接
        if (selectTwoItem.type == 4) {
          this.currentPage = 1;
          this.getGoodsList(); // 获取商品列表
          this.getGoodsCategory(); // 获取商品品类
          this.getGoodsClassify(); // 获取商品分类

          // this.getGoodsType(); // 商品分类链接
          // this.getGoodsPage(); // 商品自定义页面

          this.threeLevelVisible = false; // 三级部分隐藏
          this.goodsLinksVisible = true; // 商品链接列表部分显示
          return false;
        }
        if (this.rewriteData.callback) {
          this.pageBound = this.rewriteData.callback.type;
          this.callback = JSON.parse(JSON.stringify(this.rewriteData.callback));
          this.rewriteData.callback = {};
        }
        this.twoLevelOptions.forEach(function(ele, index) {
          if (e == ele.value) {
            this.selectLinkObj.name = ele.label;
            this.selectLinkObj.url = ele.content;
          }
        });
      } else if (this.goodType == 10) {
        if (this.rewriteData.goodsTreeVisible == 1) {
          const params = this.rewriteData.params || {};
          this.cardUrl = params.tagid;
          this.tagName = params.title;
          this.rewriteData.goodsTreeVisible = 0;
        }
        // 商品分类链接
        this.getGoodsLink();
      } else if (this.goodType == 11) {
        // 商品自定义页面
        this.threeLevelVisible = true;
        if (this.rewriteData.threeLevelValue) {
          this.threeLevelValue = this.rewriteData.threeLevelValue;
          this.rewriteData.threeLevelValue = '';
        }
        this.getGoodsPage();
      } else {
        // 判断三级中下拉/下拉树形/搜索下拉
        this.goodsLinksVisible = false; // 商品列表隐藏
        this.threeLevelVisible = true; // 三级部分显示
        this.threeLevelValue = ''; // 清空三级数据
        this.twoLevelSelectValue = '';
        this.threeLevelSelectValue = '';
        let twoType = selectTwoItem.type;
        // 判断三级显示的下拉组件
        this.setThreeVisible(twoType, selectTwoItem);

        // 如果是门店,直接返回,需要输入后搜索出现下拉列表
        if (twoType == 2) {
          this.twoLevelSelectValue = 'sign';
          return false;
        }
        if (twoType == 3) {
          this.twoLevelSelectValue = 'goodsCate';
          this.getGoodsClassify();
          return false;
        }
        // 获取三级列表数据
        this.getLinksList(selectTwoItem.linkId, 3, twoType);
      }
      // this.pageBound = 1;
      // this.callback = {};
    },

    // sy 商品分类链接
    getGoodsLink() {
      this.axios
        .get(`${this.baseUrl}/api-plug/list-mall-product-tag?requestProject=gic-web`)
        .then(res => {
          if (res.data.errorCode === 0) {
            const data = res.data.result;
            if (data && data.length) {
              this.treeData = data;
            } else {
              this.treeData = [];
            }
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // sy 商品自定义页面
    getGoodsPage() {
      this.axios
        .get(`${this.baseUrl}/api-plug/list-mall-page?requestProject=gic-web`)
        .then(res => {
          if (res.data.errorCode === 0) {
            const data = res.data.result;
            if (data && data.length) {
              // definePage 自定义页面
              this.threeLevelOptions = data.map(val => ({
                ...val,
                label: val.pageName,
                value: val.pageId
              }));
            } else {
              this.threeLevelOptions = [];
            }
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    // set threelevel visible
    setThreeVisible(type, selectTwoItem) {
      switch (type) {
        // 如果下拉显示
        case 0: // 单选
          this.threeLeveloneVisible = true; // 三级中第一个下拉单选
          this.threeLevelTreeVisible = false; // 三级中第二个下拉树形结构
          this.threeLevelSearchVisible = false; // 三级中第三个搜索下拉
          break;
        case 2: // 搜索下拉
          this.threeLeveloneVisible = false; // 三级中第一个下拉单选
          this.threeLevelTreeVisible = false; // 三级中第二个下拉树形结构
          this.threeLevelSearchVisible = true; // 三级中第三个搜索下拉
          // 设置链接 门店签到
          this.selectLinkObj.name = selectTwoItem.name;
          this.selectLinkObj.url = selectTwoItem.content;
          break;
        case 3: // 树形结构
          this.threeLevelValue = null;
          this.threeLeveloneVisible = false; // 三级中第一个下拉单选
          this.threeLevelTreeVisible = true; // 三级中第二个下拉树形结构
          this.threeLevelSearchVisible = false; // 三级中第三个搜索下拉
          // 设置链接 商品分类
          this.selectLinkObj.name = selectTwoItem.name;
          this.selectLinkObj.url = selectTwoItem.content;
          break;
      }
    },

    // 获取商品品类
    getGoodsCategory() {
      var para = {
        filterGoods: 1,
        parentId: '',
        requestProject: this.repProjectName
      };
      this.axios
        .post(this.baseUrl + '/api-mall/list_mall_goods_category', qs.stringify(para))
        .then(res => {
          var resData = res.data;
          var onelevelCategory = '';
          if (resData.errorCode == 0) {
            resData.result.forEach(function(ele, index) {
              if (ele.parentId == '-1') {
                ele.subOptions = [];
                ele.key = ele.mallCategoryId;
                onelevelCategory = ele;
                resData.result.splice(index, 1);
              }
            });
            const list = resData.result;
            const 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) {
                  ele.subOptions = [];
                  ele.subOptions.push(el);
                  list.splice(ind, 1);
                }
              });
            });

            list.forEach(function(ele, index) {
              onelevelCategory.subOptions.push(ele);
            });
            this.categoryOptions = [];
            this.categoryOptions.push(onelevelCategory);

            return false;
          }

          this.$message.error({
            duration: 1000,
            message: resData.message
          });
        })
        .catch(function(error) {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    // 获取商品分类
    getGoodsClassify() {
      var para = {
        requestProject: this.repProjectName
      };
      this.axios
        .post(this.baseUrl + '/api-mall/list_mall_goods_tag_tree', qs.stringify(para))
        .then(res => {
          const resData = res.data;
          if (resData.errorCode == 0) {
            let list = [resData.result];

            // let lists = resData.result;

            // list.forEach(function(ele,index) {
            //    ele.subOptions = [];
            //    ele.name = ele.tagName;
            //    ele.key = ele.mallProTagId;
            //    lists.forEach(function(el,ind) {
            //       ele.name = ele.tagName;
            //       ele.key = ele.mallProTagId;
            //       if(el.parentId == ele.mallProTagId ){
            //         ele.subOptions.push(el)
            //       }
            //    })
            // })
            // this.goodsCategoryOptions = [];
            // this.classifyOptions = [];
            // list.forEach(function(ele,index){
            //   if (ele.parentId == '-1') {
            //     this.goodsCategoryOptions.push(ele);
            //     this.classifyOptions.push(ele);
            //   }
            // })

            list.forEach(function(ele, index) {
              ele.name = ele.tagName;
              ele.key = ele.mallProTagId;
              if (!!ele.childTagList) {
                ele.subOptions = this.checkChildren(ele.childTagList);
              }
            });

            this.goodsCategoryOptions = list;
            this.classifyOptions = list;
            // this.classifyOptions = list;
            return;
          }

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

    checkChildren(childTagList) {
      if (!!childTagList) {
        childTagList.forEach(function(ele, index) {
          ele.name = ele.tagName;
          ele.key = ele.mallProTagId;
          if (!!ele.childTagList) {
            ele.subOptions = this.checkChildren(ele.childTagList);
          }
        });
      }
      return childTagList;
    },

    // threeLevelValueChange
    threeLevelValueChange(e) {
      // var this = this;
    },

    // threeSingleValueChange
    threeSingleValueChange(e) {
      // 是那个类型的
      if (this.linkId == 16) {
        this.pageId = e;
        let item = '';
        this.threeLevelOptions.forEach(function(ele, index) {
          if (e == ele.pageId) {
            item = ele;
          }
        });
        this.pageName = item.pageName;
      }
      this.giftType = e;
      if (this.giftType == 'coup') {
        this.visibleType = 8;
      } else if (this.giftType == 'gift') {
        this.visibleType = 9;
      }
      var selThreeItem = '';
      this.threeLevelOptions.forEach(function(ele, index) {
        if (e == ele.linkId) {
          selThreeItem = ele;
        }
      });
      // 非门店签到
      this.selectLinkObj.id = e;
      this.selectLinkObj.url = selThreeItem.content;
      this.selectLinkObj.name = selThreeItem.name;
      // #sy 三级下拉
      // 卡券
      if (this.visibleType == 8) {
        this.cardLinksVisible = true;
        this.cardType = true;
      } else if (this.visibleType == 9) {
        // 礼品
        this.cardLinksVisible = true;
        this.cardType = false;
      }
    },
    // 卡券列表
    // 礼品列表

    // 获取自定义列表
    getDefinePage() {
      const para = {
        pageType: 1,
        status: 1,
        pageSize: 50,
        currentPage: this.definePageCurrent,
        requestProject: this.repProjectName
      };
      this.axios.post(this.baseUrl + '/api-admin/list-page', qs.stringify(para)).then(res => {
        const { errorCode, message, result } = res.data || {};
        if (errorCode != 0) {
          return this.$message.error(message);
        }
        this.definePageTotal = result.totalPage;
        if (this.definePageCurrent == 1) {
          this.twoLevelOptions = [];
        }
        if (Array.isArray(result.result)) {
          const list = result.result.map(ele => {
            return Object.assign({}, ele, {
              id: ele.pageId,
              label: ele.title,
              value: ele.pageId
            });
          });
          this.twoLevelOptions = this.twoLevelOptions.concat(list);
          if (this.rewriteData.twoLevelValue) {
            this.twoLevelValue = this.rewriteData.twoLevelValue;
            this.rewriteData.twoLevelValue = '';
            this.twoLevelValueChange(this.twoLevelValue);
          }
        }
      });
    },

    // 查询第三方小程序列表
    getAppList() {
      this.axios
        .post(this.baseUrl + '/api-plug/applet-app-search?requestProject=gic-web')
        .then(res => {
          var resData = res.data;
          let list = [];
          if (resData.errorCode == 0) {
            resData.result.forEach(v => {
              if (v.appStatus === 1) {
                list.push({
                  id: v.appletAppId,
                  label: v.appName,
                  value: v.appId
                });
              }
            });
            this.twoLevelOptions = list;
            if (this.rewriteData.twoLevelValue) {
              this.twoLevelValue = this.rewriteData.twoLevelValue;
              this.rewriteData.twoLevelValue = '';
            }
          } else {
            this.$message.error({
              duration: 1000,
              message: res.message
            });
          }
        })
        .catch(error => {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    // --------------------------------------------------

    // -------------------------------------------
    // 选择树形节点方法

    // 商品链接部分 categorySelect
    categorySelect(node, id) {
      this.category = node.key;
      // 重新获取商品列表
      // this.getGoodsList();
      if (this.currentPage == 1) {
        this.getGoodsList();
      } else {
        this.currentPage = 1;
        this.getGoodsList();
      }
    },
    beforeClearCategory(node, id) {
      this.category = null;
      // 重新获取商品列表
      // this.getGoodsList();
      if (this.currentPage == 1) {
        this.getGoodsList();
      } else {
        this.currentPage = 1;
        this.getGoodsList();
      }
    },

    loadOptions({ action, parentNode, callback }) {
      // Typically, do the AJAX stuff here.
      // Once the server has responded,
      // assign children options to the parent node & call the callback.
      // We just use `setTimeout()` here to simulate an async operation
      // instead of requesting a real API server for demo purpose.
      console.log(action, parentNode, callback);
      if (action === 'LOAD_CHILDREN_OPTIONS') {
        if (parentNode.key) {
          this.getChildrenNode(parentNode, parentNode.key);
        }
      }
    },

    // 获取子节点方法
    getChildrenNode(parentNode, parentId) {
      var para = {
        filterGoods: 1,
        parentId: parentId,
        requestProject: this.repProjectName
      };
      this.axios
        .post(this.baseUrl + '/api-mall/list_mall_goods_category', qs.stringify(para))
        .then(res => {
          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;
          }
          this.$message.error({
            duration: 1000,
            message: res.message
          });
        })
        .catch(function(error) {
          console.log(error);
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    // classifySelect  分类
    classifySelect(node, id) {
      this.classify = node.key;
      // 重新获取商品列表
      // this.getGoodsList();
      if (this.currentPage == 1) {
        this.getGoodsList();
      } else {
        this.currentPage = 1;
        this.getGoodsList();
      }
    },
    beforeClearClassify(node, id) {
      console.log(node, id, this.classify);
      this.classify = null;
      // 重新获取商品列表
      // this.getGoodsList();
      if (this.currentPage == 1) {
        this.getGoodsList();
      } else {
        this.currentPage = 1;
        this.getGoodsList();
      }
    },

    // 商品分类 goodsCategorySelect
    goodsCategorySelect(node, id) {
      // var this = this;
      // 调用
      // this.selectLinkItem()
    },

    // --------------------------------------------

    // 分页
    linkSizeChange(val) {
      this.pageSize = val;
      // 请求商品列表
      this.getGoodsList();
    },

    // 页码变化触发
    linkCurrentChange(val) {
      this.currentPage = val;
      // 请求商品列表
      this.getGoodsList();
    },

    // 选择商品链接
    selectGoodLinkItem(item) {
      this.selectGoodId = item.mallProId;
      // 调用函数传递链接/名字
      this.selectLinkItem(item);
    },

    // 选择链接以后调用函数
    selectLinkItem(item) {
      this.selectLinkObj.name = item.proName;
      this.selectLinkObj.url = item.url;
      this.selectLinkObj.params = { proId: item.mallProId }; // 2018.6.28修改参数 proId
      // this.$emit('linkSelect')
    },

    // 搜索输入
    toSearchInput: function(value) {
      // 搜索重置当前页 为 1

      if (this.currentPage == 1) {
        this.getGoodsList();
      } else {
        this.currentPage = 1;
        this.getGoodsList();
      }
    },
    // 清空输入
    clearInput: function(e) {
      // 搜索重置当前页 为 1

      if (this.currentPage == 1) {
        this.getGoodsList();
      } else {
        this.currentPage = 1;
        this.getGoodsList();
      }
    },

    // 获取商品列表
    getGoodsList() {
      var para = {
        pageNum: this.currentPage,
        searchparams: this.searchGoods || '',
        pageSize: this.pageSize,
        mallCategoryId: this.category || '',
        tagId: this.classify || '', // 分类
        requestProject: this.repProjectName
      };

      // this.currentPage = 1;
      // this.pageSize = 10;
      // this.total = 50;

      this.axios
        .post(this.baseUrl + '/api-mall/page-mall-goods', qs.stringify(para))
        .then(res => {
          var resData = res.data;
          if (resData.errorCode == 0) {
            this.goodsList = resData.result.result;
            this.total = resData.result.totalCount;
            if (this.rewriteData.params && this.rewriteData.params.proId) {
              const goods = this.goodsList.filter(el => el.mallProId == this.rewriteData.params.proId);
              this.rewriteData.params.proId = '';
              if (goods.length > 0) this.selectGoodLinkItem(goods[0]);
            }
            return;
          }

          this.$message.error({
            duration: 1000,
            message: resData.message
          });
        })
        .catch(function(error) {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    // 搜索后出现下拉列表
    // 搜索
    remoteMethod(query) {
      if (query !== '') {
        // 获取搜索列表数据
        this.getStoreList(query, this.threeLevelValue);
      } else {
        this.threeLevelOptions = [];
      }
    },

    // h5 分享开关
    shareSwitch(e, obj) {
      console.log(e, obj);
    },

    // // 取消操作
    // cancelLinkSelect() {
    //   var this = this
    //   this.$confirm('确认关闭?', '', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       type: ''
    //     }).then(() => {
    //       this.$emit('linkSelect')
    //     }).catch(() => {
    //     });
    // },

    // 确认操作
    confirmLinkSelect() {
      if (this.pageBound == 2) {
        let bool = this.$refs.memberAuth.confirmLinkSelect();
        if (bool === false) return;
      }

      this.selectLinkObj.linksType = this.linksType;
      this.selectLinkObj.twoLevelValue = this.twoLevelValue;
      this.selectLinkObj.threeLevelValue = this.threeLevelValue;
      this.selectLinkObj.goodsTreeVisible = Number(this.goodsTreeVisible) || 0;
      setTimeout(_ => {
        console.log(this.linkId, this.linksType, this.twoLevelValue);

        if (this.linksType == 50) {
          // { "id": "50", "name": "直播", "pagePath": "", "params": { "roomId": "1" }, "url": "" }
          if (!this.twoLevelValue) {
            this.$message.error({
              duration: 1000,
              message: '请选择链接'
            });
            return false;
          }
          let name = this.twoLevelOptions.find(el => el.value == this.twoLevelValue);
          this.selectLinkObj = {
            id: this.linksType,
            name: name.name || '',
            pagePath: '',
            params: {
              room_id: this.twoLevelValue
            },
            url: ''
          };

          this.transData();
          return;
        }

        // 如果选择 h5 判断选择的链接
        if (this.oneLevelTypeValue == 5 || this.oneLevelTypeValue == 14) {
          if (!this.h5linkObj.name.trim() || !this.h5linkObj.url.trim()) {
            this.$message.error({
              duration: 1000,
              message: '请填写链接内容'
            });
            return;
          }
          if (!!this.h5linkObj.share && this.h5linkObj.shareWebType == 1 && !this.h5linkObj.shareUrl && this.oneLevelTypeValue != 14) {
            this.$message.error({
              duration: 1000,
              message: '请填写分享链接'
            });
            return;
          }
          // 校验网址
          const regHttps = /(https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
          const httpSurl = 'https://' + this.h5linkObj.url;
          if (this.oneLevelTypeValue == 5 && !regHttps.test(httpSurl)) {
            this.$message.error({
              duration: 1000,
              message: '输入的网址不合法!'
            });
            return;
          }
          this.selectLinkObj.share = this.h5linkObj.share == true ? 1 : 0;
          this.selectLinkObj.conditionType = this.h5linkObj.conditionType;
          this.selectLinkObj.name = this.h5linkObj.name;
          this.selectLinkObj.url = this.oneLevelTypeValue == 14 ? this.h5linkObj.url : httpSurl; // +'?'+this.h5linkObj.fixParam+'&'+this.h5linkObj.dynamicPara;
          // 去掉固定参数 20180912 this.h5linkObj.fixParam
          this.selectLinkObj.params = '';
          if (!!this.dynamicList.length) {
            let h5DataList = JSON.parse(JSON.stringify(this.dynamicList));
            h5DataList.forEach(function(ele, index) {
              delete ele.editAble;
              delete ele.selectKey;
              delete ele.inputValue;
            });
            this.selectLinkObj.params = h5DataList;
          }

          if (!!this.h5linkObj.share && this.oneLevelTypeValue != 14) {
            this.selectLinkObj.shareWebType = this.h5linkObj.shareWebType;
            if (this.h5linkObj.shareWebType == 1) {
              this.selectLinkObj.shareUrl = this.h5linkObj.shareUrl;
            }
          }
          // this.selectLinkObj.fixParam = this.h5linkObj.fixParam;
          // this.selectLinkObj.dynamicPara = this.h5linkObj.dynamicPara;
          // 触发父组件方法,传递参数
          this.transData();
          return;
        }

        // 如果是第三方小程序
        if (this.oneLevelTypeValue == 7) {
          if (!this.twoLevelValue) {
            this.$message.error({
              duration: 1000,
              message: '请选择第三方小程序'
            });
            return false;
          }
          // const reg = /^(http|https|www)(:\/\/)?.[A-Za-z]+.[A-Za-z]+.*/;
          // if (!reg.test(this.thirdObj.pagePath)) {
          //   this.$message.error({
          //     duration: 1000,
          //     message: "输入的网址不合法!"
          //   })
          //   return;
          // }
          this.twoLevelOptions.forEach(v => {
            if (v.value === this.twoLevelValue) {
              this.selectLinkObj.name = v.label;
              this.selectLinkObj.appid = v.value;
              // this.selectLinkObj.id = selectOneItem.linkId;
              // this.selectLinkObj.id = v.id;
            }
          });
          this.selectLinkObj.pagePath = this.thirdObj.pagePath;
          this.selectLinkObj.params = '';
          if (!!this.dynamicList.length) {
            let thirdDataList = JSON.parse(JSON.stringify(this.dynamicList));
            thirdDataList.forEach(function(ele, index) {
              delete ele.editAble;
              delete ele.selectKey;
              delete ele.inputValue;
            });
            this.selectLinkObj.params = thirdDataList;
          }
          // 触发父组件方法,传递参数
          this.transData();
          return;
        }

        // 如果选择的自定义页面
        if (this.oneLevelTypeValue == 6) {
          if (!this.twoLevelValue.trim()) {
            this.$message.error({
              duration: 1000,
              message: '请选择自定义页面'
            });
            return;
          }
          // 触发父组件方法,传递参数
          this.transData();
          return;
        }
        // 确定是会员功能 然后看是那个类型的
        if (this.linkId == 27) {
          if (this.visibleType == 8) {
            // 优惠券
            console.log(this.chooseFlag);
            if (this.chooseFlag) {
              this.selectLinkObj.name = '积分商城/' + this.cardName;
              this.selectLinkObj.id = this.giftType;
              this.selectLinkObj.params = {
                integralMallProId: this.cardUrl
              };
              this.transData();
              return;
            } else {
              this.$message.warning({
                duration: 1000,
                message: '请选择卡券！'
              });
              return false;
            }
          } else if (this.visibleType == 9) {
            // 礼品
            if (this.giftFlag) {
              this.selectLinkObj.name = '积分商城/' + this.giftName;
              this.selectLinkObj.id = this.giftType;
              this.selectLinkObj.params = {
                integralMallProId: this.giftUrl
              };
              this.transData();
              return;
            } else {
              this.$message.warning({
                duration: 1000,
                message: '请选择礼品！'
              });
              return false;
            }
          }
          if (this.twoLevelValue == 13) {
            this.selectLinkObj.callback = {
              ...this.callback,
              type: this.pageBound
            };
            this.transData();
            return;
          }
        }

        if (this.linkId == 16) {
          if (this.goodType == 10) {
            // 商品分类链接
            this.selectLinkObj.name = '商品分类链接/' + this.tagName;
            this.selectLinkObj.id = this.middleGoodId;
            this.selectLinkObj.params = {
              tagid: this.cardUrl,
              title: this.tagName
            };
            console.log(this.cardUrl);
            if (this.cardUrl) {
              this.transData();
            } else {
              this.$message.error({
                duration: 1000,
                message: '请选择链接'
              });
            }
            return false;
          } else if (this.goodType == 11) {
            this.selectLinkObj.name = '商城自定义页面/' + this.pageName;
            this.selectLinkObj.id = this.middleGoodId;
            this.selectLinkObj.params = {
              pageId: this.pageId,
              title: this.pageName
            };
            if (this.pageId) {
              this.transData();
            } else {
              this.$message.error({
                duration: 1000,
                message: '请选择链接'
              });
            }
            return false;
          }
          if (!this.twoLevelValue) {
            this.$message.error({
              duration: 1000,
              message: '请选择链接'
            });
          }
        }

        // 如果门店签到
        if (this.twoLevelSelectValue == 'sign') {
          if (!this.checkTwoLevel(this.twoLevelSelectValue)) {
            return false;
          }
          return false;
        }
        // 如果是商品分类
        if (this.twoLevelSelectValue == 'goodsCate') {
          if (!this.checkTwoLevel(this.twoLevelSelectValue)) {
            return false;
          }
          return false;
        }
        // 分享有赏
        if (this.linkId === 'yueshi') {
          this.selectLinkObj.id = this.linkId;
          this.selectLinkObj.name = '分享有赏';
          this.$emit('linkSelect', this.selectLinkObj);
          this.$emit('update:linkVisible', false);
          this.resetAll();
          return;
        }

        if (!!this.selectLinkObj.name && !!this.selectLinkObj.id) {
          // 触发父组件方法,传递参数
          this.transData();
        } else {
          this.$message.error({
            duration: 1000,
            message: '请选择链接'
          });
        }
      });
    },

    getMallId(item) {
      this.tagName = item.tagName;
      this.cardUrl = item.mallProTagId;
    },

    checkTwoLevel(v) {
      if (!this.threeLevelValue || !this.threeLevelValue.length) {
        this.$message.error({
          duration: 1000,
          message: '请选择' + (v == 'sign' ? '门店' : '商品分类')
        });
        return false;
      }
      this.selectLinkObj.url = this.selectLinkObj.url; // +'?'+this.threeLevelValue
      this.selectLinkObj.params = {
        storeId: this.threeLevelValue
      };
      // 触发父组件方法,传递参数
      this.transData();
    },

    // 重置所有组件
    resetAll() {
      this.cardLinksVisible = false;
      this.visibleType = null;
      this.h5linkVisible = false;
      this.thirdlinkVisible = false; // 第三方小程序
      this.linksType = '';
      this.twoLevelVisible = false; // 二级下拉
      this.threeLevelVisible = false; // 三级整个
      this.goodsLinksVisible = false; // 商品列表隐藏
      this.twoLevelValue = ''; // 清空所有选择的
      this.twoLevelSelectValue = '';
      this.threeLevelValue = ''; // 清空所有选择的

      // h5新增部分
      this.dynamicRow = {
        key: '',
        value: '',
        selectKey: '',
        inputValue: '',
        editAble: false
      };
      this.dynamicList = [];

      // 第三方小程序
      this.thirdObj = {
        name: '',
        pagePath: '',
        appid: ''
      };

      this.selectLinkObj = {
        url: '',
        name: '',
        pagePath: ''
      };
      this.currentPage = 1;
      this.total = 0;
      this.pageSize = 9;
      this.searchGoods = '';
      this.classify = null;
      this.category = null;

      this.h5linkObj.name = '';
      this.h5linkObj.url = '';
      this.h5linkObj.fixParam = '';
      this.h5linkObj.dynamicPara = '';
      this.h5linkObj.share = false;
      this.h5linkObj.shareWebType = '0'; // 0：当前展示的页面, 1：分享出去的页面
      this.h5linkObj.shareUrl = ''; // 分享的页面链接

      this.pageBound = 1;
    },

    // 触发父组件方法,传递参数
    transData() {
      console.log(this.selectLinkObj);
      this.$emit('linkSelect', this.selectLinkObj);
      this.$emit('update:linkVisible', false);
      this.resetAll();
    },

    // 获取一级列表
    getLinksList(parentId, num, twoType) {
      // 如果不传传的显示类型,设置
      twoType = twoType ? twoType : '';

      var para = {
        parentId: parentId,
        requestProject: this.repProjectName,
        linkScene: this.linkShowType
      };

      this.axios
        .post(this.baseUrl + '/api-plug/list-link-data', qs.stringify(para))
        .then(res => {
          var resData = res.data;
          if (resData.errorCode == 0) {
            this.setLevelListOptions(Array.isArray(resData.result) ? resData.result : [], num, twoType);
            return;
          }

          this.$message.error({
            duration: 1000,
            message: resData.message
          });
        })
        .catch(function(error) {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    setLevelListOptions(result, num, twoType) {
      // 设置一级
      if (num == 1) {
        result.forEach(function(ele, index) {
          ele.id = ele.linkId;
          ele.label = ele.name;
          ele.value = ele.linkId;
        });

        this.linksTypeOptions = result;
        if (this.linkData && this.linkData.id == 50) {
          this.linksType = this.linkData.id;
        }
        if (this.rewriteData.linksType) {
          this.linksType = this.rewriteData.linksType;
          this.rewriteData.linksType = '';
          this.linksTypeChange(this.linksType);
        }
        if (this.rewriteData.pagePath) {
          this.thirdObj.pagePath = this.rewriteData.pagePath;
          this.rewriteData.pagePath = '';
        }
        return;
      }
      // 设置二级
      if (num == 2 && result[0]) {
        result.forEach(function(ele, index) {
          ele.id = ele.linkId;
          ele.label = ele.name;
          ele.value = ele.linkId;
        });
        this.twoLevelOptions = result;
        if (this.rewriteData.twoLevelValue) {
          this.twoLevelValue = this.rewriteData.twoLevelValue;
          this.rewriteData.twoLevelValue = '';
          this.twoLevelValueChange(this.twoLevelValue);
        }
        return;
      }

      // 设置三级
      if (num == 3 && result[0]) {
        // 如果是分类
        // if (twoType == 3) {
        //   return false;
        // }
        // 如果是单选下拉
        if (twoType == 0) {
          result.forEach(function(ele, index) {
            ele.id = ele.linkId;
            ele.label = ele.name;
            ele.value = ele.linkId;
          });
          this.threeLevelOptions = result;
          if (this.rewriteData.params && this.rewriteData.params.integralMallProId) {
            this.cardUrl = this.rewriteData.params.integralMallProId;
            this.rewriteData.params.integralMallProId = '';
          }
          if (this.rewriteData.threeLevelValue) {
            this.threeLevelValue = this.rewriteData.threeLevelValue;
            this.rewriteData.threeLevelValue = '';
            this.threeSingleValueChange(this.threeLevelValue);
          }
        }

        return;
      }
    },

    // 获取门店列表
    getStoreList(query, threeLevelValue) {
      var para = {
        searchParam: query,
        selectedIds: threeLevelValue.toString(),
        flag: null,
        requestProject: this.repProjectName
      };

      this.axios
        .post(this.baseUrl + '/api-plug/query-store-by-code-name', qs.stringify(para))
        .then(res => {
          var resData = res.data;
          if (resData.errorCode == 0) {
            resData.result.forEach(function(ele, index) {
              ele.id = ele.storeId;
              ele.label = ele.storeName;
              ele.value = ele.storeId;
            });
            this.threeLevelOptions = resData.result;
            return;
          }

          this.$message.error({
            duration: 1000,
            message: resData.message
          });
        })
        .catch(function(error) {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    // 判断添加重复字段
    isRepeat(arr) {
      let hash = {};
      for (let i in arr) {
        if (hash[arr[i]]) {
          return true;
        }
        hash[arr[i]] = true;
      }
      return false;
    },

    // dynamicChange
    dynamicChange(e) {
      this.dynamicRow.selectKey = e;
    },
    dynamicBlur(e) {
      this.dynamicRow.inputValue = e.target.value;
    },

    // 添加参数
    addDynamic() {
      if (!this.dynamicRow.key || !String(this.dynamicRow.value).trim()) {
        this.$message.error({
          duration: 1000,
          message: '请完善参数'
        });
        return;
      }
      this.dynamicList.push(JSON.parse(JSON.stringify(this.dynamicRow)));
      var arrKeys = this.dynamicList.map(ite => ite.key); // 返回对象中键值集合的数组
      var arrValues = this.dynamicList.map(ite => ite.value);
      if (this.isRepeat(arrKeys) || this.isRepeat(arrValues)) {
        this.dynamicList.splice(this.dynamicList.length - 1, 1);
        // arrKeys.splice(this.dynamicList.length-1,1)
        this.$message.error({
          duration: 1000,
          message: '选项不能重复'
        });
        return;
      }

      // 添加对象到数组中
      // this.dynamicList.push(this.dynamicRow)

      // 删除一下
      this.dynamicRow.value = '';
      this.dynamicRow.key = null;
    },

    //  点击编辑
    editDynamic(index, obj) {
      obj.editAble = true;
    },

    // 删除参数
    delDynamic(index) {
      this.dynamicList.splice(index, 1);
    },

    // 确认编辑
    confirmDynamic(index, obj) {
      if (!obj.selectKey || !String(obj.inputValue).trim()) {
        this.$message.error({
          duration: 1000,
          message: '请完善参数'
        });
        return;
      }

      // 判断重复字段
      var copyList = JSON.parse(JSON.stringify(this.dynamicList));
      copyList[index].key = obj.selectKey;
      copyList[index].value = obj.inputValue;
      var copyKeys = copyList.map(ite => ite.key); // 返回对象中键值集合的数组
      var copyValues = copyList.map(ite => ite.value);
      if (this.isRepeat(copyKeys) || this.isRepeat(copyValues)) {
        copyList.splice(copyList.length - 1, 1);
        // copyKeys.splice(copyList.length-1,1)
        this.$message.error({
          duration: 1000,
          message: '选项不能重复'
        });
        return;
      }

      obj.key = obj.selectKey;
      obj.value = obj.inputValue;
      // return;
      // 隐藏编辑部分
      obj.editAble = false;
    },

    // 取消编辑
    cancleDynamic(index, obj) {
      // 恢复原值
      obj.selectKey = obj.key;
      obj.inputValue = obj.value;
      // 隐藏编辑部分
      obj.editAble = false;
    },

    callbackVal(val) {
      this.callback = val;
    }
  },
  watch: {
    linkVisible(val) {
      this.mylinkToolsVisible = val; // 新增linkToolsVisible的watch，监听变更并同步到linkToolsVisible上
      console.log(this.linkData);
      // 不能再这里处理数据，linkData是原数据会被改掉
      this.rewriteData = JSON.parse(JSON.stringify(this.linkData));
      // 处理 h5 链接
      if (this.rewriteData && this.rewriteData.linksType == 5) {
        this.rewriteData.url = this.rewriteData.url.includes('https') ? this.rewriteData.url.replace(/https:\/\//, '') : this.rewriteData.url.replace(/http:\/\//, '');
      }
      if (val) this.getLinksList(0, 1);
    },
    // isWx(val) {
    //   var this = this
    //   this.isWxapp = val;
    // },
    showType(val) {
      this.linkShowType = val || 0;
    },
    projectName: function(newData, oldData) {
      this.repProjectName = newData || 'gic-web';
    },
    linksType(val) {
      if (val == 50) {
        if (this.linkData.params && this.linkData.params.room_id) {
          this.axios.get(`${this.baseUrl}/api-plug/list-wx-lives?requestProject=gic-web`).then(res => {
            if (res.data.errorCode === 0) {
              const data = res.data.result.result;
              if (data && data.length) {
                this.twoLevelVisible = true;
                this.twoLevelOptions = data.map(el => ({
                  ...el,
                  label: el.name,
                  value: el.roomid
                }));
                if (this.linkData.params.room_id) {
                  this.twoLevelValue = this.linkData.params.room_id;
                } else {
                  this.twoLevelValue = '';
                }
              } else {
                this.twoLevelOptions = [];
              }
            } else {
              this.twoLevelOptions = [];
            }
          });
        }
      }
    }
  },

  mounted() {
    // 获取 showType
    this.linkShowType = this.showType || 0;
    this.pageName = '';
  }
};
</script>

<style></style>
