<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="88px">
<!--      <el-form-item label="营销关键字" prop="keyword" style="white-space: nowrap;">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入营销关键字"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="营销关键字" prop="keyword"  style="white-space: nowrap;">
        <el-select v-model="queryParams.keyword" clearable placeholder="请选择营销关键字">
          <el-option
            v-for="dict in keywordOptions"
            :key="dict.keyword"
            :label="dict.keyword"
            :value="dict.keyword"
          ></el-option>
        </el-select>
      </el-form-item>
     <el-form-item label="发送文字内容" prop="content" style="white-space: nowrap;">
        <el-input
          v-model="queryParams.content"
          placeholder="请输入发送文字内容"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="内容类型" prop="contentType">
        <el-select v-model="queryParams.contentType" placeholder="请选择内容类型" clearable size="small">
          <el-option
            v-for="dict in contentTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客服角色" prop="roleIds">
        <el-select v-model="queryParams.roleIds" placeholder="请选择客服角色" clearable size="small">
          <el-option
            v-for="item in roles"
            :key="item.roleId"
            :label="item.roleName"
            :value="item.roleId"
          />
        </el-select>
      </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="['fastGpt:fastGptKeywordSend: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="['fastGpt:fastGptKeywordSend: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="['fastGpt:fastGptKeywordSend:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['fastGpt:fastGptKeywordSend:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="fastGptKeywordSendList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="营销关键字" align="center" prop="keyword"/>
      <el-table-column label="内容类型" align="center" prop="contentType">
        <template slot-scope="scope">
          <dict-tag :options="contentTypeOptions" :value="scope.row.contentType"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="图片访问地址" align="center" prop="imgUrl" />-->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="客服角色" align="center" prop="roleIds">
        <template slot-scope="scope">
          {{ getRoleNameById(scope.row.roleIds) }}
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDetails(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fastGpt:fastGptKeywordSend:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fastGpt:fastGptKeywordSend: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"
    />

    <!-- 添加或修改Ai指令对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="营销关键字" prop="keyword">
          <el-select v-model="form.keyword" placeholder="请选择营销关键字">
            <el-option
              v-for="dict in keywordOptions"
              :key="dict.keyword"
              :label="dict.keyword"
              :value="dict.keyword"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发送内容" prop="content">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="请输入发送内容"
            v-model="form.content">
          </el-input>
        </el-form-item>
        <el-form-item label="内容类型" prop="contentType">
          <el-select v-model="form.contentType" placeholder="请选择内容类型">
            <el-option
              v-for="dict in contentTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="imgUrl" v-if="this.form.contentType !== 0">
          <ImageUpload v-model="form.imgUrl"  type="image" :limit="1" :width="100" :height="100" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="客服角色" prop="roleIds">
          <el-select
            v-model="form.roleIds"
            placeholder="请选择客服角色"
            size="small"
            multiple
            filterable
            clearable
            :filter-method="filterRoles"
          >
            <el-option
              v-for="item in filteredRoles"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"/>
          </el-select>
        </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-drawer
      :with-header="false"
      size="75%"  @close="handleDrawerClose"
      :title="show.title" :visible.sync="show.open">
      <fastGptKeyWordDetails  ref="Details" />
    </el-drawer>
  </div>
</template>

<script>
import {
  listFastGptKeywordSend,
  getFastGptKeywordSend,
  delFastGptKeywordSend,
  addFastGptKeywordSend,
  updateFastGptKeywordSend,
  exportFastGptKeywordSend,
  keywordList
} from "@/api/fastGpt/fastGptKeywordSend";
import ImageUpload from "@/components/ImageUpload/index.vue";
import fastGptKeyWordDetails from "@/views/fastGpt/fastGptKeywordSend/fastGptKeyWordDetails.vue";
import { getAllRoleList } from "@/api/fastGpt/fastGptRole";

export default {
  name: "FastGptKeywordSend",
  components: {fastGptKeyWordDetails, ImageUpload},
  data() {
    return {
      show:{
        title:"指令内容",
        open:false,
      },
      roleMap:{},
      roles:[],
      filteredRoles: [], // 过滤后的角色数据
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // Ai指令表格数据
      fastGptKeywordSendList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 关键字内容字典
      keywordOptions: [],
      // 内容类型字典
      contentTypeOptions: [],
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        content: null,
        contentType: null,
        imgUrl: null,
        status: null,
        roleIds: [],
        createTime: null,
      },
      // 表单参数
      form: {roleIds: [],},
      // 表单校验
      rules: {
        keyword: [
          { required: true, message: "营销关键字不能为空", trigger: "change" }
        ],
        content: [
          // 如果 contentType 不是纯文本类型（比如图文混合），可以动态设置校验规则
          // 这里假设纯文本内容不需要上传图片
          { validator: (rule, value, callback) => {
              const { contentType } = this.form;
              if (contentType === 0 && !value) {
                callback(new Error("发送文字内容不能为空"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        imgUrl: [
          { validator: (rule, value, callback) => {
              const { contentType } = this.form;
              if (contentType !== 0 && !value) {
                callback(new Error("图片不能为空"));
              } else {
                callback();
              }
            },
            trigger: "change"
          }
        ],
        roleIds: [
          { required: true, message: "至少选择一个客服角色", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    Promise.all([
      keywordList().then(response => {
        this.keywordOptions = response.data;
      }),
    this.getDicts("sys_fastgpt_keyword_file_type").then(response => {
      this.contentTypeOptions = response.data;
    }),
    this.getDicts("sys_fastgpt_keyword_send_status").then(response => {
      this.statusOptions = response.data;
    }),
      getAllRoleList().then(response => {
        this.roles = response.data;
        this.filteredRoles = response.data;
        // 生成角色映射表
        this.roleMap = response.data.reduce((map, role) => {
          map[role.roleId] = role.roleName;
          return map;
        }, {});
      })
    ])
  },
  methods: {
    /** 查询Ai指令列表 */
    getList() {
      this.loading = true;
      listFastGptKeywordSend(this.queryParams).then(response => {
        this.fastGptKeywordSendList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 添加过滤方法
    filterRoles(query) {
      this.filteredRoles = this.roles.filter(item =>
        item.roleName.toLowerCase().includes(query.toLowerCase())
      );
    },
    // 获取角色名
    getRoleNameById(roleIds) {
      if (!roleIds) return '-';

      // 确保 roleIds 是数组
      const idArray = Array.isArray(roleIds) ? roleIds : roleIds.split(',').map(id => id.trim());
      return idArray
        .map(id => this.roleMap[id])
        .filter(name => name)
        .join('、');
    },
    //查看按钮
    handleDetails(row){
      this.show.open=true;
      setTimeout(() => {
        this.$refs.Details.getDetails(row.id);
      }, 500);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      getAllRoleList().then(response => {
        this.roles = response.data;
        this.filteredRoles = response.data;
      });
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        keyword: null,
        content: null,
        contentType: null,
        imgUrl: null,
        status: 0,
        roleIds: [],
        createTime: null
      };
      this.resetForm("form");

    },
    //关闭
    handleDrawerClose(){
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加Ai指令";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getFastGptKeywordSend(id).then(response => {
        const data = response.data;
        this.form = {
          ...data,
          roleIds: data.roleIds ? data.roleIds.split(',').map(Number) : [] // 确保转为 number[]
        };
        this.open = true;
        this.title = "修改Ai指令";
        this.$nextTick(() => {
          this.$forceUpdate(); // 强制更新 el-select 的绑定
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 提取 roleIds 数组中的 roleId 字段组成字符串
          this.form.roleIds = this.form.roleIds.join(',');
          if (this.form.id != null) {
            updateFastGptKeywordSend(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFastGptKeywordSend(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除Ai指令编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delFastGptKeywordSend(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有Ai指令数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportFastGptKeywordSend(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  }
};
</script>
<style scoped>.el-form-item__content {
  white-space: nowrap;
}
</style>
