<template>
  <div class="app-container">
    <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="success"
          icon="el-icon-refresh"
          size="mini"
          @click="getList"
        >刷新</el-button>
      </el-col>
    </el-row>

    <el-table border v-loading="loading" :data="siteList">
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="站点名称" align="center" prop="siteName" min-width="150" show-overflow-tooltip />
      <el-table-column label="投放类型" align="center" prop="launchType" width="100" />
      <el-table-column label="配置回传" align="center" prop="configCallback" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.configCallback === 1 ? 'success' : 'info'" size="small">
            {{ scope.row.configCallback === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="站点状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" size="small">
            {{ scope.row.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <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="420" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(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-data-line"
            @click="handleStatistics(scope.row)"
          >统计</el-button>
          <el-button
            size="mini"
            type="text"
            :icon="scope.row.status === 1 ? 'el-icon-video-pause' : 'el-icon-video-play'"
            @click="handleEnable(scope.row)"
          >{{ scope.row.status === 1 ? '停用' : '启用' }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="handleGenerateUrl(scope.row)"
          >生成投放url</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改站点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body class="site-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px" 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="siteName">
            <el-input 
              v-model="form.siteName" 
              placeholder="请输入站点名称"
              prefix-icon="el-icon-notebook-2"
              clearable
              :disabled="isDetail"
            />
          </el-form-item>
          <el-form-item label="渠道" prop="channelId">
            <el-select 
              v-model="form.channelId" 
              placeholder="请选择渠道" 
              style="width: 100%"
              filterable
              @change="handleChannelChange"
              :disabled="isDetail"
            >
              <el-option
                v-for="item in channelList"
                :key="item.id"
                :label="item.channelName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目" prop="projectId">
            <el-select 
              v-model="form.projectId" 
              placeholder="请选择项目" 
              style="width: 100%"
              filterable
              @change="handleProjectChange"
              :disabled="isDetail"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 投放配置 -->
        <div class="form-section">
          <div class="section-title">
            <i class="el-icon-setting"></i>
            <span>投放配置</span>
          </div>
          <el-form-item label="投放类型" prop="launchType">
            <el-select 
              v-model="form.launchType" 
              placeholder="请选择投放类型" 
              style="width: 100%"
              prefix-icon="el-icon-s-flag"
              @change="handleLaunchTypeChange"
              :disabled="isDetail"
            >
              <el-option
                v-for="item in launchTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="广告类型" prop="adType">
            <el-select 
              v-model="form.adType" 
              placeholder="请选择广告类型" 
              style="width: 100%"
              :disabled="isDetail"
            >
              <el-option
                v-for="item in adTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          
          <!-- 企微分配规则 -->
          <el-form-item label="企微分配规则" prop="allocationRule">
            <el-radio-group v-model="form.allocationRule" @change="handleAllocationRuleChange" :disabled="!form.launchType || isDetail">
              <el-radio 
                label="1"
                :border="true"
              >个人码分配</el-radio>
              <el-radio 
                label="2"
                :border="true"
              >活码分配</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <!-- 根据选择的分配规则显示不同的下拉框 -->
          <el-form-item 
            v-if="form.allocationRule === '1'" 
            label="企业微信" 
            prop="allocationRuleId"
            class="slide-fade"
          >
            <el-select 
              v-model="form.allocationRuleId" 
              placeholder="请选择企业微信" 
              style="width: 100%"
              filterable
              :disabled="isDetail"
            >
              <el-option
                v-for="item in allocationRuleList"
                :key="item.id"
                :label="item.ruleName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item 
            v-if="form.allocationRule === '2'" 
            :label="form.launchType === 1 ? '群活码' : '企业微信活码'" 
            prop="allocationRuleId"
            class="slide-fade"
          >
            <el-select 
              v-model="form.allocationRuleId" 
              :placeholder="form.launchType === 1 ? '请选择群活码' : '请选择企业微信活码'" 
              style="width: 100%"
              filterable
              :disabled="isDetail"
            >
              <el-option
                v-for="item in form.launchType === 1 ? groupActiveList : contactWayList"
                :key="item.id"
                :label="form.launchType === 1 ? item.groupName : item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 广告商信息 -->
        <div class="form-section">
          <div class="section-title">
            <i class="el-icon-office-building"></i>
            <span>广告商信息</span>
          </div>
          <el-form-item label="投放广告商" prop="advertiserId">
            <el-select 
              v-model="form.advertiserId" 
              placeholder="请先选择投放类型" 
              style="width: 100%"
              @change="handleAdvertiserChange"
              filterable
              :disabled="!form.launchType || isDetail"
            >
              <el-option
                v-for="item in advertiserList"
                :key="item.id"
                :label="item.advertiserName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="投放广告商账号" prop="promotionAccountId">
            <el-select 
              v-model="form.promotionAccountId" 
              placeholder="请选择投放广告商账号" 
              style="width: 100%"
              @change="handlePromotionAccountChange"
              filterable
              :disabled="!form.advertiserId || isDetail"
            >
              <el-option
                v-for="item in promotionAccountList"
                :key="item.id"
                :label="item.accountName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 页面和来源 -->
        <div class="form-section">
          <div class="section-title">
            <i class="el-icon-monitor"></i>
            <span>页面和来源</span>
          </div>
          <el-form-item label="投放页面" prop="launchPageId">
            <el-select 
              v-model="form.launchPageId" 
              placeholder="请选择投放页面" 
              style="width: 100%"
              @change="handleLaunchPageChange"
              filterable
              :disabled="isDetail"
            >
              <el-option
                v-for="item in landingPageTemplateList"
                :key="item.id"
                :label="item.templateName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="投放域名" prop="launchDomain">
            <el-select 
              v-model="form.launchDomain" 
              placeholder="请选择投放域名" 
              style="width: 100%"
              filterable
              :disabled="isDetail"
            >
              <el-option
                v-for="item in launchDomainList"
                :key="item.id"
                :label="item.domain"
                :value="item.domain"
              />
            </el-select>
          </el-form-item>

        </div>

        <!-- 回传配置 -->
        <div class="form-section">
          <div class="section-title">
            <i class="el-icon-share"></i>
            <span>回传配置</span>
          </div>
          <el-form-item label="是否配置回传" prop="configCallback">
            <el-radio-group v-model="form.configCallback" @change="handleConfigCallbackChange" :disabled="isDetail">
              <el-radio 
                v-for="item in configCallbackOptions"
                :key="item.value"
                :label="item.value"
                :border="true"
              >{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item 
            v-if="form.configCallback === 1" 
            label="回传账号" 
            prop="callbackAccountId"
            class="slide-fade"
          >
            <el-select 
              v-model="form.callbackAccountId" 
              placeholder="请选择回传账号" 
              style="width: 100%"
              @change="handleCallbackAccountChange"
              filterable
              :disabled="isDetail"
            >
              <el-option
                v-for="item in callbackAccountList"
                :key="item.id"
                :label="item.accountName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          
          <!-- 转换类型配置区域 -->
          <div v-if="form.configCallback === 1 && form.callbackAccountId" class="conversion-config-section">
            <div class="config-header">
              <span class="config-title">转换类型配置</span>
              <el-button type="primary" size="small" icon="el-icon-plus" @click="addConversionEvent">添加事件</el-button>
            </div>
            
            <div v-if="conversionEvents.length === 0" class="empty-tip">
              暂无转换事件，请点击“添加事件”按钮添加
            </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="130px" 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>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button v-if="!isDetail" type="primary" @click="submitForm" icon="el-icon-check">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 站点详情对话框 -->
    <el-dialog title="站点详情" :visible.sync="detailOpen" width="900px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="站点名称">{{ detail.siteName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="站点URL" :span="2">{{ detail.siteUrl || '-' }}</el-descriptions-item>
        <el-descriptions-item label="投放类型">{{ detail.launchType || '-' }}</el-descriptions-item>
        <el-descriptions-item label="广告类型">{{ detail.adType || '-' }}</el-descriptions-item>
        <el-descriptions-item label="广告商名称" :span="2">{{ detail.advertiserName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="推广账户名称" :span="2">{{ detail.promotionAccountName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="投放页面名称" :span="2">{{ detail.launchPageName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="投放域名" :span="2">{{ detail.launchDomain || '-' }}</el-descriptions-item>
        <el-descriptions-item label="一级分配规则">
          <span v-if="detail.allocationRule === '1'">选择员工"个人码"分配规则</span>
          <span v-else-if="detail.allocationRule === '2'">选择员工"活码"分配规则</span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="二级分配汇总">{{ detail.allocationRuleId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="项目名称">{{ detail.projectName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="配置回传">
          <el-tag :type="detail.configCallback === 1 ? 'success' : 'info'" size="small">
            {{ detail.configCallback === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="回传账号名称">{{ detail.callbackAccountName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="站点状态">
          <el-tag :type="detail.status === 1 ? 'success' : 'info'" size="small">
            {{ detail.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建人">{{ detail.creator || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(detail.createTime) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新人">{{ detail.updater || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">{{ parseTime(detail.updateTime) || '-' }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 站点统计对话框 -->
    <el-dialog title="站点统计" :visible.sync="statisticsOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border v-if="statistics">
        <el-descriptions-item label="站点ID">{{ statistics.siteId }}</el-descriptions-item>
        <el-descriptions-item label="访问量">{{ statistics.visitCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="访客数">{{ statistics.visitorCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="转化数">{{ statistics.conversionCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="转化率">
          {{ statistics.conversionRate ? (statistics.conversionRate * 100).toFixed(2) + '%' : '0%' }}
        </el-descriptions-item>
        <el-descriptions-item label="统计时间">{{ parseTime(statistics.updateTime) }}</el-descriptions-item>
      </el-descriptions>
      <div v-else style="text-align: center; padding: 40px 0;">
        <el-empty description="暂无统计数据"></el-empty>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="statisticsOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 生成投放url对话框 -->
    <el-dialog title="生成投放url" :visible.sync="urlDialogOpen" width="500px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="投放链接">
          <div class="url-container">
            <el-input 
              v-model="launchUrl" 
              readonly
              class="url-input"
            />
            <el-button 
              type="primary" 
              size="small"
              icon="el-icon-document-copy"
              @click="copyUrl"
            >复制</el-button>
          </div>
        </el-form-item>
        <el-form-item label="二维码">
          <div id="qrcode" class="qrcode-container"></div>
          <el-button 
            type="primary" 
            size="small"
            icon="el-icon-download"
            @click="downloadQrcode"
            style="margin-top: 10px;"
          >下载</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="urlDialogOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSite, getSite, addSite, updateSite, delSite, getSiteStatistics, enableSite } from "@/api/adv/site";
import { pageAdvertiser } from "@/api/adv/advertiser";
import { pagePromotionAccount } from "@/api/adv/promotionAccount";
import { pageTemplate } from "@/api/adv/landingPageTemplate";
import QRCode from 'qrcode';

import { pageCallbackAccount, getCallbackAccount, queryEventType, saveEventType } from "@/api/adv/callbackAccount";
import { pageDomain } from "@/api/adv/domain";
import { pageProject as pageChannel } from "@/api/adv/channel";
import { pageProject } from "@/api/adv/project";
import { pageAssignRule } from "@/api/qw/assignRule";
import { pageGroupLiveCode } from "@/api/qw/groupLiveCode";
import { listContactWay } from "@/api/qw/contactWay";

export default {
  name: "Site",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 站点表格数据
      siteList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为详情模式（只读）
      isDetail: false,
      // 是否显示详情对话框
      detailOpen: false,
      // 详情数据
      detail: {},
      // 是否显示统计弹出层
      statisticsOpen: false,
      // 统计数据
      statistics: null,
      // 表单参数
      form: {},
      // 投放类型选项
      launchTypeOptions: [
        { label: "线上投放", value: 1 },
        { label: "线下投放", value: 2 }
      ],
      // 广告类型选项
      adTypeOptions: [
        { label: "信息流广告", value: "信息流广告" }
      ],
      // 是否配置回传选项
      configCallbackOptions: [
        { label: "否", value: 0 },
        { label: "是", value: 1 }
      ],
      // 广告商列表
      advertiserList: [],
      // 广告商账号列表
      promotionAccountList: [],
      // 落地页模板列表
      landingPageTemplateList: [],
      // 企业微信分配规则列表
      allocationRuleList: [],
      // 群活码列表
      groupActiveList: [],
      // 企业微信活码列表
      contactWayList: [],
      // 回传账号列表
      callbackAccountList: [],
      // 投放域名列表
      launchDomainList: [],
      // 渠道列表
      channelList: [],
      // 项目列表
      projectList: [],
      // 转换事件列表
      conversionEvents: [],
      // 广告商事件选项（systemBuiltin='0'）
      advertiserEventOptions: [],
      // 系统事件选项（systemBuiltin='1'）
      systemEventOptions: [],
      // 生成url对话框
      urlDialogOpen: false,
      // 投放链接
      launchUrl: "",
      // 表单校验
      rules: {
        siteName: [
          { required: true, message: "站点名称不能为空", trigger: "blur" }
        ],
        siteUrl: [
          { required: true, message: "站点地址不能为空", trigger: "blur" }
        ],
        launchType: [
          { required: true, message: "请选择投放类型", trigger: "change" }
        ],
        adType: [
          { required: true, message: "请选择广告类型", trigger: "change" }
        ],
        advertiserId: [
          { required: true, message: "请选择投放广告商", trigger: "change" }
        ],
        promotionAccountId: [
          { required: true, message: "请选择投放广告商账号", trigger: "change" }
        ],
        launchPageId: [
          { required: true, message: "请选择投放页面", trigger: "change" }
        ],

        launchDomain: [
          { required: true, message: "请选择投放域名", trigger: "change" }
        ],
        configCallback: [
          { required: true, message: "请选择是否配置回传", trigger: "change" }
        ],
        callbackAccountId: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.configCallback === 1 && !value) {
                callback(new Error('请选择回传账号'));
              } else {
                callback();
              }
            }, 
            trigger: "change" 
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询站点列表 */
    getList() {
      this.loading = true;
      listSite().then(response => {
        this.siteList = response.data;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        siteName: undefined,
        siteUrl: undefined,
        launchType: undefined,
        adType: undefined,
        advertiserId: undefined,
        advertiserName: undefined,
        promotionAccountId: undefined,
        promotionAccountName: undefined,
        launchPageId: undefined,
        launchPageName: undefined,
        projectId: undefined,
        projectName: undefined,
        channelId: undefined,
        channelName: undefined,
        launchDomain: undefined,
        configCallback: 0,
        callbackAccountId: undefined,
        callbackAccountName: undefined,
        allocationRule: undefined,
        allocationRuleId: undefined
      };
      this.promotionAccountList = [];
      this.launchDomainList = [];
      this.allocationRuleList = [];
      this.groupActiveList = [];
      this.contactWayList = [];
      this.conversionEvents = [];
      this.advertiserEventOptions = [];
      this.systemEventOptions = [];
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 不再预加载广告商列表，等待选择投放类型后再加载
      this.loadCommonSelectOptions();
      this.isDetail = false;
      this.open = true;
      this.title = "添加站点";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.loadCommonSelectOptions();
      this.isDetail = false;
      getSite(row.id).then(response => {
        this.form = response.data;
        // 确保 allocationRule 是字符串类型
        if (this.form.allocationRule !== undefined && this.form.allocationRule !== null) {
          this.form.allocationRule = String(this.form.allocationRule);
        }
        // 根据投放类型加载广告商列表
        if (this.form.launchType) {
          this.loadAdvertiserList(this.form.launchType);
        }
        // 如果有广告商ID，加载对应的广告商账号列表
        if (this.form.advertiserId) {
          this.loadPromotionAccountList(this.form.advertiserId);
          
          // 如果配置了回传，加载回传账号列表
          if (this.form.configCallback === 1) {
            this.loadCallbackAccountList(this.form.advertiserId);
            
            // 如果有回传账号，加载事件类型和转换事件
            if (this.form.callbackAccountId) {
              this.loadEventTypesAndConversionEvents(this.form.advertiserId, this.form.callbackAccountId);
            }
          }
        }
        // 如果设置了企微分配规则，加载对应的数据
        if (this.form.allocationRule) {
          if (this.form.allocationRule === '1') {
            // 加载企业微信分配规则列表
            this.loadAllocationRuleList();
          } else if (this.form.allocationRule === '2') {
            // 加载活码列表（根据投放类型）
            if (this.form.launchType === 1) {
              this.loadGroupActiveList();
            } else if (this.form.launchType === 2) {
              this.loadContactWayList();
            }
          }
        }
        this.$nextTick(() => {
          this.open = true;
          this.title = "修改站点";
        });
      });
    },
    /** 查看统计按钮操作 */
    handleStatistics(row) {
      this.$router.push({
        path: '/adv/new-adv/statistics',
        query: { siteId: row.id }
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.detail = {};
      this.detailOpen = true;
      getSite(row.id).then(response => {
        this.detail = response.data;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 如果配置了回传且有转换事件，校验转换事件
          if (this.form.configCallback === 1 && this.form.callbackAccountId && this.conversionEvents.length > 0) {
            for (let i = 0; i < this.conversionEvents.length; i++) {
              const event = this.conversionEvents[i];
              if (!event.systemEventType || !event.advertiserEventType) {
                this.msgError(`请完善事件${i + 1}的配置`);
                return;
              }
            }
          }
          
          if (this.form.id != undefined) {
            // 修改
            updateSite(this.form.id, this.form).then(response => {
              if (response.code === 200) {
                // 如果配置了回传，保存转换事件
                if (this.form.configCallback === 1 && this.form.callbackAccountId) {
                  this.saveConversionEvents();
                } else {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              }
            });
          } else {
            // 新增
            addSite(this.form).then(response => {
              if (response.code === 200) {
                // 如果配置了回传，保存转换事件
                if (this.form.configCallback === 1 && this.form.callbackAccountId) {
                  this.saveConversionEvents();
                } else {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除站点"' + row.siteName + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delSite(row.id);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function() {});
    },
    /** 启用/停用按鑵操作 */
    handleEnable(row) {
      const statusText = row.status === 1 ? '停用' : '启用';
      this.$confirm(`是否确认${statusText}站点"${row.siteName}"?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return enableSite(row.id);
      }).then(() => {
        this.getList();
        this.msgSuccess(`${statusText}成功`);
      }).catch(function() {});
    },
    /** 生成投放url */
    handleGenerateUrl(row) {
      this.launchUrl = row.siteUrl || '';
      this.urlDialogOpen = true;
      this.$nextTick(() => {
        this.generateQrcode();
      });
    },
    /** 生成二维码 */
    generateQrcode() {
      const qrcodeElement = document.getElementById('qrcode');
      if (qrcodeElement) {
        qrcodeElement.innerHTML = '';
        // 创建 canvas 元素
        const canvas = document.createElement('canvas');
        QRCode.toCanvas(canvas, this.launchUrl, {
          errorCorrectionLevel: 'H',
          type: 'image/jpeg',
          quality: 0.95,
          margin: 1,
          width: 200
        }).then(() => {
          qrcodeElement.appendChild(canvas);
        }).catch(error => {
          console.error('生成二维码失败:', error);
          this.msgError('生成二维码失败');
        });
      }
    },
    /** 复制url */
    copyUrl() {
      if (!this.launchUrl) {
        this.msgError('投放链接为空');
        return;
      }
      navigator.clipboard.writeText(this.launchUrl).then(() => {
        this.msgSuccess('复制成功');
      }).catch(() => {
        // 平台不支持新API，改成传统方法
        const textarea = document.createElement('textarea');
        textarea.value = this.launchUrl;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        this.msgSuccess('复制成功');
      });
    },
    /** 下载二维码 */
    downloadQrcode() {
      const qrcodeCanvas = document.querySelector('#qrcode canvas');
      if (qrcodeCanvas) {
        const link = document.createElement('a');
        link.href = qrcodeCanvas.toDataURL();
        link.download = `qrcode_${new Date().getTime()}.png`;
        link.click();
        this.msgSuccess('下载成功');
      } else {
        this.msgError('没有找到二维码');
      }
    },
    /** 加载下拉选项数据 */
    loadSelectOptions() {
      // 加载广告商列表（已废弃，改用loadAdvertiserList）
      pageAdvertiser({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.advertiserList = response.data.records;
      }).catch(error => {
        console.error('加载广告商列表失败:', error);
        this.advertiserList = [];
      });
      
      // 加载落地页模板列表
      pageTemplate({ pageNum: 1, pageSize: 1000, status: 1 }).then(response => {
        this.landingPageTemplateList = response.data.records;
      }).catch(error => {
        console.error('加载落地页模板失败:', error);
        this.landingPageTemplateList = [];
      });
      
      // 加载域名列表
      pageDomain({ pageNum: 1, pageSize: 1000, status: 1 }).then(response => {
        this.launchDomainList = response.data.records;
      }).catch(error => {
        console.error('加载域名失败:', error);
        this.launchDomainList = [];
      });
    },
    /** 加载公共下拉选项数据（不包含广告商） */
    loadCommonSelectOptions() {
      // 加载落地页模板列表
      pageTemplate({ pageNum: 1, pageSize: 1000, status: 1 }).then(response => {
        this.landingPageTemplateList = response.data.records;
      }).catch(error => {
        console.error('加载落地页模板失败:', error);
        this.landingPageTemplateList = [];
      });
      
      // 加载域名列表
      pageDomain({ pageNum: 1, pageSize: 1000, status: 1 }).then(response => {
        this.launchDomainList = response.data.records;
      }).catch(error => {
        console.error('加载域名失败:', error);
        this.launchDomainList = [];
      });
      
      // 加载渠道列表
      pageChannel({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.channelList = response.data.records || [];
      }).catch(error => {
        console.error('加载渠道列表失败:', error);
        this.channelList = [];
      });
      
      // 加载项目列表
      pageProject({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.projectList = response.data.records || [];
      }).catch(error => {
        console.error('加载项目列表失败:', error);
        this.projectList = [];
      });
    },
    /** 投放类型变化时 */
    handleLaunchTypeChange(launchType) {
      // 重置广告商相关数据
      this.form.advertiserId = undefined;
      this.form.advertiserName = "";
      this.form.promotionAccountId = undefined;
      this.form.promotionAccountName = "";
      this.advertiserList = [];
      this.promotionAccountList = [];
      
      // 重置回传账号相关数据
      this.form.callbackAccountId = undefined;
      this.form.callbackAccountName = "";
      this.callbackAccountList = [];
      this.conversionEvents = [];
      this.advertiserEventOptions = [];
      this.systemEventOptions = [];
      
      // 重置企业微信分配规则相关数据
      this.form.allocationRule = undefined;
      this.form.allocationRuleId = undefined;
      this.allocationRuleList = [];
      this.groupActiveList = [];
      this.contactWayList = [];
      
      // 根据投放类型加载广告商列表
      if (launchType) {
        this.loadAdvertiserList(launchType);
      }
      
      // 根据投放类型重新加载活码数据（如果已选择活码分配）
      if (this.form.allocationRule === '2') {
        if (launchType === 1) {
          this.loadGroupActiveList();
        } else if (launchType === 2) {
          this.loadContactWayList();
        }
      }
    },
    /** 加载广告商列表 */
    loadAdvertiserList(launchType) {
      if (!launchType) return;
      // launchType: 1=线上投放, 2=线下投放
      // custom: 1=线上广告商, 2=自定义广告商
      const customValue = launchType; // launchType值直接对应custom值
      pageAdvertiser({ 
        pageNum: 1, 
        pageSize: 1000, 
        enabled: 1,
        custom: customValue 
      }).then(response => {
        this.advertiserList = response.data.records;
      }).catch(error => {
        console.error('加载广告商列表失败:', error);
        this.advertiserList = [];
      });
    },
    /** 广告商变化时 */
    handleAdvertiserChange(advertiserId) {
      this.form.advertiserName = "";
      this.form.promotionAccountId = undefined;
      this.form.promotionAccountName = "";
      this.promotionAccountList = [];
      
      // 重置回传账号相关数据
      this.form.callbackAccountId = undefined;
      this.form.callbackAccountName = "";
      this.callbackAccountList = [];
      
      if (advertiserId) {
        const advertiser = this.advertiserList.find(item => item.id === advertiserId);
        if (advertiser) {
          this.form.advertiserName = advertiser.advertiserName;
        }
        // 加载对应的广告商账号列表
        this.loadPromotionAccountList(advertiserId);
        
        // 如果已选择配置回传，加载回传账号列表
        if (this.form.configCallback === 1) {
          this.loadCallbackAccountList(advertiserId);
        }
      }
    },
    /** 加载广告商账号列表 */
    loadPromotionAccountList(advertiserId) {
      if (!advertiserId) return;
      pagePromotionAccount({ pageNum: 1, pageSize: 1000, advertiserId: advertiserId }).then(response => {
        this.promotionAccountList = response.data.records;
      }).catch(error => {
        console.error('加载广告商账号失败:', error);
        this.promotionAccountList = [];
      });
    },
    /** 广告商账号变化时 */
    handlePromotionAccountChange(promotionAccountId) {
      this.form.promotionAccountName = "";
      if (promotionAccountId) {
        const account = this.promotionAccountList.find(item => item.id === promotionAccountId);
        if (account) {
          this.form.promotionAccountName = account.accountName;
        }
      }
    },
    /** 投放页面变化时 */
    handleLaunchPageChange(launchPageId) {
      this.form.launchPageName = "";
      
      if (launchPageId) {
        const template = this.landingPageTemplateList.find(item => item.id === launchPageId);
        if (template) {
          this.form.launchPageName = template.templateName;
        }
      }
    },
    
    /** 渠道变化时 */
    handleChannelChange(channelId) {
      this.form.channelName = "";
      
      if (channelId) {
        const channel = this.channelList.find(item => item.id === channelId);
        if (channel) {
          this.form.channelName = channel.channelName;
        }
      }
    },

    /** 项目变化时 */
    handleProjectChange(projectId) {
      this.form.projectName = "";
      
      if (projectId) {
        const project = this.projectList.find(item => item.id === projectId);
        if (project) {
          this.form.projectName = project.projectName;
        }
      }
    },

    /** 回传账号变化时 */
    handleCallbackAccountChange(callbackAccountId) {
      this.form.callbackAccountName = "";
      this.conversionEvents = [];
      this.advertiserEventOptions = [];
      this.systemEventOptions = [];
      
      if (callbackAccountId) {
        const account = this.callbackAccountList.find(item => item.id === callbackAccountId);
        if (account) {
          this.form.callbackAccountName = account.accountName;
          // 加载事件类型和转换事件
          this.loadEventTypesAndConversionEvents(this.form.advertiserId, callbackAccountId);
        }
      }
    },
    /** 配置回传变化时 */
    handleConfigCallbackChange(value) {
      // 重置回传账号
      this.form.callbackAccountId = undefined;
      this.form.callbackAccountName = "";
      this.callbackAccountList = [];
      this.conversionEvents = [];
      this.advertiserEventOptions = [];
      this.systemEventOptions = [];
      
      // 重置企微分配规则相关数据
      this.form.allocationRule = undefined;
      this.form.allocationRuleId = undefined;
      this.allocationRuleList = [];
      this.groupActiveList = [];
      
      // 如果选择配置回传，且已选择广告商，加载回传账号列表
      if (value === 1 && this.form.advertiserId) {
        this.loadCallbackAccountList(this.form.advertiserId);
      }
    },
    /** 加载回传账号列表 */
    loadCallbackAccountList(advertiserId) {
      if (!advertiserId) return;
      pageCallbackAccount({ pageNum: 1, pageSize: 1000, advertiserId: advertiserId }).then(response => {
        this.callbackAccountList = response.data.records;
      }).catch(error => {
        console.error('加载回传账号列表失败:', error);
        this.callbackAccountList = [];
      });
    },
    /** 加载事件类型和转换事件 */
    loadEventTypesAndConversionEvents(advertiserId, callbackAccountId) {
      // 加载事件类型选项
      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);
      });
      
      // 加载已有的转换事件
      getCallbackAccount(callbackAccountId).then(response => {
        const account = response.data;
        this.parseConversionEvents(account.conversionEvent);
      }).catch(error => {
        console.error('加载回传账号详情失败:', error);
      });
    },
    /** 解析转换事件 */
    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;
      }
    },
    /** 企微分配规则变化 */
    handleAllocationRuleChange(allocationRule) {
      // 重置需要加载的数据列表
      this.form.allocationRuleId = undefined;
      this.allocationRuleList = [];
      this.groupActiveList = [];
      this.contactWayList = [];
      
      // 根据不同的分配规则加载对应数据
      if (allocationRule === '1') {
        // 加载企业微信分配规则列表
        this.loadAllocationRuleList();
      } else if (allocationRule === '2') {
        // 根据投放类型加载群活码或企业微信活码
        if (this.form.launchType === 1) {
          this.loadGroupActiveList();
        } else if (this.form.launchType === 2) {
          this.loadContactWayList();
        }
      }
    },
    /** 加载企业微信分配规则列表 */
    loadAllocationRuleList() {
      pageAssignRule({
        pageNum: 1,
        pageSize: 1000,
        status: 1
      }).then(response => {
        this.allocationRuleList = response.data.records || [];
      }).catch(error => {
        console.error('加载企业微信分配规则列表失败:', error);
        this.allocationRuleList = [];
      });
    },
    /** 加载群活码列表 */
    loadGroupActiveList() {
      pageGroupLiveCode({
        pageNum: 1,
        pageSize: 1000,
        status: 1
      }).then(response => {
        this.groupActiveList = response.data.records || [];
      }).catch(error => {
        console.error('加载群活码列表失败:', error);
        this.groupActiveList = [];
      });
    },
    /** 加载企业微信活码列表 */
    loadContactWayList() {
      // 调用/qw/contactWay/list接口获取企业微信活码数据
      // 注意：此接口返回rows字段，不是data.records
      listContactWay().then(response => {
        this.contactWayList = response.rows || [];
      }).catch(error => {
        console.error('加载企业微信活码列表失败:', error);
        this.contactWayList = [];
      });
    },
    /** 保存转换事件 */
    saveConversionEvents() {
      // 调用保存接口
      saveEventType(this.form.callbackAccountId, this.conversionEvents).then(response => {
        if (response.code === 200) {
          this.msgSuccess('保存成功');
          this.open = false;
          this.getList();
        }
      }).catch(error => {
        console.error('保存失败:', error);
        this.msgError('保存失败');
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

// 对话框样式
::v-deep .site-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;
  }
  
  .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);
    }
  }
  
  ::v-deep .el-select {
    .el-input__inner {
      padding-left: 15px;
    }
  }
  
  ::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);
      }
    }
  }
  
  // 回传账号显示动画
  .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);
      }
    }
  }
}

// 表格样式优化
.el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  
  ::v-deep .el-table__header {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
      font-size: 14px;
    }
  }
  
  ::v-deep .el-table__row {
    transition: all 0.3s ease;
    
    &:hover {
      background-color: rgba(102, 126, 234, 0.05);
    }
  }
}

// 顶部按钮组样式
.mb8 {
  margin-bottom: 15px;
  
  .el-button {
    border-radius: 6px;
    padding: 10px 20px;
    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);
      }
    }
    
    &.el-button--success {
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
      }
    }
  }
}

// 转换类型配置区域样式
.conversion-config-section {
  margin-top: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
  
  .config-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    .config-title {
      font-size: 15px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .empty-tip {
    text-align: center;
    padding: 30px 0;
    color: #909399;
    font-size: 14px;
  }
}

.conversion-event-item {
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  background-color: #fff;
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  }
  
  .event-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
    
    .event-title {
      font-weight: 600;
      font-size: 14px;
      color: #303133;
    }
  }
}

// 投放链接对话框样式
.url-container {
  display: flex;
  gap: 10px;
  align-items: center;
  
  .url-input {
    flex: 1;
  }
}

.qrcode-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  
  canvas {
    border: 1px solid #e0e0e0;
    border-radius: 4px;
  }
}
</style>

