<template>
  <div class="appStore">
    <div class="as_header">
      <div class="as_h_top">
        <span>应用管理</span>
        <!-- <el-button class="addBtn" type="primary" size="mini" @click="addAppFn">添加应用</el-button> -->
      </div>
      <div class="as_h_bottom">
        <el-input v-model="searchText" style="width:40%;" placeholder="请输入应用名称" size="small"></el-input>
        <el-select v-model="selectJuri" placeholder="请选择权限" size="small" style="width:39%;margin-left:10px;font-size: 16px;" @change="getData()">
          <el-option v-for="item in selectList" :key="item.index" :label="item.label" :value="item.index"></el-option>
        </el-select>
        <el-button
          type="primary"
          size="mini"
          @click="getData()"
          icon="el-icon-search"
          style="margin-left: 10px;"
        ></el-button>
      </div>
      <div class="as_h_typeList">
				<span :class="{'typeActive':showType==''}" @click="changeType('')">全部</span>
				<span v-for="(item,index) in typeList" :key="item.id" :class="{'typeActive':item.id==showType}" @click="changeType(item.id)">{{item.name}}</span>

      </div>
    </div>
    <div class="as_content">
      <div class="as_c_item" v-for="(item, index) in dataList" :key="item.id" @click="closeCard()">
        <div class="as_c_i_top">
          <div class="as_c_i_t_icon">
            <svg
              t="1732605901531"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="4275"
              width="200"
              height="200"
							v-if="!item.json.icon"
            >
              <path
                d="M179.2 153.6a51.2 51.2 0 0 0-51.2 51.2v128a51.2 51.2 0 0 0 51.2 51.2h128a51.2 51.2 0 0 0 51.2-51.2V204.8a51.2 51.2 0 0 0-51.2-51.2H179.2z m0-102.4h128a153.6 153.6 0 0 1 153.6 153.6v128a153.6 153.6 0 0 1-153.6 153.6H179.2a153.6 153.6 0 0 1-153.6-153.6V204.8a153.6 153.6 0 0 1 153.6-153.6z m0 614.4a51.2 51.2 0 0 0-51.2 51.2v128a51.2 51.2 0 0 0 51.2 51.2h128a51.2 51.2 0 0 0 51.2-51.2V716.8a51.2 51.2 0 0 0-51.2-51.2H179.2z m0-102.4h128a153.6 153.6 0 0 1 153.6 153.6v128a153.6 153.6 0 0 1-153.6 153.6H179.2a153.6 153.6 0 0 1-153.6-153.6V716.8a153.6 153.6 0 0 1 153.6-153.6z m611.84-403.4048a51.2 51.2 0 0 0-72.3968 0L646.144 232.2432a51.2 51.2 0 0 0 0 72.3968l72.448 72.3968a51.2 51.2 0 0 0 72.3968 0l72.3968-72.3968a51.2 51.2 0 0 0 0-72.3968L791.04 159.744z m72.3968-72.3968l72.3968 72.3968a153.6 153.6 0 0 1 0 217.2416l-72.3968 72.3968a153.6 153.6 0 0 1-217.2416 0l-72.3968-72.3968a153.6 153.6 0 0 1 0-217.2416l72.3968-72.3968a153.6 153.6 0 0 1 217.2416 0zM699.7504 896a51.2 51.2 0 0 1 0 102.4A162.1504 162.1504 0 0 1 537.6 836.2496v-110.8992A162.1504 162.1504 0 0 1 699.7504 563.2h110.8992a162.1504 162.1504 0 0 1 162.1504 162.1504v8.448a51.2 51.2 0 0 1-102.4 0v-8.448c0-33.024-26.7264-59.7504-59.7504-59.7504h-110.8992c-33.024 0-59.7504 26.7264-59.7504 59.7504v110.8992c0 33.024 26.7264 59.7504 59.7504 59.7504z"
                fill="#2C6DD2"
                p-id="4276"
              ></path>
              <path
                d="M791.4496 160a51.2 51.2 0 0 0-72.3968 0l-72.448 72.3968a51.2 51.2 0 0 0 0 72.3968l72.448 72.3968a51.2 51.2 0 0 0 72.3968 0l72.3968-72.3968a51.2 51.2 0 0 0 0-72.3968l-72.3968-72.3968z"
                fill="#20C997"
                p-id="4277"
              ></path>
            </svg>
						<img :src="item.json.icon" alt="" v-else>
          </div>
          <div class="as_c_i_t_message">
            <div>{{ item.name }}</div>
            <span v-if="item.label==='agent'">智能体</span>
						<span v-if="item.label==='workflow'">工作流</span>
          </div>
					<div class="ac_c_i_t_popover" v-if="showMenu(item)">
						<svg t="1732786015570" @click.stop="showCard(item.id)" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9199" width="200" height="200"><path d="M192 443.733333c-38.4 0-68.266667 29.866667-68.266667 68.266667 0 38.4 29.866667 68.266667 68.266667 68.266667s68.266667-29.866667 68.266667-68.266667c0-38.4-29.866667-68.266667-68.266667-68.266667zM512 443.733333c-38.4 0-68.266667 29.866667-68.266667 68.266667 0 38.4 29.866667 68.266667 68.266667 68.266667s68.266667-29.866667 68.266667-68.266667c0-38.4-29.866667-68.266667-68.266667-68.266667zM832 443.733333c-38.4 0-68.266667 29.866667-68.266667 68.266667 0 38.4 29.866667 68.266667 68.266667 68.266667s68.266667-29.866667 68.266667-68.266667c0-38.4-34.133333-68.266667-68.266667-68.266667z" fill="#111111" p-id="9200"></path></svg>
						<div class="popoverBox" v-if="showCardId===item.id">
							<div v-if="item.userid===userinfo.userid" @click="editAppFn(item)">
								<img src="../../assets/images/appStore/edit.svg"> 
								<span>编辑</span>
							</div>
							<div v-if="item.json && item.json.copy==='1'" @click="copyAppFn(item)">
								<img src="../../assets/images/appStore/copy.svg"> 
								<span>复制</span>
							</div>
							<div v-if="item.userid===userinfo.userid" @click="deleteAppFn(item)">
								<img src="../../assets/images/appStore/del.svg"> 
								<span>删除</span>
							</div>
						</div>
					</div>
        </div>
        <div class="as_c_i_bottom">
          <div>{{ item.detail }}</div>
          <span @click="openUrl(item.url)">{{ item.url }}</span>
        </div>
      </div>
      <span class="as_c_empty" v-if="dataList.length === 0">
        暂无应用...
      </span>
    </div>
		<appStorePopup ref="appStorePopupRef" :typeList="typeList" @success="appStorePopupSuccess"/>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getStoreType, getStore,addApp,editApp,insertSave,deleteApp } 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 {
      dataList: [],
      typeList: [],
      showType: '',
      searchText: '',
      selectJuri: 3,
      selectList: [
        { index: 1, label: '我的' },
        { index: 2, label: '组织' },
        { index: 3, label: '所有人' }
      ],
      getDataLoading: false,
			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;
			}
		}
  },
  methods: {
    getData() {
      this.getDataLoading = true
      let params = {
        uid: this.userinfo.userid,
        name: this.searchText,
        label: '',
        type: this.showType,
        juri: this.selectJuri,
        stand: 'cn'
      }

      getStore(params)
        .then(res => {
          let _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.getDataLoading = false
        })
        .catch(err => {
          this.getDataLoading = false
          this.$toast.error('获取应用数据失败')
        })
    },
    getAllStoreType() {
      let params = {
        suserid: this.userinfo.userid,
        sorg: this.userinfo.org,
        soid: this.userinfo.organizeid,
        sstand: 'cn'
      }

      getStoreType(params)
        .then(res => {
          let _data = res[0]
          if (_data.length > 0) {
            this.typeList = _data
          } else {
            this.typeList = []
          }
        })
        .catch(err => {
          console.log(err)
          this.$toast.error('获取应用类型失败')
        })
    },
    openUrl(url) {
      window.open(url, '_blank')
    },
    addAppFn() {
      this.$refs.appStorePopupRef.open({type:1})
    },
		editAppFn(data){
			this.$refs.appStorePopupRef.open({type:2,form:{
				id: data.id,
          nname: data.name,
          nlabel: data.label,
          ndetail: data.detail,
          nurl: data.url,
          ntype: data.type,
          njuri: data.juri,
          nstand: data.stand,
          njson: data.json
			}})
		},
		copyAppFn(item){
			Dialog.confirm({
				title:"复制应用",
				message:`确定复制《${item.name}》这个应用吗?`
			}).then(_=>{
				let params = [
					{
						name:`${item.name}_copy`,
						userid:this.userinfo.userid,
						label:item.label,
						detail:item.detail,
						url:item.url,
						type:item.type,
						juri:"1",
						stand:"cn",
						json:JSON.stringify(item.json)
					}
				]

				addApp(params).then(res=>{
					if(res==1){
						this.insertSaveFn(item,3)
						Toast.success("已复制到我的列表")
					}else{
						this.$toast.fail("复制失败")
					}
					this.getData()
				}).catch(e=>{
					console.log(e);
					this.$toast.fail("复制失败")
				})
			}).catch(_=>{
				
			})
		},
		deleteAppFn(item){
			Dialog.confirm({
				title:"删除应用",
				message:`确定删除《${item.name}》这个应用吗?`
			}).then(_=>{
				let params = [{
					uid:this.userinfo.userid,
					aid:item.id
				}]
				deleteApp(params).then(res=>{
					if(res==1){
						this.$toast.success("删除应用成功")
						
					}else{
						this.$toast.fail("删除应用失败")
					}
					this.getData()
				}).catch(e=>{
					console.log(e)
					this.$toast.fail("删除应用失败")
				})

			}).catch(_=>{
				console.log("取消删除")
			})
		},
		insertSaveFn(item,type){
			return new Promise(resolve=>{
				let params = [{
					uid:this.userinfo.userid,
					type:type,
					aid:item.id,
					json:""
				}]
				insertSave(params).then(res=>{
					if(res){
						resolve(1)
					}else{
						resolve(0)
					}
				}).catch(e=>{
					console.log(e)
					resolve(0)
				})

			})
		},
		appStorePopupSuccess(data,type){
			if (type === 1) {
        //添加
        let params = [
          {
            nname: data.nname, //app名称
            nuserid: this.userinfo.userid, //创建的用户ID
            nlabel: data.nlabel, //app标签
            ndetail: data.ndetail, //app简介
            nurl: data.nurl, //app链接
            ntype: data.ntype, //app类型
            njuri: data.njuri, //app权限 1:我的 2:组织 3:所有人
            nstand: "cn", //语言
            njson: "" //其他信息
          }
        ];
        addApp(params).then(res => {
            if (res == 1) {
              this.$message.success("添加成功");
              this.$refs.appStorePopupRef.close(true);
              this.getData();
            } else {
              this.$message.error("添加失败");
              this.$refs.appStorePopupRef.loading = false;
            }
          })
          .catch(err => {
            console.log(err);
            this.$message.error("添加失败");
          });
      } else if (type === 2) {
				let params = [
					{
						aid: data.id,
						nname: data.nname, //app名称
            nuserid: this.userinfo.userid, //创建的用户ID
            nlabel: data.nlabel, //app标签
            ndetail: data.ndetail, //app简介
            nurl: data.nurl, //app链接
            ntype: data.ntype, //app类型
            njuri: data.njuri, //app权限 1:我的 2:组织 3:所有人
            nstand: "cn", //语言
            njson: data.njson //其他信息
					}
				]
				editApp(params).then(res => {
            if (res == 1) {
              this.$message.success("修改成功");
              this.$refs.appStorePopupRef.close(true);
              this.getData();
            } else {
              this.$message.error("修改失败");
              this.$refs.appStorePopupRef.loading = false;
            }
          })
          .catch(err => {
            console.log(err);
            this.$message.error("修改失败");
          });
      }
		},
		showCard(id){
			if(this.showCardId==id)return this.showCardId = null;
			this.showCardId = id
		},
		changeType(id){
			if(this.showType !== id){
				this.showType = id
				this.getData()
			}
		},
		closeCard(){
			this.showCardId = null
		}
  },
  mounted() {
    this.getData()
    this.getAllStoreType()
  }
}
</script>

