<template>
  <div class="p-20" v-loading="loading">
    <el-form label-width="100px" :model="form" size="small" :rules="rules" ref="form">
      <dm-sub-title type="line">基础信息</dm-sub-title>
      <div class="section">
        <el-form-item label="链接类型" required>
          <el-radio-group v-model="form.linkType" :disabled="isEdit">
            <el-radio :label="1">专用链接</el-radio>
            <el-radio :label="2">通用链接</el-radio>
          </el-radio-group>
          <p class="tips" v-if="form.linkType == 1">仅用于在GIC系统中创建“短信模板”时直接添加引用，便于系统根据会员手机号为该引流链接带上特定会员参数，常用于通过短信的方式来促进存量会员的私域转化。</p>
          <p class="tips" v-else>可复制此引流链接或下载链接二维码，通过不同营销活动、渠道等引导客户添加导购企微号，转化成私域流量。</p>
        </el-form-item>
        <el-form-item label="链接名称" required prop="name">
          <el-input placeholder="请输入链接名称" class="w-340" :maxlength="20" show-word-limit v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="链接描述" prop="remark">
          <el-input placeholder="请输入链接描述" type="textarea" class="w-340" :maxlength="100" :autosize="{ minRows: 4, maxRows: 6 }" show-word-limit v-model="form.remark"></el-input>
        </el-form-item>
        <el-form-item label="链接标签" required prop="memberLabelId" class="memberTag-form-item">
          <el-button plain v-if="!form.memberLabelId" @click="tagsDialogVisible = true"><i class="iconfont-components3 icon-cp-PlusOutlined addPic"></i>添加标签</el-button>
          <el-tooltip :disabled="!isEdit || form.memberLabelStatus != 0" content="已删除" placement="top" v-else>
            <el-tag closable @close="handleTagCloseTag" :type="isEdit && form.memberLabelStatus == 0 ? 'warning' : ''">{{ form.memberLabelName }}</el-tag>
          </el-tooltip>
        </el-form-item>
        <dm-memberTag-group isHb :visiable.sync="tagsDialogVisible" projectName="haobao-3" @save="saveTagPop"></dm-memberTag-group>
      </div>
      <dm-sub-title type="line">分配规则</dm-sub-title>
      <p class="tips-info">
        客户点击此引流链接，系统所分配的企微员工活码将根据下方层级配置区分优先级进行展示：<br />
        <span class="dot"></span> <span style="color:#FA8C16">优先级判断规则是“从上到下、从左到右”。</span>如：当上一层级匹配到结果后，则不会再执行下个层级的判断；同一层级内，当左边的勾选项匹配到结果，则不会再执行层级内右边的勾选项<br />
        <span class="dot"></span>按照优先级匹配到的结果的大前提是该员工“可生成活码”且“并未达到当天添加好友上限”，否则则继续进行后续优先级的判断； <br />
        <span class="dot"></span>若按照优先级所匹配到的结果已经与该客户是好友关系了，不会继续进行后续优先级的判断，直接展示该员工的活码。<br />
      </p>
      <div class="section">
        <div class="level">
          <div class="title">
            <span>层级一：服务门店</span>
            <el-switch v-model="form.storeRuleJson.fw_store.open" :active-value="1" :inactive-value="0"></el-switch>
          </div>
          <div class="content m-t-20" v-if="form.storeRuleJson.fw_store.open">
            <el-checkbox v-model="form.storeRuleJson.fw_store.zs" :true-label="1" :false-label="0" :disabled="disabledProperty(form.storeRuleJson.fw_store.zs, form.storeRuleJson.fw_store.dz, form.storeRuleJson.fw_store.dy) && form.storeRuleJson.fw_store.zs">专属导购</el-checkbox>
            <el-checkbox v-model="form.storeRuleJson.fw_store.dz" :true-label="1" :false-label="0" :disabled="disabledProperty(form.storeRuleJson.fw_store.zs, form.storeRuleJson.fw_store.dz, form.storeRuleJson.fw_store.dy) && form.storeRuleJson.fw_store.dz">店长</el-checkbox>
            <el-checkbox v-model="form.storeRuleJson.fw_store.dy" :true-label="1" :false-label="0" :disabled="disabledProperty(form.storeRuleJson.fw_store.zs, form.storeRuleJson.fw_store.dz, form.storeRuleJson.fw_store.dy) && form.storeRuleJson.fw_store.dy">其他导购</el-checkbox>
          </div>
        </div>
        <div class="level">
          <div class="title">
            <span>层级二：协管门店</span>
            <el-switch v-model="form.storeRuleJson.xg_store.open" :active-value="1" :inactive-value="0"></el-switch>
          </div>
          <p class="tips margin-num" v-if="form.storeRuleJson.xg_store.open">当客户在多个协管门店下都有协管导购时，随机取一个协管门店导购</p>
          <div class="content" v-if="form.storeRuleJson.xg_store.open">
            <el-checkbox v-model="form.storeRuleJson.xg_store.zs" :true-label="1" :false-label="0" :disabled="disabledProperty(form.storeRuleJson.xg_store.zs, form.storeRuleJson.xg_store.dz, form.storeRuleJson.xg_store.dy) && form.storeRuleJson.xg_store.zs">协管门店导购</el-checkbox>
            <el-checkbox v-model="form.storeRuleJson.xg_store.dz" :true-label="1" :false-label="0" :disabled="disabledProperty(form.storeRuleJson.xg_store.zs, form.storeRuleJson.xg_store.dz, form.storeRuleJson.xg_store.dy) && form.storeRuleJson.xg_store.dz">店长</el-checkbox>
            <el-checkbox v-model="form.storeRuleJson.xg_store.dy" :true-label="1" :false-label="0" :disabled="disabledProperty(form.storeRuleJson.xg_store.zs, form.storeRuleJson.xg_store.dz, form.storeRuleJson.xg_store.dy) && form.storeRuleJson.xg_store.dy">其他导购</el-checkbox>
          </div>
        </div>
        <div class="level">
          <div class="title">
            <span>层级三：其他门店</span>
            <el-switch v-model="form.customRuleJson.open" :active-value="1" :inactive-value="0"></el-switch>
          </div>
          <div class="level3-1" v-if="form.customRuleJson.open">
            <el-radio-group v-model="form.customRuleJson.store_type">
              <el-radio :label="1">推荐门店</el-radio>
              <el-radio :label="2">附近门店</el-radio>
            </el-radio-group>
            <p class="tips m-t-6" v-if="form.customRuleJson.store_type == 1">可配置最多20个门店作为推荐门店让客户自主选择要添加的门店好友</p>
            <p class="tips m-t-6" v-else>需客户同意授权当前定位信息，才可展示客户附近最多20家门店供客户选择，否则只能在指定门店下选择</p>
          </div>
          <div class="level3-2" v-if="form.customRuleJson.open">
            <div class="level3-2-content" v-if="form.customRuleJson.store_type == 1">
              <el-form-item label="选择门店" label-width="92px" prop="storeList">
                <selectShop @change="handleTransferChange" :data="storeData" :selected="form.storeList" />
              </el-form-item>
              <el-checkbox v-model="form.customRuleJson.store.dz" :true-label="1" :false-label="0" :disabled="disabledProperty(form.customRuleJson.store.dz, form.customRuleJson.store.dy) && form.customRuleJson.store.dz">店长</el-checkbox>
              <el-checkbox v-model="form.customRuleJson.store.dy" :true-label="1" :false-label="0" :disabled="disabledProperty(form.customRuleJson.store.dz, form.customRuleJson.store.dy) && form.customRuleJson.store.dy">导购</el-checkbox>
            </div>
            <div class="level3-2-content" v-else>
              <p class="content-tips">客户同意授权当前定位信息，可在“附近门店”中自主选择要添加的门店好友</p>
              <div class="level3-2-content-check">
                <el-checkbox v-model="form.customRuleJson.store.dz" :true-label="1" :false-label="0" :disabled="disabledProperty(form.customRuleJson.store.dz, form.customRuleJson.store.dy) && form.customRuleJson.store.dz">店长</el-checkbox>
                <el-checkbox v-model="form.customRuleJson.store.dy" :true-label="1" :false-label="0" :disabled="disabledProperty(form.customRuleJson.store.dz, form.customRuleJson.store.dy) && form.customRuleJson.store.dy">导购</el-checkbox>
              </div>
              <p class="content-tips m-b-10">客户拒绝授权当前定位信息，可在下方指定的门店范围中（最多20家）自主选择要添加的门店好友</p>
              <el-form-item label="选择门店" label-width="92px" prop="storeList">
                <selectShop @change="handleTransferChange" :data="storeData" :selected="form.storeList" />
              </el-form-item>
              <el-checkbox v-model="form.customRuleJson.store.ndz" :true-label="1" :false-label="0" :disabled="disabledProperty(form.customRuleJson.store.ndz, form.customRuleJson.store.ndy) && form.customRuleJson.store.ndz">店长</el-checkbox>
              <el-checkbox v-model="form.customRuleJson.store.ndy" :true-label="1" :false-label="0" :disabled="disabledProperty(form.customRuleJson.store.ndz, form.customRuleJson.store.ndy) && form.customRuleJson.store.ndy">导购</el-checkbox>
            </div>
          </div>
          <div class="level3-3" v-if="form.customRuleJson.open">
            <el-checkbox v-model="form.customRuleJson.city_store.open" :true-label="1" :false-label="0">除附近门店/指定门店之外，允许客户按照省市区自由筛选商户所有门店进行添加</el-checkbox>
            <div class="level3-3-content" v-if="form.customRuleJson.city_store.open">
              <el-checkbox v-model="form.customRuleJson.city_store.dz" :true-label="1" :false-label="0" :disabled="disabledProperty(form.customRuleJson.city_store.dz, form.customRuleJson.city_store.dy) && form.customRuleJson.city_store.dz">店长</el-checkbox>
              <el-checkbox v-model="form.customRuleJson.city_store.dy" :true-label="1" :false-label="0" :disabled="disabledProperty(form.customRuleJson.city_store.dz, form.customRuleJson.city_store.dy) && form.customRuleJson.city_store.dy">导购</el-checkbox>
            </div>
          </div>
        </div>
      </div>
      <dm-sub-title type="line">欢迎语设置</dm-sub-title>
      <div class="section">
        <welcomeItem :welcomeId.sync="form.welcomeId" :welcomeType.sync="welcomeType" ref="welcomeItem" welcomeName="link"></welcomeItem>
      </div>
      <dm-sub-title type="line">落地页配置</dm-sub-title>
      <div class="section flex" style="margin-bottom: 40px;">
        <el-form-item label="选择模板">
          <div class="table">
            <div class="search">
              <el-input class="w-260" placeholder="请输入标题" v-model="landingPage.pageSearchText" @keyup.native="toInput" clearable @clear="getList"></el-input>
              <el-button plain class="blueBtn" @click="addTemp">新建模板</el-button>
            </div>
            <el-table :data="landingData" height="426" :loading="landingLoading" @row-click="row => getCurrentRow(row)">
              <el-table-column width="55">
                <template slot-scope="{ row }">
                  <el-radio :label="row.pageId" v-model="form.pageId" @change.native="getCurrentRow(row)"><i></i></el-radio>
                </template>
              </el-table-column>
              <el-table-column prop="pageCode" label="模板ID" minWidth="148"></el-table-column>
              <el-table-column prop="pageName" label="模板名称" minWidth="172" show-overflow-tooltip></el-table-column>
              <el-table-column prop="pageTitle" label="页面标题" minWidth="156" show-overflow-tooltip> </el-table-column>
              <el-table-column prop="guideComment" label="引导语" show-overflow-tooltip></el-table-column>
            </el-table>
            <el-pagination class="paginationBox" background @current-change="getList" :current-page.sync="landingPage.pageNum" :page-size.sync="landingPage.pageSize" layout="prev, pager,next " :total="total"></el-pagination>
          </div>
        </el-form-item>
        <div class="preview" v-if="landingForm && Object.keys(landingForm).length">
          <p class="previewTitle">落地页预览</p>
          <previewPage :data="landingForm" />
          <p class="previewBottom">此二维码只是样式预览效果，请勿直接使用</p>
        </div>
      </div>
      <div class="footBtn">
        <el-button type="primary" @click="save" :loading="btnLoading">保存</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { guidePageList, linkAdd, linkUpdate, linkDetail, storeListApi } from '@/api/actCode';
