<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="ID" align="center" prop="id" width="80" />
      <el-table-column label="账户简称" align="center" prop="accountShortName" width="150" show-overflow-tooltip />
      <el-table-column label="广告商名称" align="center" prop="advertiserName" width="150" show-overflow-tooltip />
      <el-table-column label="读取方式" align="center" prop="apiSwitch" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.apiSwitch === 1 ? 'success' : 'info'" size="small">
            {{ scope.row.apiSwitch === 1 ? 'API读取' : '手动录入' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="广告主ID" align="center" prop="adAccountId" width="180" 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="680px" append-to-body class="promotion-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px" class="elegant-form">
        <!-- 基础信息 -->
        <div class="form-section">
          <div class="section-title">
            <i class="el-icon-info"></i>
            <span>基础信息</span>
          </div>
          <el-form-item label="推广方式" prop="promotionType">
            <el-input v-model="form.promotionType" disabled placeholder="展示类" />
          </el-form-item>
          <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="configMode">
            <el-radio-group v-model="form.configMode">
              <el-radio :label="1" :border="true">服务模式</el-radio>
              <el-radio :label="2" :border="true">广告主模式</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <!-- 账号信息 -->
        <div class="form-section">
          <div class="section-title">
            <i class="el-icon-user"></i>
            <span>账号信息</span>
          </div>
          <el-form-item label="推广账号名称" prop="accountName">
            <el-input 
              v-model="form.accountName" 
              placeholder="请输入推广账号名称"
              prefix-icon="el-icon-user-solid"
              clearable
              :disabled="isEdit"
            />
          </el-form-item>
          <el-form-item label="推广账户简称" prop="accountShortName">
            <el-input 
              v-model="form.accountShortName" 
              placeholder="请输入推广账户简称"
              prefix-icon="el-icon-tickets"
              clearable
            />
          </el-form-item>
        </div>

        <!-- API配置 -->
        <div class="form-section">
          <div class="section-title">
            <i class="el-icon-setting"></i>
            <span>API配置</span>
          </div>
          <el-form-item label="API读取账号信息" prop="apiSwitch">
            <el-radio-group v-model="form.apiSwitch">
              <el-radio :label="1" :border="true">开</el-radio>
              <el-radio :label="2" :border="true">关</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <template v-if="form.apiSwitch === 1">
            <el-form-item label="AppID" prop="appId" class="slide-fade">
              <el-input 
                v-model="form.appId" 
                placeholder="请输入AppID"
                prefix-icon="el-icon-key"
                clearable
              />
            </el-form-item>
            <el-form-item label="Secret Key" prop="appSecret" class="slide-fade">
              <el-input 
                v-model="form.appSecret" 
                placeholder="请输入Secret Key"
                prefix-icon="el-icon-lock"
                type="password"
                show-password
                clearable
              />
            </el-form-item>
            <el-form-item label="广告主id" prop="adAccountId" class="slide-fade">
              <el-input 
                v-model="form.adAccountId" 
                placeholder="请输入广告主id"
                prefix-icon="el-icon-postcard"
                clearable
              />
            </el-form-item>
            <el-form-item label="回调地址" prop="callbackUrl" class="slide-fade">
              <el-input 
                v-model="form.callbackUrl" 
                placeholder="请输入回调地址"
                prefix-icon="el-icon-link"
                clearable
              />
            </el-form-item>
            <el-form-item label="应用授权链接" prop="authUrl" class="slide-fade">
              <el-input 
                v-model="form.authUrl" 
                placeholder="请输入应用授权链接"
                prefix-icon="el-icon-connection"
                clearable
              />
            </el-form-item>
          </template>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" icon="el-icon-check">确 定</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: "PromotionAccount",
  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,
        accountName: undefined,
        advertiserId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        promotionType: [
          { required: true, message: "推广方式不能为空", trigger: "blur" }
        ],
        advertiserId: [
          { required: true, message: "请选择广告商", trigger: "change" }
        ],
        configMode: [
          { required: true, message: "请选择配置方式", trigger: "change" }
        ],
        accountName: [
          { required: true, message: "推广账号名称不能为空", trigger: "blur" }
        ],
        accountShortName: [
          { required: true, message: "推广账户简称不能为空", trigger: "blur" }
        ],
        apiSwitch: [
          { required: true, message: "请选择API读取账号信息", trigger: "change" }
        ],
        appId: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.apiSwitch === 1 && !value) {
                callback(new Error('请输入AppID'));
              } else {
                callback();
              }
            }, 
            trigger: "blur" 
          }
        ],
        appSecret: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.apiSwitch === 1 && !value) {
                callback(new Error('请输入Secret Key'));
              } else {
                callback();
              }
            }, 
            trigger: "blur" 
          }
        ],
        adAccountId: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.apiSwitch === 1 && !value) {
                callback(new Error('请输入广告主id'));
              } else {
                callback();
              }
            }, 
            trigger: "blur" 
          }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getAdvertiserOptions();
  },
  methods: {
    /** 查询广告商选项 */
    getAdvertiserOptions() {
      pageAdvertiser({ pageNum: 1, pageSize: 1000 }).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,
        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;
      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>
// 对话框样式
::v-deep .promotion-dialog {
  .el-dialog__header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 20px;
    margin: 0;
    border-radius: 4px 4px 0 0;
    
    .el-dialog__title {
      color: #fff;
      font-size: 18px;
      font-weight: 500;
    }
    
    .el-dialog__headerbtn .el-dialog__close {
      color: #fff;
      font-size: 20px;
      
      &:hover {
        color: #f0f0f0;
      }
    }
  }
  
  .el-dialog__body {
    padding: 25px 30px;
    background-color: #f8f9fa;
    max-height: 70vh;
    overflow-y: auto;
  }
  
  .el-dialog__footer {
    padding: 15px 30px;
    border-top: 1px solid #e8e8e8;
    background-color: #fff;
  }
}

// 表单样式
.elegant-form {
  .form-section {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
      transform: translateY(-2px);
    }
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 2px solid #e8e8e8;
    font-size: 15px;
    font-weight: 600;
    color: #303133;
    
    i {
      font-size: 18px;
      margin-right: 8px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
    
    span {
      position: relative;
      
      &::after {
        content: '';
        position: absolute;
        left: 0;
        bottom: -12px;
        width: 0;
        height: 2px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        transition: width 0.3s ease;
      }
    }
  }
  
  .form-section:hover .section-title span::after {
    width: 100%;
  }
  
  .el-form-item {
    margin-bottom: 20px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  ::v-deep .el-form-item__label {
    color: #606266;
    font-weight: 500;
    font-size: 14px;
  }
  
  ::v-deep .el-input__inner,
  ::v-deep .el-textarea__inner {
    border-radius: 6px;
    border: 1px solid #dcdfe6;
    transition: all 0.3s ease;
    
    &:hover {
      border-color: #c0c4cc;
    }
    
    &:focus {
      border-color: #667eea;
      box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
    }
    
    &:disabled {
      background-color: #f5f7fa;
      color: #909399;
    }
  }
  
  ::v-deep .el-radio {
    margin-right: 20px;
    
    &.is-bordered {
      border-radius: 6px;
      padding: 10px 20px;
      transition: all 0.3s ease;
      
      &:hover {
        border-color: #667eea;
      }
      
      &.is-checked {
        border-color: #667eea;
        background-color: rgba(102, 126, 234, 0.05);
      }
    }
  }
  
  // API字段显示动画
  .slide-fade {
    animation: slideDown 0.3s ease;
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 按钮样式
.dialog-footer {
  text-align: right;
  
  .el-button {
    padding: 10px 24px;
    border-radius: 6px;
    font-weight: 500;
    transition: all 0.3s ease;
    
    &.el-button--primary {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
      }
      
      &:active {
        transform: translateY(0);
      }
    }
    
    &.el-button--default {
      &:hover {
        color: #667eea;
        border-color: #667eea;
        background-color: rgba(102, 126, 234, 0.05);
      }
    }
  }
}
</style>