<style lang="scss" scoped>
.appStore {
  width: 100vw;
  height: 100%;
  box-sizing: border-box;
  // padding: 5px;
  background-color: #f2f4f7;
  display: flex;
	overflow: auto;
  flex-direction: column;
}

.as_header {
  width: 100%;
  height: auto;
  background-color: #fff;
}

.as_h_top {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding: 0 10px;
  font-size: 20px;
  font-weight: bold;
  border-bottom: solid 1px #eeeeee;
  position: relative;
}

.addBtn {
  position: absolute;
  right: 5px;
}

.as_h_bottom {
  width: 100%;
  height: auto;
  padding: 10px 10px;
	box-sizing: border-box;
}

.as_h_typeList {
  width: calc(100% - 20px);
  height: auto;
	padding: 0 0px 10px 0px;
}

.as_h_typeList>span{
	display: block;
	float: left;
	font-size: 16px;
	margin-left: 10px;
	margin-bottom: 10px;
	white-space:nowrap;
}

.typeActive{
	color: #409eff;
}

.as_content {
  width: 100%;
  height: calc(100% - 100px);
  overflow: auto;
  box-sizing: border-box;
  padding: 10px;
}

.as_c_empty {
  width: 100%;
  height: auto;
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.as_c_item {
  width: 100%;
  height: 150px;
  background-color: #fff;
  float: left;
  border-radius: 10px;
  margin-bottom: 10px;
  box-shadow: 0 0 10px 0 rgba(#000000, 0.1);
}

.as_c_i_top {
  width: 100%;
  height: 50px;
  box-sizing: border-box;
  padding: 10px;
  display: flex;
}

.as_c_i_t_icon {
  width: 40px;
  height: 40px;
  box-sizing: border-box;
  display: flex;
}

.as_c_i_t_icon > svg {
  width: 100%;
  height: 100%;
}

.as_c_i_t_icon > img {
  width: 100%;
  height: 100%;
}

.as_c_i_t_name {
  width: calc(100% - 60px);
  height: 50px;
  float: right;
  line-height: 50px;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.as_c_i_t_desc {
  width: calc(100% - 60px);
  height: 50px;
  float: right;
  line-height: 50px;
  font-size: 14px;
  color: #666;
}

.as_c_i_t_message {
  width: calc(100% - 40px);
  height: 100%;
  margin-left: 10px;
}

.as_c_i_t_message > div {
  width: 100%;
  height: auto;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 16.5px;
  font-weight: bold;
}

.as_c_i_t_message > span {
  color: #8991a1;
  display: block;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
	font-size: 14px;
  text-overflow: ellipsis;
}

.as_c_i_bottom {
  width: 100%;
  height: calc(100% - 50px);
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding: 10px;
  justify-content: space-between;
  // background-color: red;
}

.as_c_i_bottom > div {
  width: 100%;
  max-height: calc(100% - 22px);
  color: #8991a1;
  display: -webkit-box;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  margin-bottom: 5px;
	font-size: 16px;
}

.as_c_i_bottom > span {
  display: block;
  max-width: 100%;
  height: 15px;
  color: #409eff;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 14px;
}

.ac_c_i_t_popover{
	width: 30px;
	height:30px;
	position: relative;
}

.ac_c_i_t_popover svg{
	width: 30px;
	height: 30px;
}

.popoverBox{
	position: absolute;
	width: 60px;
	height: auto;
	padding: 5px;
	border-radius: 8px 0 8px 8px;
	background-color: #fff;
	box-shadow: 0 0 10px 0 rgba(#000000, 0.1);
	right:0;
	top:calc(100% - 5px)
}

.popoverBox>div{
	display: flex;
	justify-content: center;
	align-items: center;
	padding:5px 10px;
}

.popoverBox>div>img{
	width: 12px;
	height: 12px;
	margin-right: 4px;
}

.popoverBox>div:hover{
	color: #409eff;
}
</style>
