<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="编号" prop="no">
        <el-input
          v-model="queryParams.no"
          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="['ad:html: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="['ad:html: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="['ad:html: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="['ad:html:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="htmlList" @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="name" />
      <el-table-column label="描述" align="center" prop="remark" />
      <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="['ad:html:edit']"
          >修改</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" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="编辑页面">
          <el-button type="primary" @click="openH5(form.json)">
            编辑页面
          </el-button>
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input type="textarea" :row="5" v-model="form.remark" />
        </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="h5Open" append-to-body fullscreen>
        <H5Editor ref="h5Editor" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="h5Ok">确 定</el-button>
        <el-button @click="h5Cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改广告信息流链接对话框 -->
    <el-dialog title="生成链接" :visible.sync="openUrl" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="链接类型" prop="type">
          <el-radio v-model="urlForm.type" v-for="item in typeList" :key="item.type" :label="item.type" @change="accountChange">{{item.name}}</el-radio>
        </el-form-item>
        <el-form-item label="账号" prop="accountId">
          <el-select v-model="urlForm.accountId" filterable>
            <el-option v-for="item in accountList" :value="item.id" :key="item.id" :label="item.accountName" />
          </el-select>
        </el-form-item>
        <el-form-item label="链接" prop="type" v-if="this.urlForm.url">
          <a class="a" :href="this.urlForm.url" target="_blank">{{this.urlForm.url}}</a>
          <el-tooltip class="item" effect="dark" content="复制链接" placement="top">
            <i style="margin-left: 10px;cursor: pointer;color: #1890ff" class="el-icon-copy-document" @click="copyUrl"></i>
          </el-tooltip>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="urlOk">生成</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHtml, getHtml, delHtml, addHtml, updateHtml, exportHtml } from "@/api/ad/htmlTemplate";
import { listAll as bdAccountListAll } from "@/api/baidu/BdAccount";
import { listAll as youkuAccountListAll } from "@/api/ad/AdYouKuaccount.js";
import { listAll as iqiyiAccountListAll } from "@/api/ad/AdIqiyiAccount.js";

export default {
  name: "Html",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      accountList: [],
      typeList: [{type: 0,name: "百度"}, {type: 1,name: "优酷"}, {type: 2,name: "爱奇艺"}],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      h5Open: false,
      // 总条数
      total: 0,
      // 广告信息流链接表格数据
      htmlList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openUrl: false,
      urlForm: {
        type: 0,
        accountId: null,
        url: null,
      },
      dataJSON: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        no: null,
        images: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    openH5(){
      this.h5Open = true;
      this.$nextTick(() => {
        this.$refs.h5Editor.initData(this.form.json || "[]");
      });
    },
    h5Ok(){
      // 通过ref获取子组件的list数据
      const listData = this.$refs.h5Editor.list;
      this.form.json = JSON.stringify(listData);
      this.h5Open = false; // 关闭对话框
    },
    h5Cancel(){
      this.h5Open = false;
    },
    copyUrl(){
      navigator.clipboard.writeText(this.urlForm.url)
        .then(() => {
          this.msgSuccess("复制成功");
        })
        .catch(err => {
          this.msgError("复制失败");
        });
    },
    urlOk(){
      if(!this.form.url){
        this.msgError("推广页面信息错误，请联系管理员！");
        return;
      }
      if(this.urlForm.type == null || this.urlForm.type == undefined){
        this.msgError("链接类型不能为空");
        return;
      }
      if(!this.urlForm.accountId){
        this.msgError("账号ID不能为空");
        return;
      }
      this.urlForm.url = this.form.url + "&type=" + this.urlForm.type + "&accountId=" + this.urlForm.accountId;
    },
    accountChange(){
      let type = this.urlForm.type;
      this.urlForm.accountId = undefined;
      this.urlForm.url = undefined;
      if(type == 0){
        bdAccountListAll({}).then(res => {
          this.accountList = res.data;
        })
      }
      if(type == 1){
        youkuAccountListAll().then(res => {
          this.accountList = res.data;
        })
      }
      if(type == 2){
        iqiyiAccountListAll().then(res => {
          this.accountList = res.data;
        })
      }
    },
    openUrlFun(row){
      getHtml(row.id).then(response => {
        this.form = response.data;
        if(this.form.dataJson){
          this.dataJSON = JSON.parse(this.form.dataJson)
        }
        this.urlForm = {
          type: 0,
          accountId: null,
          url: null,
        };
        this.accountChange();
        this.openUrl = true;
      });
    },
    /** 查询广告信息流链接列表 */
    getList() {
      this.loading = true;
      listHtml(this.queryParams).then(response => {
        this.htmlList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.dataJSON = {};
      this.form = {
        id: null,
        no: null,
        images: null,
        createTime: null,
        createBy: null,
        updateBy: null,
        dataJSON: "",
        updateTime: 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.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加广告信息流链接";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHtml(id).then(response => {
        this.form = response.data;
        if(this.form.dataJson){
          this.dataJSON = JSON.parse(this.form.dataJson)
        }
        this.open = true;
        this.title = "修改广告信息流链接";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.dataJSON){
            this.form.dataJson = JSON.stringify(this.dataJSON);
          }
          if (this.form.id != null) {
            updateHtml(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHtml(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除广告信息流链接编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delHtml(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有广告信息流链接数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportHtml(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style>
.a{
  text-decoration: underline;
}
.a:hover{
  text-decoration: underline;
}
</style>
