<template>
  <div class="appStore">
    <div class="topC">
      <img
        style="width: 24px;height: 24px;object-fit: contain;"
        src="../../assets/images/appStoreCopy/topR.svg"
        @click.stop="openCe"
        alt=""
      />
      <img
        @click="searchPage"
        style="width: 24px;height: 24px;object-fit: contain;"
        src="../../assets/images/appStoreCopy/topl.svg"
        alt=""
      />
    </div>

    <div id="appStoreCon" class="bodyCon">
      <van-popup
        round
        v-model="CeShow"
        :overlay="false"
        get-container="#appStoreCon"
        position="left"
        :overlay-style="{ opacity: 0 }"
        :style="{ height: '92vh', transform: 'translate3d(0,0%, 0)', width: '45%', minWidth: '150px', opacity: 0.95 }"
      >
        <div class="popupCon">
          <div class="popTop">
            <div style="color: #0663FE;" v-if="userinfo.orgName">【{{ userinfo.orgName }}】</div>
            <!-- <div>CocoFlow</div> -->
            <div @click="comShow = true">使用电脑端</div>
            <!-- <div>关注公众号</div> -->
          </div>
          <div class="popupBot" @click="goInfo">
            <img
              style="width: 40px;height: 100%;object-fit: contain;color: #000;"
              src="../../assets/images/appStoreCopy/toux.png"
              alt=""
            />
            <div style="flex: 1;display: flex;flex-direction: column;gap: 5px;">
              <div style="font-size: 16px;font-weight: 600;">{{ userinfo.name }}</div>
              <!-- <div style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">{{ userSuffix() }}</div> -->
            </div>
          </div>
        </div>
      </van-popup>

      <van-tabs
        @change="getData"
        @touchmove.stop="handleTouchMove"
        background="#F9F8F8"
        :line-height="0"
        title-active-color="#0663FE"
        v-model="tabType"
        style="position: relative"
      >
        <img
          @click="openSel"
          style="position: absolute;right: 10px;top: 15px;"
          src="../../assets/images/appStoreCopy/arrowup.svg"
          alt=""
        />
        <div v-if="selXia" class="xiaH">
          <div class="xiaHCon" @click="CutTab(i.id)" v-for="(i, index) in typeList" :key="index">
            {{ i.name }}
          </div>
        </div>
        <van-tab v-for="(i, index) in typeList" class="appBlocks" :key="index" :name="i.id" :title="i.name">
          <template v-if="dataList.length">
            <div v-for="(i, ind) in dataList" @click="openUrl(i.url)" :key="ind + 'a'" class="appBlock">
              <div class="appBlockTop">
                <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;">
                  <img class="appBlockTopImg" :src="i.json.icon" alt="" />
                  <!-- <img style="width: 16px;" src="../../assets/images/appStoreCopy/appde.svg" alt="" /> -->
                </div>
                <div class="appBlockTopTit">{{ i.name }}</div>
                <div style="display: flex;align-items: center;">
                  <div style="display: flex;gap: 5px;">
                    <span class="ATag">{{ i.label == 'workflow' ? '工作流' : '智能体' }}</span>
                    <span class="ATag" v-if="i.tag">
                      <img
                        style="width: 30%;"
                        :src="
                          i.tag == 1 || !i.tag
                            ? require('../../assets/images/appStoreCopy/dul.svg')
                            : require('../../assets/images/appStoreCopy/hz.svg')
                        "
                        alt=""
                      />
                      {{ i.tag == '1' || !i.tag ? '官方' : '精选' }}
                    </span>
                    <span
                      class="ATag"
                      v-if="['agent'].includes(i.label) || (['workflow'].includes(i.label) && i.json.modes)"
                    >
                      <template v-if="i.label === 'agent'">聊天式</template>
                      <template v-else-if="i.json.modes">{{ wayList[i.json.modes[0]] }}</template>
                    </span>
                  </div>
                </div>
              </div>
              <div class="appBlockBot">
                <span>{{ i.username }}</span>
                <div class="appBlockBotCol">
                  <div style="display: flex;align-items: center;">
                    <img
                      @click.stop="delAllOP(i.id, 0)"
                      v-if="collList.some(item => item.id === i.id)"
                      src="../../assets/images/appStoreCopy/star1.svg"
                      alt=""
                    />
                    <img @click.stop="addAllOP(i, 0)" v-else src="../../assets/images/appStoreCopy/star.svg" alt="" />
                    {{ i.collectCount }}
                  </div>
                  <div style="display: flex;align-items: center;">
                    <img
                      @click.stop="delAllOP(i.id, 2)"
                      v-if="likeList.some(item => item.id === i.id)"
                      src="../../assets/images/appStoreCopy/xin1.svg"
                      alt=""
                    />
                    <img @click.stop="addAllOP(i, 2)" v-else src="../../assets/images/appStoreCopy/xin.svg" alt="" />
                    {{ i.likeCount }}
                  </div>
                </div>
              </div>
            </div>
          </template>
          <div v-else style="position: absolute;left: 50%;top: 30%;transform: translate(-50%,-50%);">
            暂无数据哦~
          </div>
          <!-- <div v-if="isShow"
              class="zzcl"
            >
                加载中...
            </div> -->
        </van-tab>
      </van-tabs>
      <div></div>
    </div>

    <!-- 侧边栏遮罩层 -->
    <div
      v-if="ZeShow"
      @click="openCeY"
      style="position: fixed;top: 0;left: 0;width: 100%;height: 100%;background-color: #000;opacity: 0"
    ></div>

    <van-popup overlay-class="comCss" v-model="comShow" round :closeable="true" position="bottom" class="Vpop">
      <div class="comCssTit">
        电脑端开启更多高效体验
      </div>
      <img style="width: 170px;" src="../../assets/images/appStoreCopy/comp.svg" alt="" />
      <div class="cpmUrl" @click="copyUrl">
        <div>
          https://cloud.cocorobo.cn/
        </div>
        <img style="margin-left: 5px;height: 16.8px;" src="../../assets/images/appStoreCopy/copyIco.svg" alt="" />
      </div>
      <div class="comBot">
        复制网址，去电脑端浏览器访问吧
      </div>
    </van-popup>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getStoreType,
  getStoreCopy,
  insert_appStoreSave,
  select_appStoreSave,
  delete_appStoreSave,
  select_appStorJuri
} from '@/api/appStore'
import appStorePopup from './components/appStorePopup.vue'
import { Dialog, Toast } from 'vant'
const clickOutside = {
  bind(el, binding) {
    // 在元素上绑定一个点击事件监听器
    el.clickOutsideEvent = function(event) {
      console.log('event', event)
      console.log('村上春树')

      // 检查点击事件是否发生在元素的内部
      if (!(el === event.target || el.contains(event.target))) {
        // 如果点击事件发生在元素的外部，则触发指令绑定的方法,将点击的event数据传过去
        binding.value(event)
      }
    }
    // 在文档上添加点击事件监听器
    document.addEventListener('tap', el.clickOutsideEvent)
  },
  unbind(el) {
    // 在元素上解除点击事件监听器
    document.removeEventListener('tap', el.clickOutsideEvent)
  }
}

