<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="accountName" min-width="150" show-overflow-tooltip />
      <el-table-column label="广告商" align="center" prop="advertiserName" min-width="150" 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="300">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleConversionType(scope.row)"
          >添加转换类型</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-data"
            @click="handleConversionLog(scope.row)"
          >回传结果</el-button>
          <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="600px" 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"
          >
            <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="请输入账号名称" />
        </el-form-item>
        
        <!-- advertiserId = 1 的字段 -->
        <template v-if="form.advertiserId === 10001">
          <el-form-item label="ocpcUid" prop="adAccountId">
            <el-input v-model="form.adAccountId" placeholder="请输入ocpcUid" />
          </el-form-item>
          <el-form-item label="ocpcToken" prop="accessToken">
            <el-input v-model="form.accessToken" placeholder="请输入ocpcToken" type="password" show-password />
          </el-form-item>
        </template>
        
        <!-- advertiserId = 3 的字段 -->
        <template v-if="form.advertiserId === 10003">
          <el-form-item label="广告账户id" prop="adAccountId">
            <el-input v-model="form.adAccountId" placeholder="请输入广告账户id" />
          </el-form-item>
          <el-form-item label="数据源id" prop="scrId">
            <el-input v-model="form.scrId" placeholder="请输入数据源id" />
          </el-form-item>
          <el-form-item label="数据源token" prop="accessToken">
            <el-input v-model="form.accessToken" placeholder="请输入数据源token" type="password" show-password />
          </el-form-item>
        </template>
        
        <!-- advertiserId = 4 的字段 -->
        <template v-if="form.advertiserId === 10004">
          <el-form-item label="ownerId" prop="adAccountId">
            <el-input v-model="form.adAccountId" placeholder="请输入ownerId" />
          </el-form-item>
          <el-form-item label="apiId" prop="appId">
            <el-input v-model="form.appId" placeholder="请输入apiId" />
          </el-form-item>
          <el-form-item label="apiKey" prop="appSecret">
            <el-input v-model="form.appSecret" placeholder="请输入apiKey" type="password" show-password />
          </el-form-item>
        </template>
        
        <!-- advertiserId = 5 的字段 -->
        <template v-if="form.advertiserId === 10005">
          <el-form-item label="账户id" prop="adAccountId">
            <el-input v-model="form.adAccountId" placeholder="请输入账户id" />
          </el-form-item>
          <el-form-item label="应用id" prop="appId">
            <el-input v-model="form.appId" placeholder="请输入应用id" />
          </el-form-item>
          <el-form-item label="应用秘钥" prop="appSecret">
            <el-input v-model="form.appSecret" placeholder="请输入应用秘钥" type="password" show-password />
          </el-form-item>
          <el-form-item label="scr_id" prop="scrId">
            <el-input v-model="form.scrId" placeholder="请输入scr_id" />
          </el-form-item>
        </template>
      </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="conversionOpen" width="700px" append-to-body>
      <div style="margin-bottom: 15px;">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="addConversionEvent">添加事件</el-button>
      </div>
      
      <div v-if="conversionEvents.length === 0" style="text-align: center; padding: 40px 0; color: #909399;">
        暂无转换事件，请点击“添加事件”按钮添加
      </div>
      
      <div v-for="(event, index) in conversionEvents" :key="index" class="conversion-event-item">
        <div class="event-header">
          <span class="event-title">事件{{ index + 1 }}</span>
          <el-button 
            type="danger" 
            size="mini" 
            icon="el-icon-delete" 
            circle
            @click="removeConversionEvent(index)"
          ></el-button>
        </div>
        
        <el-form label-width="140px" style="margin-top: 10px;">
          <el-form-item label="广告商转化类型">
            <el-select 
              v-model="event.advertiserEventType" 
              placeholder="请选择广告商转化类型" 
              style="width: 100%"
              @change="handleAdvertiserEventChange(index, $event)"
            >
              <el-option
                v-for="item in advertiserEventOptions"
                :key="item.eventType"
                :label="item.eventName"
                :value="item.eventType"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="回传数据类型">
            <el-select 
              v-model="event.systemEventType" 
              placeholder="请选择回传数据类型" 
              style="width: 100%"
              @change="handleSystemEventChange(index, $event)"
            >
              <el-option
                v-for="item in systemEventOptions"
                :key="item.eventType"
                :label="item.eventName"
                :value="item.eventType"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveConversionEvents">保 存</el-button>
        <el-button @click="conversionOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageCallbackAccount, getCallbackAccount, addCallbackAccount, updateCallbackAccount, delCallbackAccount, batchDelCallbackAccount, queryEventType, saveEventType } from "@/api/adv/callbackAccount";
