<template>
  <div class="app-container">
    <!-- 筛选 -->
    <el-form inline>
      <el-form-item>
        <el-button type="primary" @click="handleActiveAdd"
          >添加广告配置</el-button
        >
      </el-form-item>

      <el-form-item label="应用选择">
        <el-select
          v-model="form.pkg"
          placeholder="应用选择"
          @change="_fetchAdvCfgList"
          filterable
          clearable
        >
          <el-option
            v-for="item in pkgList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="匹配ID">
        <el-input v-model="conditionMatchId" style="200px"></el-input>
      </el-form-item>

      <el-form-item label="匹配ID类型">
        <el-select
          v-model="form.matchIdType"
          placeholder="匹配ID类型"
          @change="_fetchAdvCfgList"
          filterable
          clearable
        >
          <el-option
            v-for="item in matchIdTypeOptions"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="上报类型">
        <el-select
          v-model="form.reportType"
          placeholder="上报类型选择"
          @change="_fetchAdvCfgList"
          filterable
          clearable
        >
          <el-option
            v-for="item in reportTypeOptions"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="统计方式">
        <el-select
          v-model="form.statMethod"
          placeholder="统计方式选择"
          @change="_fetchAdvCfgList"
          filterable
          clearable
        >
          <el-option
            v-for="item in statMethodOptions"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

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

      <el-form-item>
        <el-popconfirm
          confirmButtonText="好的"
          cancelButtonText="不用了"
          icon="el-icon-info"
          iconColor="red"
          @onConfirm="_asyncCache"
          title="确定同步缓存？"
        >
          <el-button type="warn" slot="reference"> 同步缓存 </el-button>
        </el-popconfirm></el-form-item
      >
    </el-form>

    <!-- 表格 -->
    <el-table v-loading="listLoading" :data="configList" style="width: 100%">
      <el-table-column label="开关" width="100px" fixed>
        <template slot-scope="scope">
          <img
            v-if="scope.row.status == 1"
            class="On-img"
            src="@/assets/On.png"
            alt=""
            @click="onClose(scope.row.id)"
          />
          <img
            v-else
            class="Off-img"
            src="@/assets/Off.png"
            alt=""
            @click="onClose(scope.row.id)"
          />
        </template>
      </el-table-column>
      <el-table-column label="匹配ID类型" prop="matchIdType" fixed>
        <template slot-scope="props">
          <el-tag type="primary" v-if="props.row.matchIdType === 1">
            广告主
          </el-tag>
          <el-tag type="warning" v-else-if="props.row.matchIdType === 2">
            广告组
          </el-tag>
          <el-tag type="success" v-else-if="props.row.matchIdType === 3">
            计划
          </el-tag>
          <el-tag type="success" v-else-if="props.row.matchIdType === 4">
            包
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="匹配ID" prop="matchId" fixed />
      <el-table-column label="应用名" prop="appName" />
      <el-table-column label="统计方式" min-width="150">
        <template slot-scope="scope">
          <template v-if="scope.row.statMethod == 'accumulate'">
            <el-tag>事件累计</el-tag>
            <el-tag>{{ "事件:" + scope.row.event }} </el-tag>
            <el-tag>{{ "累计次数:" + scope.row.times }}</el-tag>
          </template>
          <template v-else-if="scope.row.statMethod == 'cpm'">
            <el-tag type="success">ecpm</el-tag>
            <el-tag type="success">{{ "均价:" + scope.row.ecpm }}</el-tag>
            <el-tag type="success">{{
              "ecpm视频数:" + scope.row.ecpmVideoNum
            }}</el-tag>
          </template>
          <template v-else-if="scope.row.statMethod == 'mix'">
            <el-tag type="warning">混合</el-tag>
            <el-tag>{{ "事件:" + scope.row.event }} </el-tag>
            <el-tag>{{ "累计次数:" + scope.row.times }}</el-tag>
            <el-tag type="success">{{ "均价:" + scope.row.ecpm }}</el-tag>
            <el-tag type="success">{{
              "ecpm视频数:" + scope.row.ecpmVideoNum
            }}</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="上报类型" prop="reportType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.reportType == 'keyword'">关键行为</el-tag>
          <el-tag v-else-if="scope.row.reportType == 'register'">注册</el-tag>
          <el-tag type="success" v-else-if="scope.row.reportType == 'pay'"
            >付费</el-tag
          >
          <div v-else-if="scope.row.reportType == 'retain'">次留</div>

          <el-tag type="success" v-if="scope.row.reportTimeMethod == 'day'"
            >天</el-tag
          >
          <template v-else-if="scope.row.reportTimeMethod == 'nextHour'">
            <el-tag type="success">顺延小时</el-tag>
            <el-tag type="success">小时数:{{ scope.row.reportHour }}</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="回传比例" prop="ratio" />
      <el-table-column label="当日转化数" prop="convertNum" />
      <el-table-column label="操作" min-width="100">
        <template slot-scope="scope">
          <el-button type="primary" @click="editForm(scope.row)">
            编辑
          </el-button>

          <el-popconfirm
            confirmButtonText="好的"
            cancelButtonText="不用了"
            icon="el-icon-info"
            iconColor="red"
            @onConfirm="delCfg(scope.row.id)"
            title="确定删除吗？"
          >
            <el-button type="danger" slot="reference"> 删除 </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      :before-close="clearForm"
      width="30%"
    >
      <el-form :inline="false">
        <el-form-item :label-width="formLabelWidth" label="匹配ID类型">
          <el-select v-model="form.matchIdType" filterable clearable>
            <el-option
              v-for="item in matchIdTypeOptions"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="formUpdateModel"
          :label-width="formLabelWidth"
          label="匹配ID"
        >
          <el-input v-model="form.matchId" autocomplete="off" disabled />
        </el-form-item>

        <el-form-item
          v-if="!formUpdateModel && form.matchIdType !== 4"
          label="添加匹配ID"
          :label-width="formLabelWidth"
        >
          <el-tag
            :key="tag"
            v-for="tag in idGroups"
            closable
            :disable-transitions="false"
            @close="closeTag(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
            style="width: 200px"
          >
          </el-input>
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput"
          >
            + 添加
          </el-button>
        </el-form-item>

        <el-form-item label="应用" :label-width="formLabelWidth">
          <el-select v-model="form.pkg" filterable>
            <el-option
              v-for="item in pkgList"
              :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="form.reportType"
            placeholder="上报类型选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in reportTypeOptions"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="统计方式" :label-width="formLabelWidth">
          <el-select
            v-model="form.statMethod"
            placeholder="统计方式选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in statMethodOptions"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <template v-if="form.statMethod == 'cpm' || form.statMethod == 'mix'">
          <el-form-item label="ecpm" :label-width="formLabelWidth">
            <el-input-number
              v-model="form.ecpm"
              :precision="2"
              :step="10"
            ></el-input-number>
          </el-form-item>

          <el-form-item label="ecpm所需视频" :label-width="formLabelWidth">
            <el-input-number
              v-model="form.ecpmVideoNum"
              :precision="0"
              autocomplete="off"
              :step="1"
              :min="0"
              style="width: 200px"
            ></el-input-number>
          </el-form-item>
        </template>

        <template
          v-if="form.statMethod == 'accumulate' || form.statMethod == 'mix'"
        >
          <el-form-item label="上报触发事件" :label-width="formLabelWidth">
            <el-input v-model="form.event"></el-input>
          </el-form-item>

          <el-form-item label="触发次数" :label-width="formLabelWidth">
            <el-input-number
              v-model="form.times"
              :precision="0"
              autocomplete="off"
              :step="1"
              :min="0"
              style="width: 200px"
            ></el-input-number>
          </el-form-item>
        </template>

        <el-form-item :label-width="formLabelWidth" label="上报时间">
          <el-select
            v-model="form.reportTimeMethod"
            placeholder="上报时间选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in reportTimeMethod"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <template v-if="form.reportTimeMethod == 'nextHour'">
          <el-form-item label="小时数" :label-width="formLabelWidth">
            <el-input-number
              v-model="form.reportHour"
              :precision="0"
              autocomplete="off"
              :step="1"
              :min="1"
              :max="24"
              style="width: 200px"
            ></el-input-number>
          </el-form-item>
        </template>

        <el-form-item :label-width="formLabelWidth" label="上报率">
          <el-input-number
            v-model="form.ratio"
            :precision="0"
            autocomplete="off"
            :step="10"
            :min="0"
            :max="100"
            style="width: 200px"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="!addCanClick" type="primary" @click="saveEditor"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageObj.size"
      layout="total, prev, pager, next, sizes"
      :total="pageObj.total"
      background
    >
    </el-pagination>
  </div>
