<template>
  <div class="app-container">
    <el-button
      class="authorization-btn"
      type="primary"
      @click="is_toutiao_authorization = true"
      >头条授权</el-button
    >
    <el-button
      class="authorization-btn"
      type="primary"
      @click="guangdiantongAuthorization()"
      >广点通授权</el-button
    >
    <el-button
      class="authorization-btn"
      type="primary"
      @click="is_kuaishou_authorization = true"
      >快手授权</el-button
    >
    <el-button
      class="authorization-btn"
      type="primary"
      @click="weiboAuthorization()"
      >微博授权</el-button
    >
    <el-button
      class="authorization-btn"
      type="primary"
      @click="tiktokAuthorization()"
      >TikTok授权</el-button
    >
    <el-button class="authorization-btn" type="primary" @click="showBaiduPop"
      >百度token</el-button
    >

    <el-form :inline="true">
      <el-form-item label="产品">
        <zx-app-select
          v-model="condition.pkg"
          defaultValue=""
          :addAllOption="false"
          menuCode="game.Overview,android,thirdPkg"
          @change="_oceanEngineList"
        ></zx-app-select>
      </el-form-item>

      <el-form-item label="代理商">
        <el-select v-model="condition.agentId" clearable filterable @change="_oceanEngineList">
          <el-option
            v-for="item of agentList"
            :key="item.id"
            :label="item.agentName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="平台类型">
        <el-select v-model="condition.type" clearable filterable @change="_oceanEngineList">
          <el-option
            v-for="item of typeList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="投放方式">
        <el-select v-model="condition.agentMethod" clearable filterable @change="_oceanEngineList">
          <el-option
            v-for="item of agentMethodList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="账号id">
        <el-input v-model="condition.accountId" />
      </el-form-item>
      <el-form-item label="广告主id">
        <el-input v-model="condition.advertiserId" />
      </el-form-item>
      <el-form-item label="账号状态">
        <el-select v-model="condition.accountStatus" clearable filterable @change="_oceanEngineList">
          <el-option
            v-for="item of accountStatusList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="_oceanEngineList()">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="listLoading"
      element-loading-text="Loading"
      :data="tableData"
      highlight-current-row
      border
      style="width: 100%"
    >
      <el-table-column prop="id" label="序号" width="50px" align="center" />
      <el-table-column prop="agentName" label="代理商" width="120px" align="center" >
        <template slot-scope="scope">
          {{ scope.row.agentName }}
          <br/>
          <span v-if="scope.row.serviceAgentName != null && scope.row.serviceAgentName != undefined && scope.row.serviceAgentName !=  ''"
                style="color: #5aa1ed">服务商: {{ scope.row.serviceAgentName }}</span>

        </template>
      </el-table-column>
      <el-table-column prop="appName" label="应用名称" align="center" />
      <el-table-column prop="accountId" label="用户ID" align="center" />
      <el-table-column prop="displayName" label="用户名" align="center" />
      <el-table-column prop="email" label="邮箱" align="center" />
      <el-table-column prop="advertiserIds" label="广告主ID" align="center" />
      <el-table-column prop="typeName" label="授权平台" align="center" />
      <el-table-column label="投放方式" prop="agentMethodName" align="center" />
      <el-table-column label="token状态" prop="available" align="center">
        <template slot-scope="scope">
          <el-tag
            type="success"
            :style="
              scope.row.statusDesc.indexOf('异常') > -1
                ? 'color: red'
                : 'color: greed;'
            "
          >
            {{ scope.row.statusDesc }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="280px" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            plain
            @click="clickEditor(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="scope.row.accountUsername && scope.row.accountPassword != ' '"
            size="small"
            v-clipboard:copy="scope.row.accountUsername"
            v-clipboard:success="copyUsername"
          >
            复制账号
          </el-button>
          <el-button
            v-if="scope.row.accountPassword && scope.row.accountPassword != ' '"
            size="small"
            v-clipboard:copy="scope.row.accountPassword"
            v-clipboard:success="copyPassword"
          >
            复制密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
     <el-pagination
      background
      :total="totalNum"
      :page-size="condition.size"
      :current-page="condition.offset"
      style="text-align: right; margin-bottom: 5px"
      layout="total, prev, pager, next, sizes"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>

    <el-dialog :visible.sync="is_clickEditor" width="30vw" @close="clearForm">
      <el-form >
        <el-form-item label="请选择代理商" :label-width="formLabelWidth">
          <el-select v-model="agentId" clearable filterable placeholder="请选择代理商">
            <el-option
              v-for="item of agentList"
              :key="item.id"
              :label="item.agentName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="请选择服务代理商" :label-width="formLabelWidth">
          <el-select v-model="serviceAgentId" clearable filterable placeholder="请选择服务代理商">
            <el-option
              v-for="item of agentList"
              :key="item.id"
              :label="item.agentName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="请选择应用" :label-width="formLabelWidth">
          <el-select v-model="pkg" clearable filterable placeholder="请选择应用">
            <el-option
              v-for="item of pkgOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="投放状态" :label-width="formLabelWidth">
          <el-select v-model="putinStatus" placeholder="请选择投放状态">
            <el-option
              v-for="item of stateList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="投放方式" :label-width="formLabelWidth">
          <el-select v-model="agentMethod" placeholder="请选择投放方式">
            <el-option
              v-for="item of agentMethodList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="账号" :label-width="formLabelWidth">
          <el-input
            v-model="accountUsername" style="width: 11vw"
            placeholder="请输入账号"
          ></el-input>
        </el-form-item>

        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input
            v-model="accountPassword" style="width: 11vw"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>

        <el-form-item label="垫款周期" :label-width="formLabelWidth">
          <el-select v-model="frontTime" placeholder="请选择垫款周期">
            <el-option
              v-for="item of frontTimeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="is_clickEditor = false">取 消</el-button>
        <el-button type="primary" @click="clickEditorOk">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="is_toutiao_authorization">
      <div>
        <el-select v-model="toutiao_app_id">
          <el-option v-for="item in toutiaoSq"
                     :label="item.label"
                     :value="item.value"
            >
          </el-option>
        </el-select>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="is_toutiao_authorization = false">取 消</el-button>
        <el-button type="primary" @click="toutiaoAuthorization()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="is_gdt_authorization">
      <div>
        <el-input v-model="gdt_client_id" placeholder="请输入应用ID"></el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="is_clickEditor_gdt = false">取 消</el-button>
        <el-button type="primary" @click="clickEditorOk_gdt">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="is_kuaishou_authorization" width="280px">
      <div>
        <el-select v-model="companyType" placeholder="请选择授权公司">
          <el-option
            v-for="item of companyTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="is_kuaishou_authorization = false">取 消</el-button>
        <el-button type="primary" @click="kuaishouAuthorization"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog :visible.sync="is_baidu" width="30%">
      <el-form label-position="right" label-width="80px">
        <el-form-item label="百度token">
          <el-input v-model="popConditions.accessToken" style="width: 200px" />
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input v-model="popConditions.accountId" style="width: 200px" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="popConditions.displayName" style="width: 200px" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="popConditions.email" style="width: 200px" />
        </el-form-item>
        <el-form-item label="广告主ID">
          <el-input
            v-model="popConditions.advertiserIds"
            placeholder="请输入广告主ID(数字)"
            type="number"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="is_baidu = false">取 消</el-button>
        <el-button type="primary" @click="baiduEditor">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  oceanEngineList,
  oauthCallback,
  gdtCallback,
  kuaishouCallback,
  weiboCallback,
  tiktokCallback,
  ceanEngineUpdate,
} from "@/api/putManagement";
import { putonAgent } from "@/api/agent";
import { v2TableMappingAPI } from "@/api/report";
import { fetchCommonTable } from '@/api/common.js';

