<template>
  <section class="quickReply">
    <ai-top-fixed background="#F5F5F5">
      <u-tabs slot="tabs" :list="tabs" :is-scroll="false" :current="currentType" font-size="32"
              bar-width="192" height="96" @change="handleTabClick"/>
      <u-search placeholder="搜索" shape="square" bg-color="#fff" :show-action="false" search-icon-color="#ccc"
                v-model="search.title" @search="page.current=1,getList()"/>
      <ai-tabs v-model="search.category" :ops="categories" @change="getList" wrap>
        <u-icon v-if="isPersonal" label="管理" size="38" class="manage" name="iconEdit" custom-prefix="iconfont"
                color="#1365DD" slot="end"
                label-color="#1365DD" @tap="handleManageType"/>
      </ai-tabs>
    </ai-top-fixed>
    <div class="mainPanel">
      <div class="fill">
        <ai-card :card-title="e.title" v-for="(e,i) in list" :key="i" @send="handleSendMsg(e)">
          <div class="textContent" v-if="e.contentType=='text'" v-html="e.content"/>
          <div class="fileContent" v-else-if="e.contentType=='news'">
            <ai-image link/>
            <div class="info">
              <span>{{ e.accessTitle }}</span>
              <em>{{ e.accessUrl }}</em>
            </div>
          </div>
          <div class="fileContent" v-else-if="e.contentType=='miniprogram'">
            <ai-image miniapp/>
            <div class="info">
              {{ e.accessTitle }}
            </div>
          </div>
          <div class="fileContent" v-else>
            <template v-if="e.file">
              <ai-image :src="e.file.url"/>
              <div class="info">
                <span>{{ e.file.name }}</span>
                <em>{{ e.file.fileSizeStr }}</em>
              </div>
            </template>
          </div>
          <template #title>
            <u-row>
              <div class="top" v-if="e.isTop==1">置顶</div>
              <div class="fill">{{ e.title }}</div>
            </u-row>
          </template>
          <template v-if="isPersonal" #menu>
            <div class="menu" @tap="handleTop(e)">{{ e.isTop == 1 ? '取消' : '' }}置顶</div>
            <div class="menu" @tap="handleDetail(e.id)">编辑</div>
            <div class="menu" @tap="handleDel(e.id)">删除</div>
          </template>
        </ai-card>
      </div>
    </div>
    <div v-if="isPersonal" class="iconfont iconfont-iconAdd addBtn" @tap="handleDetail('')"/>
  </section>
</template>

<script>
import AiTabs from "../../components/AiTabs";
import AiCard from "../../components/AiCard";
import {mapActions, mapState} from "vuex";
import AiImage from "../../components/AiImage";
import USticky from "../../uview/components/u-sticky/u-sticky";
import AiTopFixed from "../../components/AiTopFixed";

