<template>
  <div >
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" style="margin-left: 50px;margin-top: 20px;">
      <el-form-item label="" prop="roleName" >
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入客服名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      <!--  <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
      </el-form-item>
    </el-form>

	<div style="padding-left: 50px;padding-right: 50px;">
		<div class="container">
			 <div class="card add-card" @click="addCard">
			       <h3>+ 创建模型</h3>
			 </div>
		    <div class="card" v-for="(item, index) in fastGptRoleList" :key="index" @click="updateGpt(item)">
			  <div class="avatar-container" >
			      <div class="avatar-wrapper">
			          <img :src="item.avatar" alt="头像" class="avatar" />
			      </div>
			      <div class="avatar-info-wrapper">
			          <div class="card-name">{{item.roleName}}</div>
			      </div>
			  </div>
				
		      <div  class="card-content"  >{{item.reminderWords}}</div>
			  <div>
				
				  <span class="author">创建时间: {{item.createTime}}</span>
				  <span style="float: right;margin-right: 10px;">
					  <el-popover
						  popper-class="customPopper"
					      placement="left"
					      trigger="hover"
						  width="50px"
						  >
						  <div>
						  <div>
							<el-button
							  size="mini"
							  type="text"
							  @click="copy(item)"
							>复制</el-button>  
						  </div>
						 <div>
						<el-button
						  size="mini"
						  type="text"
						  @click="handleDelete(item)"
						>删除</el-button>  
						</div>
						  </div>
					      <a slot="reference">⋮</a>
					   </el-popover>
				  </span>
				  
			  </div>
			  
		 </div>
		</div>
	</div>
	
    <pagination style="margin-right: 40px;"
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
 
    <!-- 添加或修改应用对话框 --> 
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="客服名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名" />
        </el-form-item>
        <el-form-item label="客服头像" prop="avatar">
          <ImageUpload v-model="form.avatar" type="image" :num="1" :width="150" :height="150" style="margin-top: 1%;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFastGptRole, getFastGptRole, delFastGptRole, addFastGptRole, updateFastGptRole, exportFastGptRole,copyFastGptRole } from "@/api/fastGpt/fastGptRole";
import {allListTagGroup} from "@/api/qw/tagGroup";
import {listTag} from "@/api/qw/tag";
import {
  addFastGptRoleTag,
  delFastGptRoleTag,
  getListByRoleId,
  updateFastGptRoleTag
} from "@/api/fastGpt/fastGptRoleTag";
import source from "echarts/src/data/Source";
import ImageUpload from "@/views/qw/sop/ImageUpload.vue";