</template>
<script>
import {
  fetchAdvCfgList,
  updateOrAddList,
  switchData,
  deletePutin,
  asyncCache,
} from "@/api/report";

import { getSelectApps } from "@/api/cloud";

import {
  matchIdType,
  reportType,
  statMethod,
  reportTimeMethod,
} from "@/const/const";

export default {
  data() {
    return {
      addCanClick: true,
      formUpdateModel: true,
      inputVisible: false,
      inputValue: "",
      formLabelWidth: "120px",
      listLoading: false,
      dialogFormVisible: false,
      configList: [],
      editingKey: "",
      pkgList: "",
      pkg: "",
      count: 2,
      idGroups: [],
      conditionMatchId: "",
      form: {
        id: "",
        matchIdType: "",
        matchId: "",
        pkg: "",
        reportType: "",
        statMethod: "",
        times: null,
        event: null,
        ecpm: 200,
        ecpmVideoNum: 15,
        ratio: 100,
        status: null, // 开关 1
        reportTimeMethod: "", // 上报时间选择
        reportHour: 24,
      },
      pageObj: {
        page: 1,
        size: 20,
        total: 0,
      },
      // 常量选择
      matchIdTypeOptions: matchIdType, // 匹配ID类型参数
      reportTypeOptions: reportType, // 上报类型参数
      statMethodOptions: statMethod, // 统计类型参数
      reportTimeMethod: reportTimeMethod, // 上报时间
      is_save: false, // 允许保存配置
    };
  },
  created() {
    this._fetchAdvCfgList();
    this._fetchAppList();
  },
  methods: {
    // 网络请求 获取app列表
    _fetchAppList() {
      const params = {
        platformId: 5,
        menuCode: "game.Overview",
      };
      getSelectApps(params).then((response) => {
        if (response.result.data[0].value == "") {
          response.result.data.splice(0, 1);
        }
        this.pkgList = response.result.data;
      });
    },

    // 网络请求 获取表格数据
    _fetchAdvCfgList() {
      this.listLoading = true;
      let params = {
        pkg: this.form.pkg,
        matchIdType: this.form.matchIdType,
        reportType: this.form.reportType,
        statMethod: this.form.statMethod,
        page: this.pageObj.page,
        size: this.pageObj.size,
        matchId: this.conditionMatchId,
      };
      fetchAdvCfgList(params).then((resp) => {
        this.listLoading = false;
        this.configList = resp.result.data.content;
        this.pageObj.total = resp.result.data.total;
        if (this.pageObj.page * this.pageObj.size > this.pageObj.total) {
          this.pageObj.page = 1;
        }
      });
    },

    // 网络请求 新增或更新
    _updateOrAddList() {
      let params = {
        idGroups: this.idGroups,
        pkg: this.form.pkg,
        matchIdType: this.form.matchIdType,
        reportType: this.form.reportType,
        statMethod: this.form.statMethod,
        ecpm: this.form.ecpm,
        ecpmVideoNum: this.form.ecpmVideoNum,
        event: this.form.event,
        times: this.form.times,
        ratio: this.form.ratio,
        reportTimeMethod: this.form.reportTimeMethod,
        reportHour: this.form.reportHour,
      };
      if (this.form.statMethod == "cpm") {
        delete params.times;
        delete params.event;
      } else if (this.form.statMethod == "accumulate") {
        delete params.ecpm;
        delete params.ecpmVideoNum;
      }
      if (this.formUpdateModel) {
        params.id = this.form.id;
        params.matchId = this.form.matchId;
        delete params.idGroups;
      }
      if (this.form.reportTimeMethod == "day") {
        delete params.reportHour;
      }
      return updateOrAddList(params);
    },

    // 网络请求 控制切换按钮 传入id 发送
    opConfigSwitch(id) {
      switchData({ id: id }).then((resp) => {
        if (resp.status === 200) {
          this.$message.success("操作成功");
        } else {
          this.$message.error("操作失败");
        }
        this._fetchAdvCfgList();
      });
    },

    // 网络请求 删除数据
    delCfg(id) {
      deletePutin({ id: id }).then((resp) => {
        if (resp.status === 200) {
          this.$message.success("删除成功");
          this._fetchAdvCfgList();
        } else {
          this.$message.error("删除失败");
        }
      });
    },

    // 网络请求 同步缓存
    _asyncCache() {
      asyncCache().then((res) => {
        if (res.status == 200) {
          this.$message.success("同步缓存成功！");
        } else {
          this.$message.error(res.message);
        }
      });
    },

    // 表单中的tag标签值
    closeTag(tag) {
      this.idGroups.splice(this.idGroups.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 添加匹配id 将值放入idGroups数组中
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.idGroups.push(inputValue.trim());
      }
      this.inputVisible = false;
      this.inputValue = "";
    },

    // 清空表单数据 二次进入时为空的表单
    clearForm() {
      this.form.id = "";
      this.form.matchIdType = "";
      this.form.reportType = "";
      this.form.statMethod = "";
      this.form.matchId = "";
      this.idGroups = [];
      this.dialogFormVisible = false;
    },

    // 编辑表单 回传数据
    editForm(row) {
      this.formUpdateModel = true;
      this.dialogFormVisible = true;
      this.form.id = row.id;
      let data = { ...row };
      this.form = data;
    },

    onClose(key) {
      this.opConfigSwitch(key);
    },

    // 添加
    handleActiveAdd() {
      this.clearForm();
      this.formUpdateModel = false;
      this.dialogFormVisible = true;
    },

    // 编辑保存
    saveEditor() {
      // 防止重复点击禁用
      if (this.form.matchIdType === 4) {
        this.idGroups = [this.form.pkg];
      }
      // this.addCanClick = false;

      this.proving();

      if (this.is_save) {
        this._updateOrAddList().then((resp) => {
          this.dialogFormVisible = false;
          this.form.matchIdType = "";
          this.form.reportType = "";
          this.form.statMethod = "";
          // this.addCanClick = true;
          if (resp.status === 200) {
            this.$message.info("保存成功");
            this._fetchAdvCfgList();
          } else {
            this.$message.error(resp.message);
          }
        });
      }
    },

    // 保存时做验证
    proving() {
      console.log(this.idGroups);
      var statMethod = this.form.statMethod;
      if (statMethod == "" || statMethod == null) {
        this.$message.warning("请选择统计方式！");
        return (this.is_save = false);
      }
      if (this.form.pkg == "" || this.form.pkg == null) {
        this.$message.warning("请选择包名！");
        return (this.is_save = false);
      }
      if (this.form.matchIdType == "" || this.form.matchIdType == null) {
        this.$message.warning("请选择匹配id类型！");
        return (this.is_save = false);
      }
      if (!this.formUpdateModel) {
        if (this.idGroups == [] || this.idGroups.length == 0) {
          this.$message.warning("请输入匹配id！");
          return (this.is_save = false);
        }
      }
      if (this.form.reportType == "" || this.form.reportType == null) {
        this.$message.warning("请选择上报类型！");
        return (this.is_save = false);
      }
      if (
        this.form.reportTimeMethod == "" ||
        this.form.reportTimeMethod == null
      ) {
        this.$message.warning("请选择上报时间！");
        return (this.is_save = false);
      }
      this.is_save = true;
      switch (statMethod) {
        case "cpm":
          if (this.form.ecpm <= 0) {
            this.$message.warning("ecpm值必须大于0！");
            return (this.is_save = false);
          } else if (this.form.ecpmVideoNum <= 0) {
            this.$message.warning("ecpm所需视频值必须大于0！");
            return (this.is_save = false);
          } else {
            this.is_save = true;
          }
          break;
        case "accumulate":
          if (this.form.times <= 0) {
            this.$message.warning("触发次数必须大于0！");
            return (this.is_save = false);
          } else if (
            this.form.event.replace(/^\s*|\s*$/g, "") == "" ||
            this.form.event.replace(/^\s*|\s*$/g, "") == null
          ) {
            this.$message.warning("上报触发事件名不能为空！");
            return (this.is_save = false);
          } else {
            this.form.event = this.form.event.replace(/^\s+|\s+$/g, "");
            this.is_save = true;
          }
          break;
        case "mix": {
          if (!this.form.times > 0) {
            this.$message.warning("触发次数必须大于0！");
            return (this.is_save = false);
          } else if (this.form.ecpm <= 0) {
            this.$message.warning("ecpm值必须大于0！");
            return (this.is_save = false);
          } else if (this.form.event == "" || this.form.event == null) {
            this.$message.warning("上报触发事件名不能为空！");
            return (this.is_save = false);
          } else {
            this.form.event = this.form.event.trim();
            return (this.is_save = true);
          }
        }
      }
    },

    // 分页
    handleSizeChange(val) {
      this.pageObj.size = val;
      this._fetchAdvCfgList();
    },

    handleCurrentChange(val) {
      this.pageObj.page = val;
      this._fetchAdvCfgList();
    },
  },
};
</script>
<style lang="css">
.editable-cell {
  position: relative;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 24px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  line-height: 18px;
  display: none;
}

.editable-cell-icon-check {
  line-height: 28px;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.editable-add-btn {
  margin-bottom: 8px;
}

.editable-row-operations a {
  margin-right: 8px;
}
.On-img,
.Off-img {
  width: 60px;
  margin-top: 5px;
}
</style>
