<template>
  <div>
    <div class="daily-set-wrap">
      <div class="daily-set-content border-box">
        <div class="admin-tip-body">
          <div role="alert" class="el-alert el-alert--info" style="width: 860px;" v-if="type == 1">
            <i class="el-alert__icon el-icon-info"></i>
            <div class="el-alert__content">
              <p class="el-alert__title">
                1、若使用此处的好办欢迎语，请关闭企微欢迎语或其他自建应用/第三方应用的欢迎语配置，否则会产生冲突，好办欢迎语不生效。<br />
                2、在使用此处好办欢迎语的情况下，只有关联了好办导购账号的企微员工在添加好友后才能触发欢迎语。 <br />
                3、可按照企微不同的组织架构来分别配置不同的欢迎语。（若某企微员工在多个企微部门，或者某企微部门配置了多条欢迎语，则仅发送“更新时间”最新的那条欢迎语） <br />
                4、创建欢迎语时，可在欢迎语内容中配置“带参会员小程序/带参公众号二维码”，以便于在“不同开平”的情况下，保证“客户”身份与“好友”身份的对应，<a href="https://www.yuque.com/exnmlu/oo64hg/bsabp2" target="_blank" style="color:#2f54eb;">详见>>></a>
              </p>
            </div>
          </div>
          <div role="alert" class="el-alert el-alert--info" style="width: 860px;" v-else>
            <i class="el-alert__icon el-icon-info"></i>
            <div class="el-alert__content">
              <p class="el-alert__title">
                作为一个“欢迎语库”，下方所创建的欢迎语将可被不同模块进行引用，如【活码管理】中的活码欢迎语、链接欢迎语。
              </p>
            </div>
          </div>
        </div>
        <div class="flex flex-space-between m-b-20 m-t-20">
          <el-input placeholder="请输入标题" maxlength="50" v-model="form.title" class="w-264" style="width: 264px;" @keyup.native="value => toInput(value, searchInput)" clearable @clear="clearSearch"> <i slot="prefix" class="el-input__icon el-icon-search"></i> </el-input>
          <el-button v-if="$getButtonLimit($buttonCode.addSalutatory)" :limit-code="$buttonCode.addSalutatory" type="primary" @click="addSalutatory">新建欢迎语</el-button>
        </div>
        <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" :style="{ width: '100%' }" v-loading="loading">
          <el-table-column prop="title" label="标题" width="200" fixed="left">
            <div ref="title" slot-scope="{ row }">
              <!-- 算出文本的长度，再设置 -->
              <el-tooltip placement="top" :content="row.title" v-if="row.isOverflow">
                <span class="title-text">{{ row.title }}</span>
              </el-tooltip>
              <span v-else>{{ row.title }}</span>
              <el-tag size="mini" v-if="row.defaultWelcomeFlag == 1">默认欢迎语</el-tag>
            </div>
          </el-table-column>
          <el-table-column prop="welcomeContent" label="内容" show-overflow-tooltip min-width="200">
            <template slot-scope="{ row }">{{ row.welcomeContent }}</template>
          </el-table-column>
          <el-table-column label="附件" width="200">
            <template slot-scope="{ row }">
              <el-popover placement="top-start" trigger="hover" v-if="row.welcomeMediaList && row.welcomeMediaList.length">
                <div class="flexBox" v-for="item in row.welcomeMediaList" :key="item.welcomeMediaId">
                  <svg-icon :iconname="iconType[item.mediaType]" size="16" style="margin-right: 13px;"> </svg-icon>
                  <span class="popverText">{{ item.mediaTitle }}</span>
                </div>
                <div slot="reference" class="flexBox" v-if="row.welcomeMediaList && row.welcomeMediaList.length">
                  <svg-icon :iconname="iconType[row.welcomeMediaList[0].mediaType]" size="40" style="margin-right: 10px;"> </svg-icon>
                  <span class="wrapText"> {{ row.welcomeMediaList[0].mediaTitle }}</span>
                </div>
              </el-popover>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" width="180" show-overflow-tooltip>
            <template slot-scope="{ row }">{{ row.updateTime | formatTimeStamp }}</template>
          </el-table-column>
          <el-table-column prop="creatorName" label="创建人" width="120" show-overflow-tooltip> </el-table-column>
          <el-table-column prop="modifierName" label="操作人" width="120" show-overflow-tooltip> </el-table-column>
          <el-table-column prop="suitDepartmentName" label="适用范围" width="300" v-if="type == 1">
            <template slot-scope="{ row }">
              <div v-if="row.defaultWelcomeFlag">
                <div>全体成员</div>
              </div>
              <div v-else>
                <div class="wrapText" v-if="row.suitDepartmentName.join('，').length > 40">
                  {{ row.suitDepartmentName.join('，').slice(0, 40) + '...' }}
                </div>
                <div class="wrapText" v-else>
                  {{ row.suitDepartmentName.join('，') }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" :width="type == 2 ? 220 : 180" fixed="right" v-if="$getButtonLimit($buttonCode.editSalutatory) || $getButtonLimit($buttonCode.delSalutatory)">
            <template slot-scope="{ row }">
              <el-button type="text" @click="showRelateDetail(row)" v-show="row.type == 2">关联详情</el-button>
              <el-button v-if="$getButtonLimit($buttonCode.editSalutatory)" :limit-code="$buttonCode.editSalutatory" type="text" @click="changeRoute(row)">编辑</el-button>
              <el-button v-if="$getButtonLimit($buttonCode.delSalutatory)" :limit-code="$buttonCode.delSalutatory" type="text" @click="remove(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <relation-dialog :dialogVisible.sync="dialogVisible" :id="welcomeId" @goLinkDetail="goLinkDetail" />
        <div class="block common-wrap__page text-right m-t-24" v-if="tableData.length != 0">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.pageNum" :page-sizes="[20, 40, 60, 80]" :page-size="form.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { postJsonRequest, getRequest } from '@/api/api';
import { _debounce } from '@/common/js/public';
import relationDialog from './relationDialog';
export default {
  data() {
    return {
      form: {
        title: '',
        pageSize: 20,
        pageNum: 1
      },
      dialogVisible: false,
      welcomeId: '',
      total: 0,
      wxEnterpriseId: sessionStorage.getItem('userInfos') ? JSON.parse(sessionStorage.getItem('userInfos')).wxEnterpriseId : '',
      friendSettingId: '',
      btnLoading: false,
      iconType: {
        1: 'iconwenjianleixingtupian',
        2: 'iconwenjianleixingshipin',
        3: 'iconwenjianleixing-wenjian',
        4: 'iconwenjianleixing-lianjie',
        5: 'iconwenjianleixing-xiaochengxu', // 小程序
        6: 'iconwenjianleixing-xiaochengxu', // 带参小程序
        7: 'icongongzhonghao1' // 带参公众号
      },
      tableData: [],
      loading: false
    };
  },
  mounted() {
    const that = this;
    that.getData();
    // this.getSetting();
  },
  props: {
    type: {
      type: [Number, String],
      default: 1
    }
  },
  components: {
    relationDialog
  },
  watch: {
    type(val) {
      this.form = {
        title: '',
        pageSize: 20,
        pageNum: 1
      };
      this.getData();
    }
  },
  methods: {
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      this.getData();
    }, 500),
    /**
     * 搜索标签清空
     */
    clearSearch() {
      this.getData();
    },
    /**
     * 跳转
     */
    changeRoute(row) {
      this.$router.push({ path: '/editSalutatorySet', query: { id: row.welcomeId, isDefalut: row.defaultWelcomeFlag, type: row.type } });
    },
    addSalutatory() {
      this.$router.push({ path: '/salutatorySet', query: { type: this.type } });
    },
    remove(row) {
      if (row.type == 2) {
        this.delType2(row);
      } else {
        this.delType1(row);
      }
    },
    delType1(row) {
      let str = '模板删除后将无法恢复';
      if (row.defaultWelcomeFlag == 1) {
        str = '此条欢迎语为全员欢迎语，删除后可能影响欢迎语发送';
      }
      this.$confirm(str, '确认要删除该欢迎语吗？', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        getRequest('/haoban-manage3-web/welcome/remove', { welcomeId: row.welcomeId }).then(res => {
          let resData = res.data;
          if (resData.code == 0 && resData.result) {
            this.$message.success('删除成功');
            this.getData();
          }
        });
      });
    },
    delType2(row) {
      getRequest('/haoban-manage3-web/welcome/statistics', { welcomeId: row.welcomeId }).then(res => {
        console.log(res);
        const { result } = res.data;
        let str = '';
        if (result) {
          if (result.qrCodeReferNum && result.linkReferNum) {
            str = `当前模板已关联状态为正常的活码（${result.qrCodeReferNum}）、链接（${result.linkReferNum}），请确认相关活码是否不再使用该欢迎语以及链接已投放结束，取消关联后才可删除该模板`;
          } else if (result.qrCodeReferNum) {
            str = `当前模板已关联状态为正常的活码（${result.qrCodeReferNum}），请确认相关活码是否不再使用该欢迎语，取消关联后才可删除该模板`;
          } else if (result.linkReferNum) {
            str = `当前模板已关联链接（${result.linkReferNum}），请确认相关链接已投放结束，取消关联后才可删除该模板`;
          }
          this.$confirm(str, '无法删除该欢迎语', {
            confirmButtonText: '关联详情',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.showRelateDetail(row);
          });
        } else {
          str = '模板删除后将无法恢复';
          this.$confirm(str, '确认要删除该欢迎语吗？', {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            getRequest('/haoban-manage3-web/welcome/remove', { welcomeId: row.welcomeId }).then(res => {
              let resData = res.data;
              if (resData.code == 0 && resData.result) {
                this.$message.success('删除成功');
                this.getData();
              }
            });
          });
        }
      });
    },
    showRelateDetail(item) {
      this.dialogVisible = true;
      this.welcomeId = item.welcomeId;
    },
    goLinkDetail(row) {
      console.log(row);
      if (row.type == 1) {
        this.$router.push('/actCodeDetail?hmId=' + row.referId);
      } else {
        this.$router.push(`/attractFlowLinkInfo/${row.referId}`);
      }
    },
    /**
     * 获取数据
     */
    getData() {
      this.loading = true;
      postJsonRequest('/haoban-manage3-web/welcome/list', { ...this.form, wxEnterpriseId: this.wxEnterpriseId, type: this.type })
        .then(res => {
          let resData = res.data;
          console.log(resData);
          if (resData.code == 0 && resData.result) {
            this.tableData = resData.result.result;
            this.tableData.forEach(item => {
              item.suitDepartmentName = [];
              if (item.suitDepartmentList && item.suitDepartmentList.length) {
                item.suitDepartmentList.forEach(ele => {
                  item.suitDepartmentName.push(ele.departmentName);
                });
              }
            });
            this.total = resData.result.totalCount;
            this.$nextTick(() => {
              const span = document.createElement('span');
              span.style.position = 'fixed';
              span.style.opacity = 0;
              span.style.visibility = 'hidden';
              const maxWidth = this.$refs.title && this.$refs.title.offsetWidth - 85;
              this.tableData.map(el => {
                span.innerHTML = el.title;
                document.body.appendChild(span);
                el.isOverflow = span.offsetWidth > maxWidth;
                return el;
              });
              document.body.removeChild(span);
            });
          }
        })
        .catch(error => {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSizeChange(val) {
      this.form.pageNum = 1;
      this.form.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.form.pageNum = val;
      this.getData();
    }
  }
};
</script>
<style type="text/scss" lang="scss" scoped>
.title-text {
  display: inline-block;
  vertical-align: middle;
  max-width: calc(100% - 85px);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.warp {
  background: #fff;
  margin-bottom: 10px;
  padding: 20px;
  font-size: 14px;
  h2 {
    margin-bottom: 12px;
    font-weight: 500;
  }
  .echoData {
    background: #f5f7fa;
    border-radius: 2px;
    line-height: 22px;
    color: #606266;
    padding: 5px 13px;
  }
}

.el-alert--info {
  align-items: flex-start;
  width: 700px;
  padding-top: 5px;
  font-size: 14px;
  color: #606266;
  background: rgba(240, 245, 255, 1);
  border-radius: 2px;
  border: 1px solid rgba(133, 165, 255, 1);
}
.el-icon-info {
  width: 12px;
  font-size: 12px;
  color: #2f54eb;
  margin-top: 5px;
}
.el-alert__content {
  padding-left: 9px;
  .el-alert__title {
    font-size: 13px;
    font-weight: 400;
    color: #303133;
    line-height: 22px;
  }
}
.daily-set-wrap {
  height: 100%;
  background-color: #fff;
  .daily-set-content {
    padding: 0 20px 20px 20px;
    .table-condition-left {
      font-size: 0;
    }
  }
}
.el-radio {
  margin-right: 0;
}
.el-radio + .el-radio {
  margin-left: 0;
}
.wrapText {
  width: 90%;
  text-align: left;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.flexBox {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .popverText {
    font-size: 12px;
    width: 90%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.flexBox + .flexBox {
  margin-top: 10px;
}
.popoverBox {
  max-height: 300px;
  overflow-y: auto;
  max-width: 500px;
  line-height: 28px;
}
</style>