import selectShop from '@/components/common/selectShop';
import welcomeItem from '@/views/salesleads/components/welcomesItem.vue';
import previewPage from '@/components/preview-page.vue';
import { _debounce } from '@/common/js/public';
import { scrollToError } from '@/utils/validate';
export default {
  data() {
    const validateStoreList = (rule, value, cb) => {
      if (this.form.customRuleJson.open == 1 && !this.form.storeList.length) {
        return cb(new Error('请选择门店'));
      }
      cb();
    };
    return {
      scrollToError,
      tagsDialogVisible: false,
      landingPage: {
        pageSearchText: '',
        pageNum: 1,
        pageSize: 20
      },
      welcomeType: 1,
      landingLoading: false,
      loading: false,
      landingData: [],
      total: 0,
      landingForm: {},
      isEdit: this.$route.meta.type == 'edit',
      isAdd: this.$route.meta.type == 'add',
      rules: {
        name: { required: true, message: '请输入链接名称' },
        memberLabelId: { required: true, message: '请选择链接标签' },
        storeList: { required: true, validator: validateStoreList }
      },
      storeData: [],
      form: {
        linkType: 1,
        memberLabelName: '',
        memberLabelId: '',
        // memberLabelName: '测试标签值名称重复- 温州青童时代店',
        // memberLabelId: 'edd3901afd1e418d93fdc3b50bb24784',
        storeList: [],
        name: '',
        pageId: '',
        welcomeId: '',
        remark: '',
        storeRuleJson: {
          fw_store: {
            open: 1, //是否开启 1是0否
            zs: 1, //专属导购
            dz: 0, //店长
            dy: 0 // 其他导购
          },
          xg_store: {
            open: 1,
            zs: 1,
            dz: 0,
            dy: 0
          }
        },
        customRuleJson: {
          //其他门店
          open: 1, //是否开启1是0否
          store_type: 1, // 1推荐门店 2附近门店,
          store: {
            dz: 1, //店长
            dy: 0, // 导购
            ndz: 1, // 拒绝后店长
            ndy: 0 //拒绝后导购
          },
          //省市筛选
          city_store: {
            open: 1, //是否开启1是0否
            dz: 1, //店长
            dy: 0 //导购
          }
        }
      },
      wxEnterpriseId: sessionStorage.getItem('userInfos') ? JSON.parse(sessionStorage.getItem('userInfos')).wxEnterpriseId : '',
      btnLoading: false
    };
  },
  components: {
    selectShop,
    welcomeItem,
    previewPage
  },
  mounted() {
    this.getList();
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState == 'visible') {
        this.landingPage = {
          pageSearchText: '',
          pageNum: 1,
          pageSize: 20
        };
        this.getList();
      }
    });
    if (this.isEdit) {
      this.getDetail();
    } else {
      this.getStoreList();
    }
  },

  methods: {
    toInput: _debounce(function(e, value) {
      this.getList();
    }, 500),
    getStoreList() {
      storeListApi({ pageSize: 99999 }).then(res => {
        const { result } = res.data.result;
        this.storeData = result || [];
        if (this.form.storeList && this.form.storeList.length) {
          this.storeData.map(el => {
            el.checked = this.form.storeList.some(item => item.storeId == el.storeId);
            return el;
          });
        }
      });
    },
    getDetail() {
      this.loading = true;
      linkDetail({ linkId: this.$route.params.id })
        .then(res => {
          const { result } = res.data;
          if (result) {
            const { link, page } = result;

            link.customRuleJson = JSON.parse(link.customRuleJson);
            link.storeRuleJson = JSON.parse(link.storeRuleJson);
            link.storeList = link.storeList ? link.storeList : [];
            this.form = link;
            if (!this.form.welcomeId) {
              this.welcomeType = 2;
            }
            this.landingForm = page;
            this.getStoreList();
          }
        })
        .finally(_ => {
          this.loading = false;
        });
    },
    saveTagPop(data) {
      const { tagItemId, tagItemName } = data;
      this.form.memberLabelName = tagItemName;
      this.form.memberLabelId = tagItemId;
      this.form.memberLabelStatus = 1;
      this.$refs.form.validateField('memberLabelId');
    },
    handleTableRowClick(row) {
      this.form.pageId = row.pageId;
    },
    handleTagCloseTag() {
      this.form.memberLabelName = '';
      this.form.memberLabelId = '';
    },
    handleTransferChange(val) {
      console.log(val);
      this.form.storeList = val;
      this.$refs.form.validateField('storeList');
    },

    getList() {
      this.landingLoading = true;
      guidePageList(this.landingPage)
        .then(res => {
          const { result, totalCount } = res.data.result;
          if (result) {
            this.total = totalCount;

            this.landingData = result;
          }
        })
        .finally(_ => {
          this.landingLoading = false;
        });
    },
    getCurrentRow(row) {
      console.log(row);
      this.landingForm = row;
      this.form.pageId = row.pageId;
    },
    addTemp() {
      window.open('/haoban-3/#/ladingPageAdd');
    },
    disabledProperty(a, b, c, d) {
      const args = [...arguments];
      return args.filter(i => i == 1).length <= 1;
    },
    save() {
      if (!this.$refs.welcomeItem.submit()) {
        return;
      }
      if (!this.form.pageId) {
        this.$message.error('请选择落地页模板');
        return;
      }
      if (!this.form.storeRuleJson.fw_store.open && !this.form.storeRuleJson.xg_store.open && !this.form.customRuleJson.open) {
        this.$message.error('请设置分配规则');
        return;
      }
      if (this.isEdit && this.form.memberLabelStatus == 0) {
        this.$confirm('关联的标签在GIC中已被删除，无法统计和查看添加好友客户数据，为确保后续客户数据统计，请重新关联标签', '关联的标签已被删除，请重新关联标签', {
          confirmButtonText: '选择标签',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(res => {
          this.form.memberLabelId = '';
          this.form.memberLabelName = '';
          this.$refs.form.validateField('memberLabelId');
          this.$nextTick(_ => {
            const isError = document.getElementsByClassName('memberTag-form-item');
            isError[0].scrollIntoView({
              block: 'center',
              behavior: 'smooth'
            });
          });
        });
        return;
      }
      const data = JSON.parse(JSON.stringify(this.form));
      if (data.storeRuleJson.fw_store.open == 0) {
        data.storeRuleJson.fw_store = {
          open: 0, //是否开启 1是0否
          zs: 1, //专属导购
          dz: 0, //店长
          dy: 0 // 其他导购
        };
      }
      if (data.storeRuleJson.xg_store.open == 0) {
        data.storeRuleJson.xg_store = {
          open: 0,
          zs: 1,
          dz: 0,
          dy: 0
        };
      }
      if (data.customRuleJson.open == 0) {
        data.customRuleJson = {
          open: 0, //是否开启1是0否
          store_type: 1, // 1推荐门店 2附近门店,
          store: {
            dz: 1, //店长
            dy: 0, // 导购
            ndz: 1, // 拒绝后店长
            ndy: 0 //拒绝后导购
          },
          //省市筛选
          city_store: {
            open: 1, //是否开启1是0否
            dz: 1, //店长
            dy: 0 //导购
          }
        };
        data.storeList = [];
      }
      if (data.customRuleJson.city_store.open == 0) {
        data.customRuleJson.city_store = {
          open: 0, //是否开启1是0否
          dz: 1, //店长
          dy: 0 //导购
        };
      }
      data.storeRuleJson = JSON.stringify(data.storeRuleJson);
      data.customRuleJson = JSON.stringify(data.customRuleJson);
      data.wxEnterpriseId = this.wxEnterpriseId;
      if (this.welcomeType == 2) {
        data.welcomeId = '';
      }
      delete data.memberLabelStatus;
      this.$refs.form.validate(val => {
        if (!val) {
          this.scrollToError(this);
          return;
        }
        this.btnLoading = true;
        if (this.isAdd) {
          linkAdd(data)
            .then(res => {
              setTimeout(() => {
                this.btnLoading = false;
                this.$route.meta.refresh = true;
                this.$router.go(-1);
              }, 1000);
            })
            .catch(_ => {
              this.btnLoading = false;
            });
        } else {
          linkUpdate(data)
            .then(res => {
              setTimeout(() => {
                this.btnLoading = false;
                this.$router.go(-1);
              }, 1000);
            })
            .catch(_ => {
              this.btnLoading = false;
            });
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.section {
  padding: 20px 0 40px 0;
  .level {
    width: 100%;

    background: #f7f8fa;
    border-radius: 2px;
    padding: 16px 12px;
    box-sizing: border-box;
    .margin-num {
      margin: 10px 0 16px 56px;
    }
    .title {
      display: flex;
      justify-content: space-between;
      width: 240px;

      span {
        line-height: 20px;
        color: #303133;
        font-weight: 500;
        font-size: 14px;
      }
    }
    .content {
      margin-left: 56px;
    }
  }
  .level3-1 {
    margin: 16px 0 16px 56px;
  }
  .level3-2 {
    width: calc(100% - 56px);
    margin-left: 56px;
    border-bottom: 1px dashed #dcdfe6;
    padding-bottom: 16px;
    .level3-2-content {
      margin-left: 20px;
      .content-tips {
        font-size: 12px;
        color: #606266;
        line-height: 17px;
      }
      .level3-2-content-check {
        margin: 10px 0 20px 0;
      }
    }
  }
  .level3-3 {
    padding: 16px 0 0 56px;
    .level3-3-content {
      margin: 16px 0 0 20px;
    }
  }
  .level + .level {
    margin-top: 12px;
  }
}
.flex {
  display: flex;
  justify-content: flex-start;
}
.tips-info {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  line-height: 22px;
  .dot {
    width: 5px;
    height: 5px;
    background: #999999;
    border-radius: 2.5px;
    margin-right: 8px;
    display: inline-block;
  }
}
.table {
  width: 720px;
  height: 560px;
  border: 1px solid #dcdfe6;
  padding: 12px;
  position: relative;
  box-sizing: border-box;
  .search {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
  }
  .paginationBox {
    float: right;
  }
}
.preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-left: 40px;
  /deep/ .pageTitle {
    position: absolute !important;
    top: 44px !important;
  }
  .previewTitle {
    font-weight: 500;
    color: #303133;
    line-height: 20px;
    font-size: 14px;
    width: 70px;
    text-align: center;
    margin-bottom: 20px;
  }
  .previewBottom {
    font-size: 12px;
    text-align: center;
    width: 228px;
    color: #909399;
    line-height: 17px;
  }
}
.footBtn {
  width: 100%;
  height: 56px;
  background: #ffffff;
  box-shadow: 1px -2px 8px 0px rgba(220, 223, 230, 0.6);
  position: fixed;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}
.el-pagination {
  padding: 0 !important;
}
</style>