export default {
  name: "FastGptRole",
  components: {ImageUpload},
  data() {
    return {
	
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      //AI客服类型
      typeOptions: [],
      //AI模型
      modeOptions: [],
      changeTagsOpen: {
        title : "",
        open :false,
        roleId : null,
      },
      changeTagsOpenAdd:{
        title : "",
        open :false,
        roleId : null,
      },
      //标签弹窗选择
      tagChange:{
        open:false,
        title:"",
        roleId:null,
        id:null,
      },
      //新增
      tagChangeAdd:{
        open:false,
        title:"",
        roleId:null,
        id:null,
      },
      //所有的标签组-标签
      tagGroupList:[],

      //所有的标签
      tagList:[],
	  contactInfo:[],
      //已经选择的标签
      tagListFormIndex:[],

      //新的标签
      tagListFormIndexAdd:[],
      // uploadUrl:process.env.VUE_APP_BASE_API+"/chat/upload/uploadFile",
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      // 选中数组
      ids: [],
	  externalInfoOptions:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应用表格数据
      fastGptRoleList: [],
      // 弹出层标题
      title: "新增Ai角色",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: null,
        companyId: null,
        roleType: null,
        mode: null,
        kfId: null,
        kfUrl: null,
        avatar: null,
        kfMediaId: null
      },
      // 表单参数
      form: {
      },
      //某一个标签组
      tagsForm:{},
      //新增
      tagsFormAdd:{},
      //当前role的所有标签组
      tagsFormList:[],
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        roleType: [
          { required: true, message: "角色类型不能为空", trigger: "change" }
        ],
      },
      tagsFormRules:{
        tagIds:[
          { required: true, message: "标签不能为空", trigger: "blur" }
        ],
        reminderWords:[
          { required: true, message: "提示词不能为空", trigger: "blur" }
        ]
      },

      tagsFormAddRules:{
        tagIds:[
          { required: true, message: "标签不能为空", trigger: "blur" }
        ],
        reminderWords:[
          { required: true, message: "提示词不能为空", trigger: "blur" }
        ]
      }

    };
  },
  watch: {
    tagListFormIndex: {
      handler(newList) {
        if (!Array.isArray(newList)) return;  // 仅在 newList 为数组时继续

        // 确保 tagsForm.tagIds 是数组并清空它
        this.tagsForm.tagIds = [];

        // 遍历 newList，添加 tagId
        newList.forEach(tags => {
          if (Array.isArray(tags)) {
            // 如果 tags 是数组，遍历并添加
            tags.forEach(item => {
              if (item && item.tagId !== undefined) {
                this.tagsForm.tagIds.push(item.tagId);
              }
            });
          } else if (tags && tags.tagId !== undefined) {
            // 如果 tags 是单个对象，直接添加
            this.tagsForm.tagIds.push(tags.tagId);
          }
        });
      },
      deep: true
    },

    tagListFormIndexAdd: {
      handler(newList) {

        if (!Array.isArray(newList)) return;  // 仅在 newList 为数组时继续

        // 确保 tagsForm.tagIds 是数组并清空它
        this.tagsFormAdd.tagIds = [];

        // 遍历 newList，添加 tagId
        newList.forEach(tags => {
          if (Array.isArray(tags)) {
            // 如果 tags 是数组，遍历并添加
            tags.forEach(item => {
              if (item && item.tagId !== undefined) {
                this.tagsFormAdd.tagIds.push(item.tagId);
              }
            });
          } else if (tags && tags.tagId !== undefined) {
            // 如果 tags 是单个对象，直接添加
            this.tagsFormAdd.tagIds.push(tags.tagId);
          }
        });
      },
      deep: true
    }
  },
  created() {
    //客服类型
    this.getDicts("chat_role_type").then((response) => {
      this.typeOptions = response.data;
    });
    //AI模型
    this.getDicts("chat_role_mode").then((response) => {
      this.modeOptions = response.data;
    });
	this.getDicts("sys_fastgpt_role_external_info").then((response) => {
	  this.externalInfoOptions = response.data;
	});
    this.getList();
  },
  methods: {
    /** 查询应用列表 */
    getList() {
      this.loading = true;
      listFastGptRole(this.queryParams).then(response => {
        this.fastGptRoleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelTags(){
      this.changeTagsOpen.open=false;
    },
    cancelAddTags(){
      this.changeTagsOpenAdd.open=false;
    },
    handleAvatarSuccess(res, file) {
      if(res.code==200){
        if(res.data.errcode!=0){
          this.msgError(res.data.errmsg);
        }
        else{
          //获取图片
          this.form.kfMediaId=res.data.media_id;
          this.form.avatar = res.ossUrl;
          this.$forceUpdate()
        }

      }
      else{
        this.msgError(res.msg);
      }
    },
    beforeAvatarUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return   isLt1M;
    },
    // 表单重置
    reset() {
      this.form = {
        roleId: null,
        roleName: null,
        companyId: null,
        createTime: null,
        updateTime: null,
        roleType: null,
        modeConfigJson:{APPKey:null,Key:null},
        mode: 2,
        kfId: null,
        kfUrl: null,
        avatar: null,
        kfMediaId: null,
        reminderWords: null,
        isTags:null,
      };
      this.resetForm("form");
    },

    tagRest(){
      this.tagListFormIndex=[];
      this.tagsForm={
        tagIds:null,
        reminderWords:null,
      };
    },

    tagAddRest(){
      this.tagListFormIndexAdd=[];
      this.tagsFormAdd={
        tagIds:null,
        reminderWords:null,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
	  this.contactInfo=[];
      this.open = true;
      this.title = "添加应用";
    },
	addCard(){
		this.title="新增Ai客服"
		this.open=true
	},
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
	  this.contactInfo=[];
      const roleId = row.roleId || this.ids
      getFastGptRole(roleId).then(response => {
        this.form = response.role;
        this.form.roleType = JSON.stringify(response.role.roleType);
        if(this.form.modeConfigJson!=null){
          this.form.modeConfigJson=JSON.parse(this.form.modeConfigJson)
        }
		if(this.form.contactInfo!=null){
		  this.contactInfo = (this.form.contactInfo).split(",");
		}
        //含标签吗
        getListByRoleId(roleId).then(res => {
          this.tagsFormList=res.rows;
        })

        //所有的标签组
        allListTagGroup({corpId:row.bindCorpId}).then(response => {
          this.tagGroupList = response.rows;
        });

        //所有的标签
        listTag({corpId:row.bindCorpId}).then(response => {
          this.tagList = response.rows;
        });

        this.open = true;
        this.title = "修改应用";
      });

    },

    getTagNames(tagIds) {
      // 确保 tagIds 是数组，如果是字符串则分割
      const idsArray = Array.isArray(tagIds) ? tagIds : tagIds.split(",");
      return idsArray.map(tagId => {
        const tag = this.tagList.find(list => list.tagId === tagId);
        return tag ? tag.name : tagId; // 返回标签名称或原 tagId
      }).join(', '); // 使用逗号和空格连接标签名称
    },

    //标签回复人设弹窗
    handleAddTags(value,bindCorpId) {
      if (bindCorpId==null){
        this.$message({
          message: '请先给AI客服-绑定企业 再添加标签【企微管理->员工管理->企微员工】',
          type: 'warning'
        });
        return;
      }

      this.changeTagsOpenAdd.title="创建标签回复人设";
      this.changeTagsOpenAdd.open=true;
      this.changeTagsOpenAdd.roleId=value;
    },

    //选择标签弹窗
    handleChangeTags(roleId){

      this.tagChange.open=true;
      this.tagChange.title='选择标签';
      this.tagChange.roleId=roleId;

      // 获取 tagListFormIndex 中的所有 tagId，用于快速查找
      const selectedTagIds = new Set(this.tagListFormIndex.map(tagItem => tagItem.tagId));
      for (let i = 0; i < this.tagGroupList.length; i++) {
        for (let x = 0; x < this.tagGroupList[i].tag.length; x++) {
          this.tagGroupList[i].tag[x].isSelected = selectedTagIds.has(this.tagGroupList[i].tag[x].tagId);
        }
      }

    },
    handleChangeTagsAdd(roleId){
      this.tagChangeAdd.open=true;
      this.tagChangeAdd.title='选择标签';
      this.tagChangeAdd.roleId=roleId;
    },
    //标签的选择
    tagSelection(row){
      row.isSelected= !row.isSelected;
      this.$forceUpdate();
    },
    //删除一些已经选择了的标签
    handleCloseTag(list){

      // 假设 list 对象具有一个 id 属性
      const ls = this.tagListFormIndex.findIndex(t => t.tagId === list.tagId);
      if (ls !== -1) {
        this.tagListFormIndex.splice(ls, 1);
        this.tagListFormIndex = [...this.tagListFormIndex];
      }
    },

    //删除一下已经存在的
    handleCloseRoleTag(row){
      delFastGptRoleTag(row.id).then(res => {
        getListByRoleId(row.roleId).then(res => {
          this.tagsFormList=res.rows;
        })
      })
    },

    //点击单个
    handleEditRoleTag(value, index) {

      this.changeTagsOpen.open = true;
      this.changeTagsOpen.title = "编辑标签回复人设";
      this.changeTagsOpen.roleId = value.roleId;
      this.tagsForm = value;

      // 过滤 tagList，获取匹配的标签
      const tagIdsArray = Array.isArray(value.tagIds) ? value.tagIds : value.tagIds.split(",");
      this.tagListFormIndex = this.tagList.filter(tag => tagIdsArray.includes(tag.tagId));
    },
    //选择标签
    editTagSubmitForm(){

      for (let i = 0; i < this.tagGroupList.length; i++) {
        for (let x = 0; x < this.tagGroupList[i].tag.length; x++) {
          if (this.tagGroupList[i].tag[x].isSelected === true) {

            if (!this.tagListFormIndex) {
              this.tagListFormIndex = [];
            }

            // 检查当前 tag 是否已经存在于 tagListFormIndex[index] 中
            let tagExists = this.tagListFormIndex.some(
              tag => tag.id === this.tagGroupList[i].tag[x].id
            );

            // 如果 tag 不存在于 tagListFormIndex[index] 中，则新增
            if (!tagExists) {
              this.tagListFormIndex.push(this.tagGroupList[i].tag[x]);
            }
          }
        }
      }
      if (!this.tagListFormIndex || this.tagListFormIndex.length === 0) {
        return this.$message('请选择标签');
      }

      this.tagChange.open = false;
    },

    //新增的标签
    addTagSubmitForm(){
      for (let i = 0; i < this.tagGroupList.length; i++) {
        for (let x = 0; x < this.tagGroupList[i].tag.length; x++) {
          if (this.tagGroupList[i].tag[x].isSelected === true) {

            if (!this.tagListFormIndexAdd) {
              this.tagListFormIndexAdd = [];
            }

            // 检查当前 tag 是否已经存在于 tagListFormIndex[index] 中
            let tagExists = this.tagListFormIndexAdd.some(
              tag => tag.id === this.tagGroupList[i].tag[x].id
            );

            // 如果 tag 不存在于 tagListFormIndex[index] 中，则新增
            if (!tagExists) {
              this.tagListFormIndexAdd.push(this.tagGroupList[i].tag[x]);
            }
          }
        }
      }
      if (!this.tagListFormIndexAdd || this.tagListFormIndexAdd.length === 0) {
        return this.$message('请选择标签');
      }

      this.tagChangeAdd.open = false;
    },
	copy(row){
		this.form={
			roleId:row.roleId,
			avatar:null,
			roleName:null,
		}
		this.title="复制Ai"
		this.open=true;
	},
    //取消选择标签
    editTagCancel(){
      this.tagChange.open = false;
      // this.tagRest();
    },
    addTagCancel(){
      this.tagChangeAdd.open = false;
      this.tagAddRest();
    },
    /** 提交按钮 */
    submitForm() {
		if(this.contactInfo!=null){
		   this.form.contactInfo= (this.contactInfo).toString()
		}
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.modeConfigJson=JSON.stringify(this.form.modeConfigJson)
          if (this.form.roleId != null) {
            copyFastGptRole(this.form).then(response => {
              this.msgSuccess("复制成功");
              this.open = false;
              this.getList();
            });
          } else {
			  this.form.mode=2
			  this.form.roleType=1
            addFastGptRole(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitTagsForm(roleId){
      this.$refs["tagsForm"].validate(valid => {
        if (valid) {

          this.tagsForm.roleId=roleId
          this.tagsForm.tagIds=this.tagsForm.tagIds.join(",")
          if (this.tagsForm.id!= null) {
            updateFastGptRoleTag(this.tagsForm).then(response => {
              this.msgSuccess("修改成功");
              this.changeTagsOpen = false;
              this.getList();
            });
          }else {
            addFastGptRoleTag(this.tagsForm).then(response => {
              this.msgSuccess("新增成功");
              this.changeTagsOpen = false;
              this.getList();
            });
            }
        }
      });
    },
	updateGpt(row){
		 this.$router.push('/fastGpt/fastGptRole1/uadateFastGptRole/'+row.roleId)
	},
    submitAddTagsForm(roleId){
      this.$refs["tagsFormAdd"].validate(valid => {
        if (valid) {
          this.tagsFormAdd.roleId=roleId
          this.tagsFormAdd.tagIds=this.tagsFormAdd.tagIds.join(",")
            addFastGptRoleTag(this.tagsFormAdd).then(response => {
              this.msgSuccess("新增成功");
              this.changeTagsOpenAdd = false;
              this.open=false;
              this.getList();
            });

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.roleId || this.ids;
      this.$confirm('是否确认删除应用编号为"' + roleIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFastGptRole(roleIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有应用数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportFastGptRole(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style scoped>
.container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px; /* 卡片间距 */
  justify-content: flex-start; /* 靠左对齐 */
}

.card {
  width: calc((100% - 32px) / 3); /* 三列布局，16px间距 */
  border: 1px solid green; /* 绿色边框 */
  border-radius: 10px; /* 圆角 */
  padding: 16px; /* 内边距 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  background-color: #fff; /* 白色背景 */
  cursor: pointer; /* 鼠标悬停样式 */
  height: 200px;
}

.card-name {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.card-content {
  margin: 20px 10px 10px 10px;
  height: 80px;
  color: #666;
}

.author {
  color: #999;
}

/* 新增卡片样式 */
.add-card {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  background-color: #f5f5f5; /* 浅灰色背景 */
  border: 1px solid green; /* 虚线边框 */
  color: green; /* 字体颜色 */
}

.add-card:hover {
  background-color: #e8f5e9; /* 悬停效果 */
}
.pagination-container{
	background-color: rgb(240, 242, 245); /* 悬停效果 */
}
.avatar {
  width: 30px; /* 固定宽度 */
  height: 30px; /* 固定高度 */
  border-radius: 50%; /* 裁剪为圆形 */
  object-fit: cover; /* 保证图片不会变形 */
  margin-right: 8px; /* 和标题的间距 */
}
.avatar-container {
    display: flex;
    align-items: center;
    justify-content: flex-start; /* 左对齐 */
}

.avatar-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
}

.avatar-info-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
}


</style>
<style>
	.el-popover{
		min-width: 10px;
	}
</style>