export default {
  name: 'AppStore',
  components: {
    appStorePopup
  },
  directives: {
    'click-outside': clickOutside // 注册自定义指令
  },
  data() {
    return {
      tabType: 0,
      CeShow: false,
      isShow: false, // loading
      comShow: false, // 电脑端链接
      dataList: [], // 应用列表
      typeList: [], // tab栏
      // showType: '',
      searchText: '', // 查询框文字
      selectJuri: 3,
      collList: [], // 用户收藏
      likeList: [], // 用户喜欢
      tabPage: '',
      ZeShow: false,
      selXia: false,
      // selectList: [
      //   { index: 1, label: '我的' },
      //   { index: 2, label: '组织' },
      //   { index: 3, label: '所有人' }
      // ],
      wayList: ['聊天室', '卡片式', '沉浸式'],
      // 权限标签
      juriListData: [],
      tagList: [],
      showCardId: null
    }
  },
  computed: {
    ...mapGetters(['userinfo']),
    showMenu() {
      return data => {
        let _result = false
        if (data && this.userinfo.userid) {
          if (data.userid === this.userinfo.userid || (data.json && data.json.copy === '1')) {
            _result = true
          }
        }

        return _result
      }
    },
    userSuffix() {
      let yym = ''
      return function() {
        // this.userinfo.role == 1 && this.userinfo.rrole == 1 && this.userinfo.type == 1 &&
        yym = this.userinfo

        const val = yym.accountNumber

        let userName = JSON.parse(JSON.stringify(val))

        const regEmail = new RegExp('^[A-Za-z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$')

        // // 判断用户输入账户带不带后缀
        if (!regEmail.test(userName)) {
          console.log('111')
        } else {
          const parts = userName.split('@')
          userName = parts[0]
        }

        return userName
      }
    }
  },
  methods: {
    async copyUrl() {
      const url = 'https://cloud.cocorobo.cn/'
      try {
        await navigator.clipboard.writeText(url)
        Toast({
          message: '链接已复制！',
          position: 'top'
        })
      } catch (err) {
        console.error('复制失败:', err)
        Toast({
          message: '复制失败，请手动复制',
          position: 'top'
        })
      }
    },
    // 跳转个人信息页
    goInfo() {
      this.$router.push('/userInfoPage')
    },
    // 跳转查询页面
    searchPage() {
      this.$router.push('/searchL')
    },
    // 阻止触摸移动事件的默认行为
    handleTouchMove(event) {
      event.preventDefault()
    },
    // 打开与关闭侧边栏
    openCe() {
      this.CeShow = !this.CeShow
      this.ZeShow = !this.ZeShow
    },
    // 点击遮罩层关闭侧边栏
    openCeY() {
      this.ZeShow = false
      this.CeShow = false
      this.selXia = false
    },

    // 查询应用数据
    getData(val = '') {
      this.getAllOP(0)
      this.getAllOP(2)

      let selectJuri = 4
      if (val == 'k11') {
        selectJuri = 1
      }
      this.tabPage = val
      this.isShow = true
      const params = {
        uid: this.userinfo.userid,
        name: this.searchText,
        label: '',
        type: val == 'k11' ? '' : val,
        juri: selectJuri,
        stand: this.userinfo.schoolArea,
        status: '',
        model: '',
        exportType: ''
      }

      getStoreCopy(params)
        .then(res => {
          const _data = res[0]
          if (_data.length > 0) {
            _data.forEach(i => {
              if (i.json) {
                i.json = JSON.parse(i.json)
              }
            })

            this.dataList = _data
          } else {
            this.dataList = []
          }
          this.getAppStoreJuri()

          this.isShow = false
        })
        .catch(err => {
          this.isShow = false
          this.$toast.error('获取应用数据失败')
        })
    },
    // 添加收藏0 喜欢2
    addAllOP(val, typeL) {
      console.log(val, typeL)

      const params = [
        {
          uid: this.userinfo.userid,
          type: typeL,
          aid: val.id,
          json: ''
        }
      ]
      insert_appStoreSave(params)
        .then(res => {
          // console.log(res);
          // this.getData(this.tabPage)
          if (typeL == 0) {
            this.dataList.forEach(e => {
              if (e.id == val.id) {
                e.collectCount = e.collectCount + 1
              }
            })
          } else {
            this.dataList.forEach(e => {
              if (e.id == val.id) {
                e.likeCount = e.likeCount + 1
              }
            })
          }
          this.getAllOP(typeL)
        })
        .catch(err => {
          console.log(err)
          this.$message.error('添加失败')
        })
    },
    // 删除收藏0 喜欢2
    delAllOP(val, type) {
      console.log(val, type)

      let kD = ''
      if (type == 0) {
        kD = this.collList.find(e => val === e.id)
      } else {
        kD = this.likeList.find(e => val === e.id)
      }

      const params = [
        {
          sid: kD.sid
        }
      ]

      delete_appStoreSave(params)
        .then(res => {
          console.log(res)
          // this.getData(this.tabPage)

          if (type == 0) {
            this.dataList.forEach(e => {
              if (e.id == val) {
                e.collectCount = e.collectCount - 1
              }
            })
          } else {
            this.dataList.forEach(e => {
              if (e.id == val) {
                e.likeCount = e.likeCount - 1
              }
            })
          }
          this.getAllOP(type)
        })
        .catch(err => {
          console.log(err)
          this.$message.error('操作失败')
        })
    },
    // 获取2点赞 与0收藏
    getAllOP(val) {
      const params = {
        uid: this.userinfo.userid,
        type: val,
        limit: 0
      }
      select_appStoreSave(params)
        .then(res => {
          if (val == 0) {
            this.collList = res[0]
          } else {
            this.likeList = res[0]
          }
        })
        .catch(err => {
          console.log(err)
          this.$toast.error('获取用户点赞应用失败')
        })
    },
    getAllStoreType() {
      const params = {
        suserid: this.userinfo.userid,
        sorg: this.userinfo.org,
        soid: this.userinfo.organizeid,
        sstand: this.userinfo.schoolArea,
        exportType: ''
      }

      getStoreType(params)
        .then(res => {
          const _data = res[0]
          if (_data.length > 0) {
            this.typeList = _data
            this.typeList.unshift({ id: 'k11', name: '我的' })
            this.typeList.unshift({ id: '', name: '全部' })
          } else {
            this.typeList = []
          }
        })
        .catch(err => {
          console.log(err)
          this.$toast.error('获取应用类型失败')
        })
    },
    openUrl(url) {
      window.open(url, '_blank')
    },
    setDataTag(_list) {
      const _result = _list
      _result.forEach(item => {
        if (this.juriListData.find(i => i.jid === item[i.type] && i.utype === '1') && item.juri == '3') {
          item.tag = '1' // 官方
        } else if (this.juriListData.find(i => i.jid === item[i.type] && i.utype === '2') && item.juri == '3') {
          item.tag = '2' // 精选
        } else if (item.role === 1 && item.juri == '2') {
          item.tag = '3' // 专属
        } else if (item.juri === '2') {
          item.tag = '4' // 组织
        } else if (item.userid === this.userinfo.userid && item.juri === '1') {
          item.tag = '5' // 个人
        }
      })

      return _result
    },
    openSel() {
      this.selXia = true
      this.ZeShow = true
    },
    CutTab(val) {
      this.tabType = val
      this.selXia = false
      this.ZeShow = false
      this.getData(val)
    },

    // 获取显示标权限
    getAppStoreJuri() {
      select_appStorJuri({})
        .then(res => {
          this.juriListData = res[0]
          if (this.dataList.length > 0) {
            this.dataList = JSON.parse(JSON.stringify(this.setDataTag(this.dataList)))
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  },
  mounted() {
    this.getData()
    this.getAllStoreType()
  }
}
</script>

<style lang="scss" scoped>
.appStore {
  width: 100vw;
  height: 100vh;
  box-sizing: border-box;
  // padding: 5px;
  background-color: #f9f8f8;
  display: flex;
  flex-direction: column;
  overflow: auto;
}
.topC {
  display: flex;
  justify-content: space-between;
  width: 100%;
  align-items: center;
  height: 50px;
  padding: 0px 12px;
  box-sizing: border-box;
  flex-shrink: 0;
}
.bodyCon {
  height: 100%;
  background: #f9f8f8;
}
:deep .van-popup--left {
  top: auto !important;
}
.popupCon {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 20px 12px 30px;
  height: 100%;
  box-sizing: border-box;
  .popTop {
    color: #000;
    display: flex;
    flex-direction: column;
    font-size: 12px;
    gap: 15px;
    font-family: PingFang SC;
    font-weight: 600;
  }

  .popupBot {
    display: flex;
    align-items: center;
    gap: 10px;
    background: #f3f3f3;
    border-radius: 8px;
    padding: 5px 8px;
  }
}
.appBlocks {
  position: relative;

  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(40%, 1fr)); /* 自适应列 */
  align-items: start;
  padding: 10px;
  box-sizing: border-box;
  background: #f9f8f8;
  overflow: auto;
  gap: 10px;
  .appBlock {
    //  align-self: center;
    // width: calc(50% - 10px);
    width: 100%;
    // height: 100%;
    background: #f8f8f8;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    box-shadow: 0px 4px 10px 0px #00000033;
    .appBlockTop {
      border-radius: 10px;
      padding: 10px;
      background: #fff;
      box-sizing: border-box;
      .appBlockTopImg {
        width: 30px;
        height: 30px;
        object-fit: contain;
        border-radius: 50%;
        padding: 3px;
        box-sizing: border-box;
        border: 0.5px #d9d9d9 solid;
        // margin-bottom: 10px;
      }
      .appBlockTopTit {
        font-family: PingFang SC;
        font-weight: 600;
        font-size: 14px;
        line-height: 15px;
        margin-bottom: 10px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .ATag {
        font-family: PingFang SC;
        font-weight: 400;

        justify-content: center;
        font-size: 10px;
        line-height: 16px;
        background: #f3f3f3;
        padding: 2px;
        border-radius: 2px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        flex-shrink: 0;
        img {
          margin-right: 2px;
        }
      }
    }
    .appBlockBot {
      background: #f8f8f8;
      display: flex;
      padding: 10px;
      align-items: center;
      border-radius: 0 0 10px 10px;
      justify-content: space-between;
      font-size: 14px !important;
      box-sizing: border-box;
      color: rgba(40, 47, 60, 0.8) !important;
      .appBlockBotCol {
        display: flex;
        align-items: center;
        gap: 8px;
        img {
          width: 20px;
        }
      }
    }
  }
}
// /deep/ .van-tab {
//   width: 100px;
//   text-align: center;
// }

// /deep/ .van-tabs__line {
//   width: 90px;
//   height: 2px;
//   flex-shrink: 0;
//   background: #4a8efc;
// }

/deep/ .van-tab__pane {
  max-height: calc(92vh - 44px);
  overflow-y: auto;
  overflow-x: hidden;
  width: 100%;
}
/deep/ .comCss {
  background: rgba(158, 152, 152, 0.4);
  backdrop-filter: blur(3px);
}
/deep/ .van-tabs__wrap {
  padding-right: 30px !important;
}
.Vpop {
  padding: 20px 30px;
  box-sizing: border-box;
  height: 350px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.comCssTit {
  font-family: PingFang HK;
  font-weight: 600;
  font-size: 20px;
  line-height: 20px;
  color: #0663fe;
  margin-bottom: 20px;
}
.cpmUrl {
  background: #3681fc;
  border-radius: 12px;
  padding: 10px 20px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-family: PingFang HK;
  font-weight: 600;
  font-size: 12px;
  margin: 10px 0 20px;
}
.comBot {
  font-family: PingFang HK;
  font-weight: 400;
  font-size: 14px;
  line-height: 20px;
  color: #000;
}
.zzcl {
  position: absolute;
  left: 0%;
  top: 0%;
  background: #fff;
  width: 100%;
  height: 100%;
  opacity: 0.6;
  display: flex;
  justify-content: center;
  line-height: 350px;
  font-size: 16px;
  color: #000;
}
.xiaH {
  position: absolute;
  left: 0;
  top: 44px;
  z-index: 999;
  width: 100%;
  background-color: rgb(232, 232, 233);
  border-radius: 0 0 15px 15px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  padding: 15px;
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  min-height: 100px;
  .xiaHCon {
    // flex-shrink: 0;
    width: auto;
    height: 30px;
    background: #fff;
    display: flex;
    align-items: center;
    border-radius: 5px;
    padding: 0 10px;
  }
}
</style>
