<template>
  <div>
  <div class="app-container">
    <el-alert
      title="注意事项"
      type="warning"
      description="因企业微信接口限制，1、在【企业微信后台】群欢迎语素材库进行新增/编辑/删除操作，后台不会同步更新，建议在后台入群欢迎语处进行管理。
       2、 注意：企业微信入群欢迎语素材库中，最多容纳100个素材，包括后台管理的以及企业微信后台管理的。
       3、除图片外，其他附件素材均只有三天时效，若要续用，请点击修改-》直接点击-确认后，刷新时效"
      :closable="false"
      center
      show-icon>
    </el-alert>
  </div>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" >
      <el-form-item label="企微公司" prop="corpId">
            <el-select v-model="queryParams.corpId" placeholder="企微公司"  size="small" @change="updateCorpId()">
              <el-option
                v-for="dict in myQwCompanyList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
       </el-form-item>
      <el-form-item label="消息内容" prop="createName">
        <el-input
          v-model="queryParams.textContent"
          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-item>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            size="mini"
            icon="el-icon-plus"
            @click="handleAdd"
            v-hasPermi="['qw:welcome:add']"
          >新增</el-button>
        </el-col>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="welcomeList" border>
      <el-table-column label="欢迎语类型" align="center" prop="welcomeType" >
        <template slot-scope="scope">
          <span   v-for="(item, index) in welcomeTypeOptions"    v-if="scope.row.welcomeType==item.dictValue">{{item.dictLabel}}</span>
        </template>
      </el-table-column>
      <el-table-column label="欢迎消息文本" align="left" width="600px" >
        <template slot-scope="scope">
          <div class="flex-container">
            <el-tooltip class="item" effect="dark" :content="scope.row.textContent" placement="top">
              <div style="display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; text-overflow: ellipsis;">
                <span>文本消息：</span>{{ scope.row.textContent }}
              </div>
            </el-tooltip>
            <div v-if="scope.row.welcomeType == '1'">
              <div style="float: left">
              <span>图片：</span>
              <el-image v-if="scope.row.imagePicUrl"
                style="width: 50px; height: 50px"
                :src="scope.row.imagePicUrl"
                fit="contain" />
                <span v-if="!scope.row.imagePicUrl">无图片</span>
              </div>
            </div>
            <div v-if="scope.row.welcomeType=='2'">
              <div style="float: left;margin-top: 10px">
                <el-tooltip class="item" effect="dark" :content="scope.row.linkTitle" placement="top">
                  <div style="float: left; overflow-y: hidden; height: 50px">
                    <span>图文标题：</span>{{ scope.row.linkTitle }}
                  </div>
                </el-tooltip>
                <div>
                  <el-image v-if="scope.row.linkPicurl"
                            style="width: 50px; height: 50px"
                            :src="scope.row.linkPicurl"
                            fit="contain" />
                </div>

              </div>
            </div>

            <div v-if="scope.row.welcomeType=='3'">
              <div style="float: left">
                <span>小程序标题：</span>{{scope.row.miniprogramTitle}}
                <div>
                  <el-image v-if="scope.row.miniprogramPicUrl"
                            style="width: 50px; height: 50px"
                            :src="scope.row.miniprogramPicUrl"
                            fit="contain" />
                </div>
              </div>
            </div>

            <div v-if="scope.row.welcomeType=='4'">
              <div style="float: left">
                <span>文件：</span>
                <span>请查看详情</span>
              </div>
            </div>

            <div v-if="scope.row.welcomeType=='5'">
              <div style="float: left">
                <span>视频：</span>
                <span>请查看详情</span>
              </div>
            </div>
          </div>
        </template>

      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createName" />
      <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"
            icon="el-icon-notebook-2"
            @click="hangdleDitels(scope.row)"
            v-hasPermi="['qw:welcome:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qw:welcome:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qw:welcome: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>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <div v-if="!form.welcomeId">
          <el-form-item label="欢迎语类型" prop="welcomeType">
              <el-radio-group v-model="form.welcomeType">
                <el-radio :label="item.dictValue" v-for="item in welcomeTypeOptions">{{item.dictLabel}}</el-radio>
              </el-radio-group>
          </el-form-item>
        </div>
        <el-form-item label="消息文本内容" prop="textContent">
          <el-input v-model="form.textContent" type="textarea" :rows="6" maxlength="1300" show-word-limit placeholder="请输入消息文本内容（图片,视频等附件不上传，则默认为纯文本欢迎语）" />
        </el-form-item>
        <div v-if="form.welcomeType=='1'">
          <el-form-item label="图片" prop="imagePicUrl">
            <ImageUpload v-model="form.imagePicUrl"  type="image" :num="10" :width="150" :height="150"  disabled/>
          </el-form-item>
        </div>
        <div v-if="form.welcomeType=='2'">
          <el-form-item label="图文标题" prop="linkTitle" required>
            <el-input v-model="form.linkTitle" type="textarea" :rows="2" maxlength="42" show-word-limit placeholder="请输入图文消息标题，最长为42字节" />
          </el-form-item>
          <el-form-item label="上传图文封面" prop="linkPicurl">
            <ImageUpload v-model="form.linkPicurl"  type="image" :num="10" :width="150" :height="150" />
          </el-form-item>
          <el-form-item label="图文的描述" prop="linkDesc">
            <el-input v-model="form.linkDesc" type="textarea" :rows="3" maxlength="170" show-word-limit placeholder="请输入内容,，最长为170字节" />
          </el-form-item>
          <el-form-item label="图文的链接" prop="linkUrl" required>