export default {
  name: "quickReply",
  components: {AiTopFixed, USticky, AiImage, AiCard, AiTabs},
  computed: {
    ...mapState(['agentConfig']),
    tabs() {
      return [
        {name: "个人话术", value: 0},
        {name: "公共话术", value: 1},
      ]
    },
    categories() {
      let meta = [{name: "全部分类", value: ""}]
      this.originCategories.map(e => {
        if (e.type == this.currentType) {
          meta.push({name: e.name, value: e.id})
        }
      })
      return meta
    },
    isPersonal() {
      return this.currentType == 0
    }
  },
  data() {
    return {
      currentType: 0,
      page: {current: 1, size: 10, total: 0},
      list: [],
      originCategories: [],
      search: {title: null, category: ''}
    }
  },
  methods: {
    ...mapActions(['injectJWeixin', 'wxInvoke']),
    handleManageType() {
      uni.navigateTo({url: `./typeManage?type=${this.currentType}`})
    },
    handleDetail(id) {
      uni.navigateTo({url: `./replyDetail?type=${this.currentType}&id=${id}`})
    },
    handleDel(id) {
      this.$confirm("是否要删除该话术模板").then(() => {
        this.$http.post("/app/wxcp/wxspeechtechnique/delete", null, {
          params: {id}
        }).then(res => {
          if (res?.code == 0) {
            this.$u.toast("删除成功!")
            this.getList()
          }
        })
      })
    },
    getList() {
      this.$http.post("/app/wxcp/wxspeechtechnique/list", null, {
        params: {...this.page, ...this.search, type: this.currentType}
      }).then(res => {
        if (res?.data) {
          if (this.page.current > 1) {
            this.list = [...this.list, ...res.data.records]
          } else this.list = res.data.records
          this.page.total = res.data.total
        }
      })
    },
    getCategories() {
      this.$http.post("/app/wxcp/wxspeechtechniquecategory/listAll?type=-1").then(res => {
        if (res?.data) {
          this.originCategories = res.data
        }
      })
    },
    handleTabClick(i) {
      this.page.current = 1
      this.search = {}
      this.currentType = i
      this.getList()
    },
    handleSendMsg(e) {
      let params = {
        text: {
          content: e.content || ""
        },
        image: {
          mediaid: e.mediaId || "" //图片的素材id
        },
        video: {
          mediaid: e.mediaId || "" //视频的素材id
        },
        file: {
          mediaid: e.mediaId || "" //文件的素材id
        },
        news: {
          link: e.accessUrl, //H5消息页面url 必填
          title: e.accessTitle, //H5消息标题
          desc: e.accessUrl,
          imgUrl: this.$cdn + 'file.png', //H5消息封面图片URL
        },
        miniprogram: {
          appid: e.accessAppid,//小程序的appid
          title: e.accessTitle, //小程序消息的title
          imgUrl: this.$cdn + 'miniwxmp.jpg',
          page: e.accessUrl, //小程序消息打开后的路径，注意要以.html作为后缀，否则在微信端打开会提示找不到页面
        }
      }
      this.wxInvoke(['sendChatMessage', {
        msgtype: e.contentType,
        [e.contentType]: params[e.contentType]
      }, res => {
        if (res?.err_msg == 'sendChatMessage:ok') {
          // this.$u.toast("发送成功!")
        } else {
          this.$u.toast("发送失败!")
        }
      }])
    },
    handleTop(row) {
      let {isTop, id} = row
      isTop = (Number(isTop) + 1) % 2
      this.$http.post("/app/wxcp/wxspeechtechnique/setIsTop", null, {
        params: {isTop, id}
      }).then(res => {
        if (res?.code == 0) {
          this.$u.toast("设置成功!")
          this.getList()
        }
      })
    }
  },
  created() {
    this.injectJWeixin("sendChatMessage")
    this.getList()
    this.getCategories()
  },
  onReachBottom() {
    if (this.page.total > this.list.length) {
      this.page.current++
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.quickReply {
  min-height: 100%;
  background: #F5F5F5;
  display: flex;
  flex-direction: column;

  .topFixed {
    background: transparent;
  }

  ::v-deep .u-tabs {

    .u-scroll-box {
      border-bottom: 1px solid #D4D4D4;

      .u-tab-bar {
        position: absolute;
        bottom: -6px;
      }
    }
  }

  ::v-deep .u-row {
    flex-shrink: 0;
    flex-wrap: nowrap;
    align-items: center;

    .manage {
      flex-shrink: 0;
      margin-bottom: 16px;
    }

    .top {
      width: 84px;
      height: 48px;
      background: #F7F7F7;
      border-radius: 4px;
      color: #999;
      font-size: 26px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .mainPanel {
    padding: 40px 32px 110px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;

    & > * + * {
      margin-top: 32px;
    }

    .menu {
      text-align: center;
      line-height: 80px;
      width: 192px;
      height: 80px;
      font-size: 28px;
      font-weight: 400;
      color: #333333;
    }

    .AiCard {
      margin-bottom: 32px;
    }

  }

  .addBtn {
    position: fixed;
    right: 32px;
    bottom: 64px;
    color: $uni-color-primary;
    font-size: 96px;
    text-align: center;
    font-weight: lighter;
  }

  .textContent {
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .fileContent {
    display: flex;
    font-size: 32px;
    align-items: center;

    .info {
      display: flex;
      flex-direction: column;
      justify-content: center;
      flex: 1;
      min-width: 0;

      & > * {
        width: 100%;
        word-break: break-all;
      }
    }

    .AiImage {
      margin-right: 20px;
    }

    em {
      font-style: inherit;
      font-size: 26px;
      color: #9b9b9b;
    }
  }
}
</style>
