<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="广告位置" prop="advType">
        <el-select v-model="queryParams.advType" placeholder="请选择广告位置" clearable size="small">
          <el-option
                v-for="item in advTypeOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
        </el-select>
      </el-form-item>
      <el-form-item label="显示类型" prop="showType">
        <el-select v-model="queryParams.showType" placeholder="请选择显示类型" clearable size="small">
           <el-option
                v-for="item in showTypeOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
        </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="['store:adv: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="['store:adv: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="['store:adv:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table  height="500" border v-loading="loading" :data="advList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="advId" />
      <el-table-column label="广告标题" align="center" prop="advTitle" />
      <el-table-column label="广告图片" align="center" width="120">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover"
          >
            <img slot="reference" :src="scope.row.imageUrl" width="100">
            <img :src="scope.row.imageUrl" style="max-width: 150px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="URL地址" show-overflow-tooltip align="center" prop="advUrl" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column  label="广告位置" align="center" prop="advType">
        <template slot-scope="scope">
            <el-tag prop="advType" v-for="(item, index) in advTypeOptions"    v-if="scope.row.advType==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column  label="显示方式" align="center" prop="showType">
        <template slot-scope="scope">
             <el-tag prop="showType" v-for="(item, index) in showTypeOptions"    v-if="scope.row.showType==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column  label="状态" align="center" prop="status">
        <template slot-scope="scope">
            <el-tag prop="status" v-for="(item, index) in statusOptions"    v-if="scope.row.status==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"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['store:adv:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['store:adv: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="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="广告标题" prop="advTitle">
          <el-input v-model="form.advTitle" placeholder="请输入广告标题" />
        </el-form-item>
        <el-form-item label="展示类型" prop="urlType">
          <el-radio-group v-model="form.urlType">
            <el-radio :label="1">图片</el-radio>
            <el-radio :label="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>
         <el-form-item label="广告图片" prop="imageUrl" v-if="form.urlType==1">
            <el-upload
              v-model="form.icon"
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
        <el-form-item label="广告视频" prop="video" v-if="form.urlType==2">
          <div>
            <el-upload
              ref="upload"
              class="upload-demo"
              :action="uploadUrl"
              :on-success="handleSuccess"
              :before-upload="beforeUpload"
              :limit="1"
              :accept="videoAccept"
            >
              <el-button size="small" type="primary">点击上传视频</el-button>
            </el-upload>
            <video v-if="form.imageUrl" :src="form.imageUrl" controls style="max-width: 300px; max-height: 300px; margin-top: 10px"></video>
          </div>
        </el-form-item>

        <el-form-item label="广告位置" prop="advType">
          <el-radio-group v-model="form.advType">
            <el-radio :label="item.dictValue" v-for="item in advTypeOptions" >{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示方式" prop="showType" v-if="form.urlType==1">
          <el-radio-group @change="showTypeChange" v-model="form.showType">
            <el-radio :label="item.dictValue" v-for="item in showTypeOptions" >{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公众号链接" prop="advUrl" v-if="form.showType==1 && form.urlType==1 " >
          <el-input v-model="form.advUrl" placeholder="请输入公众号链接" />
        </el-form-item>
        <el-form-item label="小程序地址" prop="advUrl" v-if="form.showType==2 && form.urlType==1 ">
          <el-input v-model="form.advUrl" placeholder="请输入小程序地址" />
        </el-form-item>
        <el-form-item label="文章内容" v-if="form.showType==3 && form.urlType==1 ">
          <editor ref="myeditor" @on-text-change="updateText" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="item.dictValue" v-for="item in statusOptions" >{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
           <el-input-number v-model="form.sort"  :min="1" :max="99" ></el-input-number>
        </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 { listAdv, getAdv, delAdv, addAdv, updateAdv, exportAdv } from "@/api/hisStore/adv";
import Editor from '@/components/Editor/wang';
export default {
  name: "Adv",
  components: {
    Editor
  },
  data() {
    return {
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      baseUrl: process.env.VUE_APP_BASE_API,
      videoAccept:"video/*",
      statusOptions:[],
      advTypeOptions:[],
      showTypeOptions:[],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 广告表格数据
      advList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        advTitle: null,
        imageUrl: null,
        advUrl: null,
        content: null,
        status: null,
        sort: null,
        advType: null,
        showType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        advTitle: [
          { required: true, message: "广告标题不能为空", trigger: "blur" }
        ],
        imageUrl: [
          { required: true, message: "广告图不能为空", trigger: "blur" }
        ],

      }
    };
  },
  created() {
    this.getDicts("common_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_adv_type").then((response) => {
      this.advTypeOptions = response.data;
    });
    this.getDicts("sys_adv_show").then((response) => {
      this.showTypeOptions = response.data;
    });
    this.getList();
  },
  methods: {
    handleSuccess(response, file) {
      // 上传成功后的回调函数
      this.myloading.close();
      this.form.imageUrl = response.url;
      this.$refs.upload.clearFiles();
    },
    beforeUpload(file) {
      // 上传前的钩子函数，可以在这里对文件进行处理
      // 返回 false 则取消上传

      // 例如限制文件大小
      const isLt2M = file.size / 1024 / 1024 < 200;
      if (!isLt2M) {
        this.$message.error('上传视频文件大小不能超过 200MB!');
        return false;
      }
      this.myloading = this.$loading({
        lock: true,
        text: '上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

    },
    showTypeChange(e){
      console.log(e)
      if(e==3){
        setTimeout(() => {
          this.$refs.myeditor.setText("");
        }, 200);
      }
    },
    updateText(text){
      this.form.content=text
    },
    handleAvatarSuccess(res, file) {
        if(res.code==200){
          this.form.imageUrl=res.url;
        }
        else{
          this.msgError(res.msg);
        }

    },
    beforeAvatarUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 200;
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 200MB!');
      }
      return   isLt1M;
    },
    /** 查询广告列表 */
    getList() {
      this.loading = true;
      listAdv(this.queryParams).then(response => {
        this.advList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        advId: null,
        urlType:1,
        advTitle: null,
        imageUrl: null,
        advUrl: null,
        content: null,
        createTime: null,
        updateTime: null,
        status: "1",
        sort: null,
        advType: null,
        showType: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.advId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加广告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const advId = row.advId || this.ids
      var that=this;
      getAdv(advId).then(response => {
        this.form = response.data;
        this.form.status = response.data.status.toString();
        this.form.advType = response.data.advType.toString();
        this.form.showType = response.data.showType ? response.data.showType.toString() : "";
        // 根据 imageUrl 判断 urlType
        if (this.form.imageUrl) {
          // 可以根据文件扩展名判断是图片还是视频
          const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
          const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv'];

          const lowerImageUrl = this.form.imageUrl.toLowerCase();
          let isImage = imageExtensions.some(ext => lowerImageUrl.includes(ext));
          let isVideo = videoExtensions.some(ext => lowerImageUrl.includes(ext));

          if (isImage) {
            this.form.urlType = 1; // 图片
          } else if (isVideo) {
            this.form.urlType = 2; // 视频
          } else {
            this.form.urlType = 1; // 默认图片
          }
        } else {
          this.form.urlType = 1; // 默认图片
        }
        console.log('urlType:', this.form.urlType, typeof this.form.urlType);
        this.open = true;
        this.title = "修改广告";
        setTimeout(() => {
          if(this.form.showType=="3"){
            console.log(that.form.content)
            if(this.form.content==null){
                that.$refs.myeditor.setText("");
            }
            else{
                that.$refs.myeditor.setText(that.form.content);
            }
          }
        }, 200);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.advId != null) {
            updateAdv(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAdv(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const advIds = row.advId || this.ids;
      this.$confirm('是否确认删除广告编号为"' + advIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAdv(advIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有广告数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportAdv(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style >
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
</style>
<style scoped>

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


</style>