export default {
  data() {
    return {
      tableData: [],
      listLoading: false,
      parameter: "",
      is_clickEditor: false,
      is_gdt_authorization: false,
      is_toutiao_authorization: false,
      toutiao_app_id: '1722457869630464',
      is_kuaishou_authorization: false,
      formLabelWidth: '150px',
      gdt_client_id: "",

      id: 0,
      agentList: [], //代理商
      agentId: "",
      serviceAgentId: "",
      pkgOption: [], //应用名称
      pkg: "",
      putinStatus: "", // 投放状态
      accountUsername: "", // 账号
      accountPassword: "", // 密码
      frontTime:'',
      toutiaoSq: [
        {label: '投放ROI实时计算(巨量)', value: '1666179911829507' },
        {label: '千川授权-第三方(third)', value: '1722457869630464', },
        {label: 'ROI千川授权(ader)', value: '1720376928468072', },
        {label: 'ROI千川授权(agent)', value: '1722532905964669', },
      ],
      frontTimeList: [
        { label: "预付", value: 1 },
        { label: "次月中旬", value: 2 },
        { label: "次月底", value: 3 },
        { label: "次次月底", value: 4 },
      ], // 垫款周期
      stateList: [
        { label: "未设置", value: 0 },
        { label: "开户中", value: 1 },
        { label: "准备素材", value: 2 },
        { label: "计划审核", value: 3 },
        { label: "正常投放中", value: 10 },
      ], // 投放状态

      typeList: [
        { label: "头条", value: 1 },
        { label: "巨量千川", value: 44 },
        { label: "广点通", value: 2 },
        { label: "快手", value: 3 },
        { label: "微博", value: 4 },
        { label: "TikTok", value: 5 },
        { label: "网易", value: 6 },
        { label: "爱奇艺", value: 7 },
        { label: "百度", value: 8 },
        { label: "oppo", value: 9 },
      ],

      agentMethod: 1,
      agentMethodList: [
        { label: "代投", value: 1 },
        { label: "自投", value: 2 },
      ],

      condition: {
        pkg: "",
        agentId: "",
        type: "",
        agentMethod: "",
        sqlId: 1369,
        accountId: '',
        advertiserId: '',
        accountStatus: '',
        page: 1,
        size: 10
      },
      totalNum: 0,
      accountStatusList: [
        {
          label: '正常',
          value: 'normal'
        },
        {
          label: '异常',
          value: 'abnormal'
        }
      ],
      companyTypeList: [], //获取公司类型
      companyType: "", //选中的公司类行

      is_baidu: false, // 百度token 弹窗
      popConditions: {
        accessToken: "",
        accountId: "",
        displayName: "",
        email: "",
        advertiserIds: "",
      },

      // totalNums: 0, // 总条数
      // size: 50, // 每页默认50条
      // page: 1, // 当前页
    };
  },

  created() {
    this.putonAgent();
    this._oceanEngineList();
    this.pkgOption = JSON.parse(window.localStorage.getItem("pkgOption"));
  },

  mounted() {
    const state = this.getUrlParameter().state;

    // 头条授权
    if (state.indexOf("toutiao") != -1) {
      const auth_code = this.getUrlParameter().auth_code;
      let states = state.split('_')
      const obj = {
        state: states[1],
        auth_code: auth_code,
      };
      if (auth_code) {
        oauthCallback(obj).then((response) => {
          console.log(response);
          if (response.status === 200) {
            this.$message({
              message: "授权成功",
              type: "success",
            });
          }
        });
      }
    }

    // 广点通授权
    if (state.indexOf("guangdiantong") != -1) {
      const authorization_code = this.getUrlParameter().authorization_code;
      const obj = {
        state: state,
        authorization_code: authorization_code,
      };
      if (authorization_code) {
        gdtCallback(obj).then((response) => {
          console.log(response);
          if (response.status === 200) {
            this.$message({
              message: "授权成功",
              type: "success",
            });
          }
        });
      }
    }

    // 快手授权
    if (state.search(/kuaishou/) !== -1) {
      const auth_code = this.getUrlParameter().auth_code;
      const obj = {
        state: state,
        auth_code: auth_code,
      };
      if (auth_code) {
        kuaishouCallback(obj).then((response) => {
          console.log(response);
          if (response.status === 200) {
            this.$message({
              message: "授权成功",
              type: "success",
            });
          }
        });
      }
    }

    // 微博
    if (state === "weibo") {
      const code = this.getUrlParameter().code;
      const obj = {
        state: state,
        code: code,
      };
      if (code) {
        weiboCallback(obj).then((response) => {
          console.log(response);
          if (response.status === 200) {
            this.$message({
              message: "授权成功",
              type: "success",
            });
          }
        });
      }
    }

    // TikTok
    if (state === "tiktok") {
      const auth_code = this.getUrlParameter().auth_code;
      const obj = {
        state: state,
        auth_code: auth_code,
      };
      if (auth_code) {
        tiktokCallback(obj).then((response) => {
          console.log(response);
          if (response.status === 200) {
            this.$message({
              message: "授权成功",
              type: "success",
            });
          }
        });
      }
    }
  },

  methods: {
    clearForm() {
      console.log("清理表单")
    },
    handleCurrentChange(page) {
      this.condition.page = page
      this._oceanEngineList()
    },
    handleSizeChange(size) {
      this.condition.size = size
      this._oceanEngineList()
    },
    //获取代理商列表
    putonAgent: function () {
      putonAgent("get", {}).then((res) => {
        if (res.status === 200) {
          this.agentList = res.result.data;
        } else {
          alert(res.msg);
        }
        //获取公司列表
        this.getCompanyType();
      });
    },

    /**
     * 获取快手投放弹窗的下拉列表数据
     */
    getCompanyType() {
      v2TableMappingAPI({ sqlId: 1303 }).then((res) => {
        this.companyTypeList = res.result.data;
      });
    },

    //编辑
    clickEditor: function (e) {
      console.log(e);
      this.is_clickEditor = true;
      this.id = e.id;
      this.agentId = e.agentId;
      this.pkg = e.pkg;
      this.putinStatus = e.putinStatus;
      this.agentMethod = e.agentMethod;
      this.accountUsername = e.accountUsername;
      this.accountPassword = e.accountPassword;
      this.frontTime = e.frontTime;
      this.serviceAgentId = e.serviceAgentId;
    },

    //确定
    clickEditorOk: function () {
      if (this.agentId === "") {
        this.$message({
          message: "请选择代理商",
          type: "warning",
        });
        return null;
      }

      if (this.pkg === "") {
        this.$message({
          message: "请选择应用",
          type: "warning",
        });
        return null;
      }

      ceanEngineUpdate({
        id: this.id,
        agentId: this.agentId,
        serviceAgentId: this.serviceAgentId,
        pkg: this.pkg,
        putinStatus: this.putinStatus,
        agentMethod: this.agentMethod,
        accountUsername: this.accountUsername,
        accountPassword: this.accountPassword,
        frontTime : this.frontTime
      }).then((res) => {
        this.listLoading = false;
        this.is_clickEditor = false;
        if (res.status === 200) {
          this._oceanEngineList();
          this.$message({
            message: "编辑成功",
            type: "success",
          });
        } else {
          alert(res.msg);
        }
      });

    },

    clickEditorOk_gdt: function () {
      const url =
        window.location.protocol +
        "//" +
        window.location.host +
        "/putManagement/putManagement";
      window.location.href =
        "https://developers.e.qq.com/oauth/authorize?client_id=" +
        this.gdt_client_id +
        "&state=guangdiantong_" +
        this.gdt_client_id +
        "&redirect_uri=" +
        url;
    },

    // 复制账号
    copyUsername() {
      this.$message({
        message: "复制成功",
        type: "success",
      });
    },

    // 复制密码
    copyPassword() {
      this.$message({
        message: "复制成功",
        type: "success",
      });
    },

    _oceanEngineList() {
      // if(this.condition.pkg == '' && this.condition.accountId == '' && this.condition.advertiserId == '') {
      //   this.$message({
      //     message: "请选择应用",
      //     type: "error",
      //   });
      //   return false;
      // }

      this.listLoading = true;
      setTimeout(() => {
        try {
          fetchCommonTable({
            ...this.condition,
          }).then((response) => {
            console.log(response);
            this.listLoading = false;
            this.tableData = response.result.data;
            // console.log(112233, this.tableData);
            // this.totalNums = this.tableData.length;
          });
        } catch (error) {
          console.log(error);
        }
      }, 300);
      this.getAuthTotal()
    },

    getAuthTotal() {
      let param = {...this.condition}
      param.sqlId = 1425
      fetchCommonTable({
        ...param,
      }).then((response) => {
        console.log(response);
        this.totalNum = response.result.data[0].total;
        // console.log(112233, this.tableData);
        // this.totalNums = this.tableData.length;
      });
    },

    // **********************************************************************************************************************

    // 头条授权
    toutiaoAuthorization() {
      // eslint-disable-next-line no-unused-vars

      let oauthUrl = 'http://ad.oceanengine.com/openapi/audit/oauth.html'
      // 1720376928468072
      if (this.toutiao_app_id === '1720376928468072' || this.toutiao_app_id === '1722457869630464' || this.toutiao_app_id === '1722532905964669') {
        oauthUrl = 'https://qianchuan.jinritemai.com/openapi/qc/audit/oauth.html'
      }
      const url =
        window.location.protocol +
        "//" +
        window.location.host +
        "/putManagement/putManagement";
      window.location.href =
        `${oauthUrl}?app_id=${this.toutiao_app_id}&state=toutiao_${this.toutiao_app_id}&redirect_uri=` +
        url;
    },

    // 广点通授权
    guangdiantongAuthorization() {
      // eslint-disable-next-line no-unused-vars
      this.is_gdt_authorization = true;
    },

    // 快手授权
    kuaishouAuthorization() {
      if (!this.companyType || this.companyType == "") {
        this.$message.warning("请先选择授权主体！");
        return;
      }
      let appId = "";
      if (this.companyType === "zxhl") {
        appId = "165893232";
      } else if (this.companyType === "ym") {
        appId = "165893236";
      } else if (this.companyType === "zcwh") {
        appId = "165894441";
      }else if (this.companyType === "zxbw") {
        appId = "165895557";
      } else {
        this.$message.warning("该主体不存在appId!");
        return;
      }
      // eslint-disable-next-line no-unused-vars
      const url =
        window.location.protocol +
        "//" +
        window.location.host +
        "/putManagement/putManagement";
      window.location.href =
        "https://ad.e.kuaishou.com/#/openapi/oauth?app_id=" +
        appId +
        "&state=kuaishou_" +
        this.companyType +
        "&scope=%5B%22report_service%22%2C%22ad_query%22%2C%22ad_manage%22%2C%22account_service%22%5D&redirect_uri=" +
        url;
    },

    // 微博授权
    weiboAuthorization() {
      // eslint-disable-next-line no-unused-vars
      const url =
        window.location.protocol +
        "//" +
        window.location.host +
        "/putManagement/putManagement";
      window.location.href =
        "https://api.biz.weibo.com/oauth/authorize?client_id=202008217739318100&&response_type=code&state=weibo&response_type=code&scope=ads_read&redirect_uri=" +
        encodeURI(url);
    },

    // TikTok授权
    tiktokAuthorization() {
      // eslint-disable-next-line no-unused-vars
      const url =
        window.location.protocol +
        "//" +
        window.location.host +
        "/putManagement/putManagement";
      window.location.href =
        "https://ads.tiktok.com/marketing_api/auth?app_id=6870097834574610433&state=tiktok&rid=5auyavoxfv3&redirect_uri=" +
        encodeURI(url);
    },

    // 获取链接里的参数
    getUrlParameter() {
      var url = window.location.href;
      var i = url.indexOf("?");
      if (i === -1) {
        return {};
      }
      var querystr = url.substr(i + 1);
      var arr1 = querystr.split("&");
      // eslint-disable-next-line no-new-object
      var arr2 = new Object();
      for (i in arr1) {
        var ta = arr1[i].split("=");
        arr2[ta[0]] = ta[1];
      }
      return arr2;
    },

    // 百度token 设置
    baiduEditor() {
      let params = {
        accessToken: this.popConditions.accessToken.replace(/^\s+|\s+$/g, ""),
        accountId: this.popConditions.accountId.replace(/^\s+|\s+$/g, ""),
        displayName: this.popConditions.displayName.replace(/^\s+|\s+$/g, ""),
        email: this.popConditions.email.replace(/^\s+|\s+$/g, ""),
        advertiserIds: JSON.stringify([
          this.popConditions.advertiserIds.replace(/^\s+|\s+$/g, ""),
        ]),
        type: 8,
      };
      if (
        Object.keys(params).find(
          (key) => params[key] == "" || params[key] == null
        )
      ) {
        this.$message.warning("请将数据填写完整!");
        return;
      }
      ceanEngineUpdate(params).then((res) => {
        this.is_baidu = false;
        this.popConditions.accessToken = "";
        if (res.status == 200) {
          this._oceanEngineList();
          this.$message.success("编辑成功");
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    // 百度弹窗
    showBaiduPop() {
      this.is_baidu = true;
      Object.keys(this.popConditions).forEach((key) => {
        this.popConditions[key] = "";
      });
    },

    // handleSizeChange(val) {
    //   console.log(`每页 ${val} 条`);
    //   this.size = val;
    // },
    // handleCurrentChange(val) {
    //   console.log("aaa", val);
    //   this.page = val;
    // },
  },
};
</script>

<style scoped>
.authorization-btn {
  margin-bottom: 20px;
}
</style>