import { pageAdvertiser } from "@/api/adv/advertiser";

export default {
  name: "CallbackAccount",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 回传账号表格数据
      accountList: [],
      // 广告商选项
      advertiserOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示转换类型弹窗
      conversionOpen: false,
      // 当前操作的回传账号
      currentAccount: null,
      // 转换事件列表
      conversionEvents: [],
      // systemBuiltIn=0）
      advertiserEventOptions: [],
      // systemBuiltIn=1）
      systemEventOptions: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        accountName: undefined,
        advertiserId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        advertiserId: [
          { required: true, message: "请选择广告商", trigger: "change" }
        ],
        accountName: [
          { required: true, message: "账号名称不能为空", trigger: "blur" }
        ],
        adAccountId: [
          { 
            validator: (rule, value, callback) => {
              if ([1, 3, 4, 5].includes(this.form.advertiserId) && !value) {
                callback(new Error('此字段不能为空'));
              } else {
                callback();
              }
            }, 
            trigger: "blur" 
          }
        ],
        accessToken: [
          { 
            validator: (rule, value, callback) => {
              if ([1, 3].includes(this.form.advertiserId) && !value) {
                callback(new Error('此字段不能为空'));
              } else {
                callback();
              }
            }, 
            trigger: "blur" 
          }
        ],
        scrId: [
          { 
            validator: (rule, value, callback) => {
              if ([3, 5].includes(this.form.advertiserId) && !value) {
                callback(new Error('此字段不能为空'));
              } else {
                callback();
              }
            }, 
            trigger: "blur" 
          }
        ],
        appId: [
          { 
            validator: (rule, value, callback) => {
              if ([4, 5].includes(this.form.advertiserId) && !value) {
                callback(new Error('此字段不能为空'));
              } else {
                callback();
              }
            }, 
            trigger: "blur" 
          }
        ],
        appSecret: [
          { 
            validator: (rule, value, callback) => {
              if ([4, 5].includes(this.form.advertiserId) && !value) {
                callback(new Error('此字段不能为空'));
              } else {
                callback();
              }
            }, 
            trigger: "blur" 
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询广告商选项 */
    getAdvertiserOptions() {
      pageAdvertiser({ current: 1, size: 1000 }).then(response => {
        this.advertiserOptions = response.data.records;
      });
    },
    /** 查询回传账号列表 */
    getList() {
      this.loading = true;
      pageCallbackAccount(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,
        advertiserId: undefined,
        advertiserName: undefined,
        accountName: undefined,
        adAccountId: undefined,
        accessToken: undefined,
        scrId: undefined,
        appId: undefined,
        appSecret: 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.getAdvertiserOptions();
      this.open = true;
      this.title = "添加回传账号";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getAdvertiserOptions();
      const id = row.id || this.ids[0];
      getCallbackAccount(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) {
            updateCallbackAccount(this.form.id, this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addCallbackAccount(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 广告商变化时 */
    handleAdvertiserChange(advertiserId) {
      this.form.advertiserName = "";
      if (advertiserId) {
        const advertiser = this.advertiserOptions.find(item => item.id === advertiserId);
        if (advertiser) {
          this.form.advertiserName = advertiser.advertiserName;
        }
      }
      // 清空其他字段
      this.form.adAccountId = undefined;
      this.form.accessToken = undefined;
      this.form.scrId = undefined;
      this.form.appId = undefined;
      this.form.appSecret = undefined;
    },
    /** 添加转换类型按钮操作 */
    handleConversionType(row) {
      this.currentAccount = row;
      this.conversionOpen = true;
      
      // 加载事件类型选项
      this.loadEventTypes(row.advertiserId);
      
      // 解析已有的转换事件
      this.parseConversionEvents(row.conversionEvent);
    },
    /** 回传结果按钮操作 */
    handleConversionLog(row) {
      this.$router.push({
        path: '/adv/new-adv/conversionLog',
        query: { callbackAccountId: row.id }
      });
    },
    /** 加载事件类型选项 */
    loadEventTypes(advertiserId) {
      queryEventType(advertiserId).then(response => {
        const eventTypes = response.data || [];
        // systemBuiltin='0' 为广告商事件
        this.advertiserEventOptions = eventTypes.filter(item => item.systemBuiltin === '0');
        // systemBuiltin='1' 为系统事件
        this.systemEventOptions = eventTypes.filter(item => item.systemBuiltin === '1');
      }).catch(error => {
        console.error('加载事件类型失败:', error);
        this.msgError('加载事件类型失败');
      });
    },
    /** 解析转换事件 */
    parseConversionEvents(conversionEvent) {
      try {
        if (conversionEvent && typeof conversionEvent === 'string') {
          this.conversionEvents = JSON.parse(conversionEvent);
        } else if (Array.isArray(conversionEvent)) {
          this.conversionEvents = conversionEvent;
        } else {
          this.conversionEvents = [];
        }
      } catch (error) {
        console.error('解析转换事件失败:', error);
        this.conversionEvents = [];
      }
    },
    /** 添加转换事件 */
    addConversionEvent() {
      this.conversionEvents.push({
        systemEventType: '',
        systemEventTypeName: '',
        advertiserEventType: '',
        advertiserEventName: ''
      });
    },
    /** 删除转换事件 */
    removeConversionEvent(index) {
      this.conversionEvents.splice(index, 1);
    },
    /** 广告商事件变化 */
    handleAdvertiserEventChange(index, eventType) {
      const event = this.advertiserEventOptions.find(item => item.eventType === eventType);
      if (event) {
        this.conversionEvents[index].advertiserEventName = event.eventName;
      }
    },
    /** 系统事件变化 */
    handleSystemEventChange(index, eventType) {
      const event = this.systemEventOptions.find(item => item.eventType === eventType);
      if (event) {
        this.conversionEvents[index].systemEventTypeName = event.eventName;
      }
    },
    /** 保存转换事件 */
    saveConversionEvents() {
      // 校验数据
      for (let i = 0; i < this.conversionEvents.length; i++) {
        const event = this.conversionEvents[i];
        if (!event.systemEventType || !event.advertiserEventType) {
          this.msgError(`请完善事件${i + 1}的配置`);
          return;
        }
      }
      
      // 调用保存接口
      saveEventType(this.currentAccount.id, this.conversionEvents).then(response => {
        if (response.code === 200) {
          this.msgSuccess('保存成功');
          this.conversionOpen = false;
          this.getList();
        }
      }).catch(error => {
        console.error('保存失败:', error);
        this.msgError('保存失败');
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids;
      this.$confirm('是否确认删除选中的回传账号?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 单条删除使用 delCallbackAccount，批量删除使用 batchDelCallbackAccount
        if (row.id) {
          return delCallbackAccount(row.id);
        } else {
          return batchDelCallbackAccount(ids);
        }
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function() {});
    }
  }
};
</script>

<style scoped>
.conversion-event-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background-color: #fafafa;
}

.event-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.event-title {
  font-weight: 600;
  font-size: 15px;
  color: #303133;
}
</style>