<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="教练名称" prop="teacherName">
        <el-input
          v-model="queryParams.teacherName"
          placeholder="请输入教练名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="教练风采状态" prop="releases">
        <el-select
          v-model="queryParams.releases"
          placeholder="请选择状态"
          clearable
          style="width: 100%"
        >
          <el-option label="不展示" value="0"></el-option>
          <el-option label="展示" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="float: right">
        <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="['system:teacher: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="['system:teacher: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="['system:teacher:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="teacherList"
      @selection-change="handleSelectionChange"
      border
      :header-cell-style="{'text-align': 'center'}"
      :cell-style="{'text-align': 'center'}"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="员工编号" align="center" prop="userId" width="80" />
      <el-table-column label="员工昵称" align="center" prop="nickName" width="80" />
      <el-table-column label="教练名称（app展示）" align="center" prop="teacherName" width="150"/>
      <el-table-column label="头像" align="center" prop="avatarImg" width="100">
        <template slot-scope="scope">
          <el-image
            :src="getFullImgUrl(scope.row.avatarImg)"
            :preview-src-list="[getFullImgUrl(scope.row.avatarImg)]"
            style="width: 60px; height: 60px; border-radius: 50%;"
            fit="cover"
            :lazy="false"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="教练风采状态" align="center" prop="releases" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.releases === 1 ? 'success' : 'info'">
            {{ scope.row.releases === 1 ? '展示' : '不展示' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="教练风采相册" align="center" prop="url" width="300">
        <template slot-scope="scope">
          <div v-if="scope.row.url" class="album-images">
            <el-image
              v-for="(img, index) in splitImages(scope.row.url).slice(0, 3)"
              :key="index"
              :src="getFullImgUrl(img)"
              :preview-src-list="splitImages(scope.row.url).map(item => getFullImgUrl(item))"
              class="album-img"
              fit="cover"
              :lazy="false"
            ></el-image>
            <span v-if="splitImages(scope.row.url).length > 3" class="more-count">
              +{{ splitImages(scope.row.url).length - 3 }}
            </span>
          </div>
          <span v-else class="no-image">无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="教练风采内容" align="center" prop="context" >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="showContentDialog(scope.row.context)"
            size="mini"
          >查看内容</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="140">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:teacher:edit']"
          >修改</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['system:teacher: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="800px" append-to-body @opened="onDialogOpened">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="员工编号" prop="userId">
          <el-select
            v-model="form.userId"
            placeholder="请选择员工"
            clearable
            filterable
            style="width: 100%"
            @change="selectUser"
            :disabled="title === '修改教练信息' ?true:false"
          >
            <el-option
              v-for="emp in employeeList"
              :key="emp.userId"
              :label="emp.nickName"
              :value="emp.userId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="教练名称" prop="teacherName">
          <el-input v-model="form.teacherName" placeholder="请输入教练名称" />
        </el-form-item>
        <el-form-item label="教练风采状态" prop="releases">
          <el-radio-group v-model="form.releases">
            <el-radio label="0">不展示</el-radio>
            <el-radio label="1">展示</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 头像上传区域 -->
        <el-form-item label="头像" prop="avatarImg">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="uploadHeaders"
            :disabled="isUploading"
          >
            <el-image
              v-if="form.avatarImg"
              :src="getFullImgUrl(form.avatarImg)"
              style="width: 100px; height: 100px; border-radius: 50%;"
              fit="cover"
              :lazy="false"
            >
              <div slot="error" class="image-error">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <el-loading
              v-if="isUploading"
              text="上传中..."
              target=".avatar-uploader"
              background="rgba(255,255,255,0.8)"
            ></el-loading>
          </el-upload>
        </el-form-item>
        <el-form-item label="教练风采相册" prop="url">
          <el-upload
            :action="uploadImgUrl"
            list-type="picture-card"
            :file-list="albumFileList"
            :on-success="handleAlbumSuccess"
            :on-remove="handleAlbumRemove"
            :limit="6"
            :on-exceed="handleExceed"
            :before-upload="beforeAlbumUpload"
            :headers="uploadHeaders"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">
              支持JPG/PNG格式，单张不超过2MB，最多上传6张
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="教练风采内容" prop="context">
          <div class="editor-container">
            <div ref="editor" style="width: 100%; min-height: 300px;"></div>
          </div>
        </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="contentDialogVisible"
      width="800px"
      :before-close="handleDialogClose"
    >
      <div v-html="contentDialogContent" class="content-viewer"></div>
    </el-dialog>
  </div>
</template>

<script>
import { listTeacher, getTeacher, delTeacher, addTeacher, updateTeacher,getUserForTeacher } from "@/api/columns/teacher";
import { listAll } from "@/api/system/user";
import WangEditor from 'wangeditor';
import { getToken } from '@/utils/auth';
import axios from 'axios';
import Pagination from '@/components/Pagination';
import RightToolbar from '@/components/RightToolbar';

export default {
  name: "Teacher",
  components: {
    Pagination,
    RightToolbar
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      teacherList: [],
      employeeList: [],
      title: "",
      open: false,
      contentDialogVisible: false,
      contentDialogContent: "",
      uploadHeaders: {
        Authorization: getToken()
      },
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/com/file/upload",
      isUploading: false,
      baseUrl: process.env.VUE_APP_BASE_API || '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teacherName: null,
        releases: null,
      },
      form: {
        releases: "0"
      },
      editor: null,
      albumFileList: [],
      rules: {
        userId: [
          { required: true, message: "请选择员工", trigger: "change" }
        ],
        teacherName: [
          { required: true, message: "教练名称不能为空", trigger: "blur" }
        ],
        releases: [
          { required: true, message: "请选择状态", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getBase();

  },
  methods: {
    /** 对话框打开后回调 */
    onDialogOpened() {
      if (!this.editor) {
        this.initEditor();
      }
    },

    /** 初始化富文本编辑器 */
    initEditor() {
      console.log(11)
      console.log("初始化富文本")
      if (this.$refs.editor) {
        this.editor = new WangEditor(this.$refs.editor);

        // 关闭默认网络图片上传
        this.editor.config.showLinkImg = false;

        // 自定义图片上传逻辑
        this.editor.config.customUploadImg = async (resultFiles, insertImgFn) => {
          this.isUploading = true;

          try {
            for (const file of resultFiles) {
              const formData = new FormData();
              formData.append('file', file);

              const response = await axios({
                url: this.uploadImgUrl,
                method: 'post',
                data: formData,
                headers: {
                  ...this.uploadHeaders,
                  'Content-Type': 'multipart/form-data'
                },
                timeout: 30000
              });

              if (response.data && response.data.code === 200 && response.data.data) {
                // 存储相对路径，显示时拼接基础路径
                const relativeUrl = response.data.data;
                const fullUrl = this.getFullImgUrl(relativeUrl);
                // 插入图片并设置正确路径
                insertImgFn(fullUrl, file.name || '图片', 'max-width:100%;height:auto;');
                // 强制同步内容到表单
                this.form.context = this.editor.txt.html();
                this.$message.success('图片上传成功');
              } else {
                this.$message.error('图片上传失败: ' + (response.data?.msg || '服务器返回异常'));
              }
            }
          } catch (error) {
            console.error('富文本图片上传错误:', error);
            this.$message.error('上传失败，请检查网络或联系管理员');
          } finally {
            this.isUploading = false;
          }
        };

        // 内容变化时同步到表单
        this.editor.config.onchange = (html) => {
          const processedHtml = html.replace(/<img/g, '<img style="max-width:100%;height:auto;"');
          this.form.context = processedHtml;
          console.log(this.form.context)
        };

        // 配置菜单栏
        this.editor.config.menus = [
          'head', 'bold', 'fontSize', 'fontName', 'italic', 'underline',
          'strikeThrough', 'foreColor', 'backColor', 'link', 'list',
          'justify', 'quote', 'emoticon', 'image', 'table', 'undo', 'redo'
        ];

        // 创建编辑器实例
        this.editor.create();
      } else {
        setTimeout(() => this.initEditor(), 100);
      }
    },

    /** 查询列表 */
    getList() {
      this.loading = true;
      listTeacher(this.queryParams).then(response => {
        this.teacherList = response.rows || [];
        this.total = response.total? Number(response.total):0;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取列表数据失败');
      });
    },

    /** 获取员工列表 */
    getBase() {
      this.loading = true;
      getUserForTeacher().then(res => {
        this.employeeList = res.data || [];
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取员工列表失败');
      });
    },

    /** 显示内容对话框 */
    showContentDialog(content) {
      let processedContent = content || '';
      processedContent = processedContent.replace(
        /<img/g,
        '<img style="max-width:100%;height:auto;margin:10px auto;display:block;"'
      );
      this.contentDialogContent = processedContent;
      this.contentDialogVisible = true;
    },

    /** 关闭内容对话框 */
    handleDialogClose() {
      this.contentDialogContent = "";
      this.contentDialogVisible = false;
    },

    /** 分割图片URL */
    splitImages(urlStr) {
      if (!urlStr || typeof urlStr !== 'string') return [];
      return urlStr.split(',').filter(img => img && img.trim());
    },

    /** 处理头像上传成功 */
    handleAvatarSuccess(response) {
      this.isUploading = false;
      if (response && response.code === 200 && response.data) {
        this.form.avatarImg = response.data;
        this.$nextTick(() => {
          this.$message.success('头像上传成功');
        });
      } else {
        this.$message.error('上传失败：' + (response.msg || '返回格式错误'));
      }
    },

    /** 头像上传前校验 */
    beforeAvatarUpload(file) {
      this.isUploading = true;
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.isUploading = false;
        this.$message.error('只能上传JPG/PNG格式的图片');
        return false;
      }
      if (!isLt2M) {
        this.isUploading = false;
        this.$message.error('图片大小不能超过2MB');
        return false;
      }
      return true;
    },

    /** 处理相册上传成功 */
    handleAlbumSuccess(response, file, fileList) {
      if (response.code === 200) {
        file.url = this.getFullImgUrl(response.data);
        this.form.url = fileList.map(f => f.url.replace(this.baseUrl, '')).join(',');
      } else {
        this.$message.error('上传失败：' + response.msg);
      }
    },

    /** 相册图片删除 */
    handleAlbumRemove(file, fileList) {
      this.form.url = fileList.map(f => f.url.replace(this.baseUrl, '')).join(',');
    },

    /** 上传数量超限 */
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传6张图片`);
    },

    /** 相册上传前校验 */
    beforeAlbumUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('只能上传JPG/PNG格式的图片');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB');
        return false;
      }
      return true;
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 表单重置 */
    reset() {
      this.form = {
        userId: null,
        teacherName: null,
        avatarImg: null,
        context: null,
        url: null,
        releases: "0"
      };
      this.resetForm("form");
      if (this.editor) {
        this.editor.txt.clear();
      }
      this.albumFileList = [];
      this.isUploading = false;
    },

    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置搜索 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },

    /** 选择变化 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      console.log(this.ids);
    },

    /** 新增 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加教练信息";
    },

    /** 修改 */
    handleUpdate(row) {
      this.reset();
      const userId = row?.userId || this.ids[0];
      if (!userId) {
        this.$message.warning('请选择一条记录进行修改');
        return;
      }
      getTeacher(userId).then(response => {
        this.form = { ...response.data };
        this.form.releases = String(this.form.releases || "0");

        // 富文本回显 - 修复空图片路径问题
       // if (this.editor && this.form.context) {
       //    let processedHtml = this.form.context;
       //    // 修复可能存在的空路径
       //    processedHtml = processedHtml.replace(/<img src=""/g, `<img src="${this.baseUrl}/"`);
       //    processedHtml = processedHtml.replace(/<img/g, '<img style="max-width:100%;height:auto;"');
       //    this.editor.txt.html(processedHtml);
       //    this.form.context = processedHtml; // 同步到表单
       //    console.log(1)
       //    console.log(this.form.context)
       //
       // }
        this.$nextTick(() => {
          setTimeout(() => {
            if (this.editor && this.form.context) {
              const processedHtml = this.form.context.replace(
                /<img/g,
                '<img style="max-width:100%;height:auto;"'
              );
              this.editor.txt.html(processedHtml);
            }
          }, 500); // 给 editor 创建留出时间
        });
       // this.form.context = this.form.context || '' // ✅ 解决第一次编辑时富文本为空

        // 相册回显
        if (this.form.url) {
          this.albumFileList = this.splitImages(this.form.url).map(url => ({
            url: this.getFullImgUrl(url),
            name: 'album-img',
            status: 'success'
          }));
        }

        this.$nextTick(() => {
          this.form.avatarImg = this.form.avatarImg;
        });

        this.open = true;
        this.title = "修改教练信息";
      }).catch(() => {
        this.$message.error('获取数据失败');
      });
    },

    /** 提交表单 */
    submitForm() {
      // 强制同步富文本内容并校验
      if (this.editor) {
        console.log(this.form.context);
        const html = this.editor.txt.html();
        console.log(html);
        // 检查是否存在空图片路径
        if (html.includes('<img') && html.includes('src=""')) {
          this.$message.error('存在无效图片，请重新上传');
          return;
        }
        this.form.context = html;
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitFunc = this.title !== '添加教练信息' ? updateTeacher : addTeacher;
          submitFunc(this.form).then(() => {
            this.$modal.msgSuccess(this.form.userId ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          }).catch(() => {
            this.$modal.msgError(this.form.userId ? "修改失败" : "新增失败");
          });
        }
      });
    },

    handleDelete(row) {
      let userIds = [];
      if (row && row.userId !== undefined) {

        userIds = [row.userId]; // 单条删除：[1]
      } else {
        userIds = this.ids; // 批量删除：[1,2,3]
      }
      console.log(row)
      console.log(userIds)
      console.log(this.ids)
      if (userIds.length === 0) {
        this.$message.warning('请选择至少一条记录进行删除');
        return;
      }

      this.$modal.confirm(`是否确认删除选中的教练信息？`).then(() => {
        // 关键：直接传递数组，而非包装在{ids: ...}中
        console.log(userIds)
        return delTeacher(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 处理图片URL */
    getFullImgUrl(url) {
      if (!url || typeof url !== 'string') return '';
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      return this.baseUrl + (this.baseUrl.endsWith('/') ? '' : '/') + url;
    }
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy();
      this.editor = null;
    }
  }
};
</script>

<style scoped>
/* 相册样式 */
.album-images {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.album-img {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
}

.more-count {
  width: 60px;
  height: 60px;
  background: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #666;
  border: 1px solid #eee;
}

.no-image {
  color: #999;
  font-size: 14px;
}

/* 富文本样式 */
.editor-container {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 5px;
}

.editor-container img {
  max-width: 100% !important;
  height: auto !important;
}

/* 查看内容样式 */
.content-viewer {
  line-height: 1.8;
  word-break: break-all;
  padding: 15px;
  max-height: 600px;
  overflow-y: auto;
}

.content-viewer img {
  max-width: 100% !important;
  height: auto !important;
  margin: 10px auto !important;
  display: block !important;
}

/* 头像上传样式 */
.avatar-uploader {
  position: relative;
  display: inline-block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

/* 图片错误样式 */
.image-error {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #8c939d;
}
</style>
