<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <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>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['chat:chatRole:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['chat:chatRole:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['chat:chatRole:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="chatRoleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="roleId" />
      <el-table-column label="客服名称" align="center" prop="roleName" />
      <el-table-column label="客服头像" width="150" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" style="height: 80px">
        </template>
      </el-table-column>
      <el-table-column  label="类型"  align="center" prop="roleType">
            <template slot-scope="scope">
                <el-tag prop="type" v-for="(item, index) in typeOptions"    v-if="scope.row.roleType==item.dictValue">{{item.dictLabel}}</el-tag>
              </template>
      </el-table-column>
      <el-table-column label="客服ID" align="center" prop="kfId" />
      <el-table-column label="客服链接" align="center" prop="kfUrl" />
      <el-table-column  label="AI模型"  align="center" prop="mode">
            <template slot-scope="scope">
                <el-tag prop="type" v-for="(item, index) in modeOptions"    v-if="scope.row.mode==item.dictValue">{{item.dictLabel}}</el-tag>
              </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleShowQr(scope.row)"
            v-hasPermi="['chat:chatRole:qrcode']"
          >获取客服二维码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['chat:chatRole:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['chat:chatRole:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改聊天角色对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客服名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入客服名称" />
        </el-form-item>
        <el-form-item label="类型" prop="roleType">
          <el-select v-model="form.roleType" placeholder="请选择类型" clearable size="small">
              <el-option
                    v-for="item in typeOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
            </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="kfHeadUrl"  >
          <el-upload
            accept=".jpg"
            name="media"
            v-model="form.avatar"
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.avatar" :src="form.avatar" class="avatar" width="200px">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="AI模型" prop="mode">
          <el-select v-model="form.mode" placeholder="请选择AI模型" clearable size="small">
              <el-option
                    v-for="item in modeOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
            </el-select>
        </el-form-item>
        <el-form-item label="APPID"   v-if="form.mode==1">
          <el-input v-model="form.modeConfigJson.appId" placeholder="请输入文心一言APPID" />
        </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>
    <el-dialog title="客服二维码" :visible.sync="qrOpen" width="400px" append-to-body>
      <div v-if="qrOpen" id="kfqr" class="kfqr"></div>
    </el-dialog>
  </div>
</template>

<script>
import { listChatRole, getChatRole, delChatRole, addChatRole, updateChatRole, exportChatRole } from "@/api/chat/chatRole";
import { getUrl } from "@/api/chat/chatUpload";
import QRCode from 'qrcodejs2'
import { getUserProfile } from "@/api/company/companyUser";

export default {
  name: "ChatRole",
  data() {
    return {
      user:null,
      qrOpen:false,
      uploadUrl:process.env.VUE_APP_BASE_API+"/chat/upload/uploadFile/",
      modeOptions:[],
      typeOptions:[],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 聊天角色表格数据
      chatRoleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: null,
        companyId: null,
        roleType: null,
        configJson: null,
        mode: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "客服名称不能为空", trigger: "blur" }
        ],
        roleType: [
          { required: true, message: "类型不能为空", trigger: "blur" }
        ],
        mode: [
          { required: true, message: "AI模型不能为空", trigger: "blur" }
        ],
        avatar: [
          { required: true, message: "头像不能为空", trigger: "blur" }
        ],


      }
    };
  },
  created() {

    this.getDicts("chat_role_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getDicts("chat_role_mode").then((response) => {
      this.modeOptions = response.data;
    });
    this.getUser();
    this.getList();
  },
  methods: {
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.uploadUrl=this.uploadUrl+this.user.companyId;
      });
    },
    handleShowQr(row){
      this.qrOpen=true;
      setTimeout(() => {
        var qrcode = new QRCode("kfqr", {
          text: encodeURI(row.kfUrl), // uri二维码扫描后跳转的地址
          width: 200,
          height: 200,
          colorDark: "#000000",
          colorLight: "#ffffff",
        });
      }, 200);


    },
    getUrl(mediaId) {
      var param={
        mediaId:mediaId
      }
      getUrl(param).then(response => {
        //this.form.url = response.data.url;
      });
    },
    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.kfHeadUrl=res.data.url;
            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;
    },
    /** 查询聊天角色列表 */
    getList() {
      this.loading = true;
      listChatRole(this.queryParams).then(response => {
        this.chatRoleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        roleId: null,
        roleName: null,
        companyId: null,
        createTime: null,
        updateTime: null,
        roleType: null,
        configJson: null,
        mode: null,
        url:null,
        kfMediaId:null,
        kfHeadUrl:null,
        modeConfigJson:{
        }
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    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.open = true;
      this.title = "添加客服";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const roleId = row.roleId || this.ids
      getChatRole(roleId).then(response => {
        this.form = response.data;
        this.form.roleType = response.data.roleType.toString();
        this.form.mode = response.data.mode.toString();
        if(this.form.modeConfigJson!=null){
          this.form.modeConfigJson=JSON.parse(this.form.modeConfigJson)
        }

        this.open = true;
        this.title = "修改客服";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.modeConfigJson=JSON.stringify(this.form.modeConfigJson)
          if (this.form.roleId != null) {
            updateChatRole(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addChatRole(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.roleId || this.ids;
      this.$confirm('是否确认删除客服编号为"' + roleIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delChatRole(roleIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有客服数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportChatRole(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style>
.kfqr{
  padding:20px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
