<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="账号名称" prop="accountName">
        <el-input
          v-model="queryParams.accountName"
          placeholder="请输入账号名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="广告商" prop="advertiserId">
        <el-select v-model="queryParams.advertiserId" placeholder="请选择广告商" clearable size="small" filterable>
          <el-option
            v-for="item in advertiserOptions"
            :key="item.id"
            :label="item.advertiserName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" 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
          plain
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          plain
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="accountList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="推广账户名称" align="center" prop="accountName" show-overflow-tooltip />
      <el-table-column label="广告商名称" align="center" prop="advertiserName" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改自定义推广账号对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="广告商" prop="advertiserId">
          <el-select 
            v-model="form.advertiserId" 
            placeholder="请选择广告商" 
            style="width: 100%" 
            filterable
            @change="handleAdvertiserChange"
            :disabled="isEdit"
          >
            <el-option
              v-for="item in advertiserOptions"
              :key="item.id"
              :label="item.advertiserName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="推广账号名称" prop="accountName">
          <el-input 
            v-model="form.accountName" 
            placeholder="请输入推广账号名称"
            clearable
            :disabled="isEdit"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pagePromotionAccount, getPromotionAccount, addPromotionAccount, updatePromotionAccount, delPromotionAccount, batchDelPromotionAccount } from "@/api/adv/promotionAccount";
import { pageAdvertiser } from "@/api/adv/advertiser";

export default {
  name: "CustomPromotionAccount",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 推广账号表格数据
      accountList: [],
      // 广告商选项
      advertiserOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为编辑模式
      isEdit: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        custom: 2,
        accountName: undefined,
        advertiserId: undefined
      },
      // 表单参数
      form: {

      },
      // 表单校验
      rules: {
        advertiserId: [
          { required: true, message: "请选择广告商", trigger: "change" }
        ],
        accountName: [
          { required: true, message: "推广账号名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询广告商选项（只加载自定义广告商custom=2） */
    getAdvertiserOptions() {
      pageAdvertiser({ pageNum: 1, pageSize: 1000, enabled: 1, custom: 2 }).then(response => {
        this.advertiserOptions = response.data.records;
      });
    },
    /** 查询推广账号列表 */
    getList() {
      this.loading = true;
      pagePromotionAccount(this.queryParams).then(response => {
        this.accountList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        promotionType: "展示类",
        advertiserId: undefined,
        advertiserName: undefined,
        configMode: 1,
        accountName: undefined,
        accountShortName: undefined,
        apiSwitch: 2,
        custom: 2,
        appId: undefined,
        appSecret: undefined,
        adAccountId: undefined,
        callbackUrl: undefined,
        authUrl: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 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.isEdit = false;
      // 新增时加载广告商列表（只加载自定义广告商custom=2）
      this.getAdvertiserOptions();
      this.open = true;
      this.title = "添加自定义推广账号";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEdit = true;
      const id = row.id || this.ids[0];
      getPromotionAccount(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改自定义推广账号";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updatePromotionAccount(this.form.id, this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addPromotionAccount(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids;
      this.$confirm('是否确认删除选中的推广账号?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return batchDelPromotionAccount(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function() {});
    },
    /** 广告商变化时 */
    handleAdvertiserChange(advertiserId) {
      this.form.advertiserName = "";
      if (advertiserId) {
        const advertiser = this.advertiserOptions.find(item => item.id === advertiserId);
        if (advertiser) {
          this.form.advertiserName = advertiser.advertiserName;
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