<!--            <ImageUpload v-model="form.linkUrl"   type="image" :num="10" :width="150" :height="150" />-->
            <el-input v-model="form.linkUrl" placeholder="请输入图文的URL链接" />
          </el-form-item>
        </div>

        <div v-if="form.welcomeType=='3'">
          <el-form-item label="小程序标题" prop="miniprogramTitle">
            <el-input v-model="form.miniprogramTitle" type="textarea" maxlength="21" show-word-limit placeholder="请输入小程序消息标题，最长为21字节"  />
          </el-form-item>
          <el-form-item label="上传小程序封面" prop="miniprogramPicUrl">
            <ImageUpload v-model="form.miniprogramPicUrl"  type="image" :num="10" :width="150" :height="150" />
          </el-form-item>
          <el-form-item label="小程序appid" prop="miniprogramAppid">
            <el-input v-model="form.miniprogramAppid" placeholder="请输入小程序appid，必须是关联到企业的小程序应用" />
          </el-form-item>
          <el-form-item label="小程序page路径" prop="miniprogramPage">
            <el-input v-model="form.miniprogramPage" placeholder="请输入小程序page路径" />
          </el-form-item>
        </div>

        <div v-if="form.welcomeType=='4'">
          <el-form-item label="上传文件" prop="fileUrl">
            <el-upload v-if="form.fileUrl==null || form.welcomeId"
                       v-model="form.fileUrl"
                       class="avatar-uploader"
                       :action="uploadUrl"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccessFile"
                       :before-upload="beforeAvatarUploadFile">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <el-link v-if="form.fileUrl" type="primary" :href="downloadUrl(form.fileUrl)" download>
              {{form.fileUrl}}
            </el-link>
          </el-form-item>
        </div>

        <div v-if="form.welcomeType=='5'">
          <el-form-item label="上传视频" prop="videoUrl">
            <el-upload v-if="form.videoUrl==null || form.welcomeId"
                       v-model="form.videoUrl"
                       class="avatar-uploader"
                       :action="uploadUrl"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccessVideo"
                       :before-upload="beforeAvatarUploadVideo">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <video v-if="form.videoUrl"
                   :src="form.videoUrl"
                   controls style="width: 200px;height: 100px">
            </video>
          </el-form-item>
        </div>
        <div v-if="!form.welcomeId">
          <el-form-item label="是否通知成员" prop="notify">
            <el-radio-group v-model="form.notify">
              <el-radio :label="item.dictValue" v-for="item in sysNoticeStatus">{{item.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

      </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
      :visible.sync="dialogVisible"
      :modal="false"
      width="1200"
      append-to-body>
      <img
        :src="this.dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>

    <!--详情    -->
  <el-drawer :title="details.title" :visible.sync="details.open" size="45%" append-to-body>
      <el-card style="background-color:  rgb(240 242 245)">
        <el-descriptions :column="1" border  :labelStyle="{width: '130px'}" >
          <el-descriptions-item label="欢迎语企微id:">
            <span>{{form.templateId}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="消息文本内容:">
            <span class="custom-span">{{form.textContent}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="图片" v-if="form.welcomeType=='1'">
            <el-image
              v-if="form.imagePicUrl"
              style="width: 100px; height: 100px"
              :src="form.imagePicUrl"
              fit="contain"
              @click="openImageViewer(form.imagePicUrl)"/>
          </el-descriptions-item>
          <el-descriptions-item label="图文标题:" v-if="form.welcomeType=='2'">
            <span class="custom-span-title">{{form.linkTitle}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="图文封面:" v-if="form.welcomeType=='2'">
            <el-image
              v-if="form.linkPicurl"
              style="width: 100px; height: 100px"
              :src="form.linkPicurl"
              fit="contain"
              @click="openImageViewer(form.linkPicurl)"/>
          </el-descriptions-item>
          <el-descriptions-item label="图文的描述:" v-if="form.welcomeType=='2'">
            <span class="custom-span">{{form.linkDesc}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="图文的链接:" v-if="form.welcomeType=='2'">
            <el-link>{{form.linkUrl}}</el-link>
<!--            <el-image-->
<!--              v-if="form.linkUrl"-->
<!--              style="width: 100px; height: 100px"-->
<!--              :src="form.linkUrl"-->
<!--              fit="contain"-->
<!--              @click="openImageViewer(form.linkUrl)"/>-->
          </el-descriptions-item>
          <el-descriptions-item label="小程序标题:" v-if="form.welcomeType=='3'">{{form.miniprogramTitle}}</el-descriptions-item>
          <el-descriptions-item label="小程序封面:" v-if="form.welcomeType=='3'">
            <el-image
              v-if="form.miniprogramPicUrl"
              style="width: 100px; height: 100px"
              :src="form.miniprogramPicUrl"
              fit="contain"
              @click="openImageViewer(form.miniprogramPicUrl)"/>
          </el-descriptions-item>
          <el-descriptions-item label="小程序appid:" v-if="form.welcomeType=='3'">{{form.miniprogramAppid}}</el-descriptions-item>
          <el-descriptions-item label="小程序page路径:" v-if="form.welcomeType=='3'">{{form.miniprogramPage}}</el-descriptions-item>
          <el-descriptions-item label="企微临时文件mediaId:" v-if="form.welcomeType=='4'">{{form.fileMediaId}}</el-descriptions-item>
          <el-descriptions-item label="文件:" v-if="form.welcomeType=='4'">
            <el-link v-if="form.fileUrl" type="primary" :href="form.fileUrl" download>
              {{form.fileUrl}}
            </el-link>
          </el-descriptions-item>
          <el-descriptions-item label="视频临时文件mediaId:" v-if="form.welcomeType=='5'">{{form.videoMediaId}}</el-descriptions-item>
          <el-descriptions-item label="视频:" v-if="form.welcomeType=='5'">
            <video v-if="form.videoUrl"
                   :src="form.videoUrl"
                   controls style="width: 200px;height: 100px">
            </video>
          </el-descriptions-item>
          <el-descriptions-item label="是否通知成员:" >
            <!-- 使用 v-if 来筛选并显示匹配的项 -->
            <span v-if="findMatchingItem(sysNoticeStatus, form.notify)">
            {{ findMatchingItem(sysNoticeStatus, form.notify).dictLabel }}
          </span>
          </el-descriptions-item>
          <el-descriptions-item label="创建人:">{{form.createName}}</el-descriptions-item>

        </el-descriptions>
      </el-card>
  </el-drawer>


  </div>
</template>

<script>
import { listWelcome, getWelcome, delWelcome, addWelcome, updateWelcome, exportWelcome } from "@/api/qw/welcome";
import ImageUpload from "@/views/qw/material/ImageUpload";
import { getMyQwUserList,getMyQwCompanyList } from "@/api/qw/user";

export default {
  name: "myWelcome",
  components: {ImageUpload},

  data() {
    return {
      //上传地址
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      //放大图片
      dialogImageUrl:null,
      dialogVisible:false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      myQwCompanyList:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入群欢迎语管理表格数据
      welcomeList: [],
      //欢迎语类型
      welcomeTypeOptions:[],
      //通知类型
      sysNoticeStatus:[].map(item => {
          return { ...item, dictValue: parseInt(item.dictValue, 10) }; // 转换为整数
      }),
      formData:null,
      //文件1图片，文件，视频，音频，图文的封面
      FileOne:'',

      //文件2 用来存上传图文的图片
      FileTwo:'',

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      details:{
        title:"",
        open:false,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateId: null,
        welcomeType: null,
        textContent: null,
        imageMediaId: null,
        imagePicUrl: null,
        linkTitle: null,
        linkPicurl: null,
        linkDesc: null,
        linkUrl: null,
        miniprogramTitle: null,
        miniprogramPicMediaId: null,
        miniprogramPicUrl: null,
        miniprogramAppid: null,
        miniprogramPage: null,
        fileMediaId: null,
        videoMediaId: null,
        fileUrl: null,
        notify: null,
        corpId: null,
        videoUrl: null,
        companyId: null,
        createName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        welcomeType:[
          {required:true,message:"类型不能为空",trigger:"blur"}
        ],
        textContent:[
          {required:true,message:"消息文本不能为空",trigger:"blur"}
        ],
        linkUrl:[
          {required:true,message:"链接不能为空",trigger:"blur"}
        ]
      }
    };
  },
  created() {
    getMyQwCompanyList().then(response => {
            this.myQwCompanyList = response.data;
            if(this.myQwCompanyList!=null){
              this.queryParams.corpId=this.myQwCompanyList[0].dictValue
              this.getList();
            }
        });
    //文本类型字典
    this.getDicts("sys_qw_welcome_type").then(response => {
      this.welcomeTypeOptions = response.data;
    });

    this.getDicts("sys_company_status").then(response => {
      this.sysNoticeStatus = response.data;
    });

  },
  methods: {
    updateCorpId(){
           this.getList();
    },
    /** 查询入群欢迎语管理列表 */
    getList() {
      this.loading = true;
      listWelcome(this.queryParams).then(response => {
        this.welcomeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleAvatarSuccessFile(res, file) {
      if(res.code==200){
        this.form.fileUrl=res.url;
        // this.FileOne=file
        this.FileOne=file.raw
      }
      else{
        this.msgError(res.msg);
      }
    },
    handleAvatarSuccessVideo(res, file) {

      if(res.code==200){
        this.form.videoUrl=res.url;
        // this.self.$forceUpdate()
        this.FileOne=file.raw
      }
      else{
        this.msgError(res.msg);
      }
    },
    beforeAvatarUploadFile(file){
      const isLt1M = file.size / 1024 / 1024 < 10;
      if (!isLt1M) {
        this.$message.error('上传大小不能超过 10MB!');
      }
      return isLt1M;
    },
    beforeAvatarUploadVideo(file){
      const isLt1M = file.size / 1024 / 1024 < 10;
      if (!isLt1M) {
        this.$message.error('上传大小不能超过 10MB!');
      }
      return isLt1M;
    },
    openImageViewer(url) {
      // 打开大图预览对话框
      this.dialogImageUrl=url
      this.dialogVisible = true;
    },
    //下载文件
    downloadUrl(materialUrl) {
      // 直接返回文件 URL
      return materialUrl;
    },
    findMatchingItem(items, value) {
      // 遍历 items 数组以找到匹配项
      return items.find(item => item.dictValue == value) || null;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        welcomeId: null,
        templateId: null,
        welcomeType: null,
        textContent: null,
        imageMediaId: null,
        imagePicUrl: null,
        linkTitle: null,
        linkPicurl: null,
        linkDesc: null,
        linkUrl: null,
        miniprogramTitle: null,
        miniprogramPicMediaId: null,
        miniprogramPicUrl: null,
        miniprogramAppid: null,
        miniprogramPage: null,
        fileMediaId: null,
        fileUrl: null,
        videoMediaId: null,
        videoUrl: null,
        notify: null,
        corpId: null,
        companyId: null,
        updateTime: null,
        createTime: null,
        createName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.corpId= this.myQwCompanyList[0].dictValue
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.welcomeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.welcomeType="1"
      this.form.notify="1"
      this.title = "添加入群欢迎语";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const welcomeId = row.welcomeId || this.ids
      getWelcome(welcomeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改入群欢迎语";
      });
    },

    hangdleDitels(row){
      this.reset();
      const welcomeId = row.welcomeId || this.ids
      getWelcome(welcomeId).then(response => {
        this.form = response.data;
        this.details.open = true;
        this.details.title = "欢迎语详情";
      });
    },
    // async urlToFile(url) {
    //   const response = await fetch(url);
    //   const data = await response.blob();
    //   const filename = url.split('/').pop();
    //   return new File([data], filename, { type: data.type });
    // },

    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.corpId=this.queryParams.corpId;
          if (this.form.welcomeId != null) {
            updateWelcome(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWelcome(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const welcomeIds = row.welcomeId || this.ids;
      this.$confirm('是否确认删除入群欢迎语编号为"' + welcomeIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delWelcome(welcomeIds,row.templateId);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },

  }
};
</script>
<style scoped>
.flex-container {
  display: flex; /* 启用Flexbox布局 */
  flex-direction: column; /* 子元素垂直排列 */
  align-items: flex-start; /* 子元素在主轴上（水平）从左到右排列 */
}

.flex-container > div {
  width: 100%; /* 确保每个子div宽度充满容器宽度 */
}
.text-container {
  max-height: 8.5em; /* 设置最大高度为6行，根据字体大小调整 */
  overflow-y: auto; /* 内容超出时显示滚动条 */
  line-height: 1.5em; /* 行高设置，确保每行高度一致 */
}
.text-container-title{
  margin-top: 10px;
  max-height: 5em; /* 设置最大高度为6行，根据字体大小调整 */
  overflow-y: auto; /* 内容超出时显示滚动条 */
  line-height: 1.5em; /* 行高设置，确保每行高度一致 */
}
.custom-span {
  display: block; /* 确保元素是块级元素 */
  height: 150px; /* 设置固定高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
  word-wrap: break-word; /* 自动换行 */
  word-break: break-all; /* 在必要时进行换行 */
}
.custom-span-title {
  display: block; /* 确保元素是块级元素 */
  height: 45px; /* 设置固定高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
  word-wrap: break-word; /* 自动换行 */
  word-break: break-all; /* 在必要时进行换行 */
}
</style>
