<template>
  <div class="abtestIndex">
    <el-form :inline="true" :model="searchForm" size="small" ref="searchForm" class="demo-form-inline">
      <el-form-item label="测试名称">
        <el-input v-model="searchForm.name" name="searchForm.name" placeholder="请输入测试名称" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.state" filterable placeholder="请选择状态" clearable>
          <el-option label="生效" :value="1" />
          <el-option label="失效" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="init()">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="reset()">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="infoShow = true">新增</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="tableData">
      <el-table-column label="名称" prop="name" align="center"></el-table-column>
      <el-table-column label="描述" prop="content" align="center"></el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch :value="scope.row.state" :active-value="1" :inactive-value="0"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center">
        <template slot-scope="scope">
          <span>{{getTimeStr(scope.row.beginTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center">
        <template slot-scope="scope">
          <span>{{getTimeStr(scope.row.endTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button v-if="returnTime(scope.row.beginTime)===0" size="mini" type="text" icon="el-icon-edit" @click="editClick(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-set-up" @click="copy(scope.row)">复制</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="removeInfo(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="mt10" v-show="total>0" background layout="total, sizes, prev, pager, next, jumper" :total="total" :current-page="searchForm.pageNo" :page-size="searchForm.pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
    <!-- 新增编辑弹窗 -->
    <el-dialog @close="dialogClose" class="dialog" :title="editNum ===0?'新建测试':'编辑测试'" :visible.sync="infoShow" append-to-body lock-scroll :close-on-click-modal="false">
      <el-form :model="infoForm" :rules="rules" style="width:60%" ref="ruleForm" label-width="100px">
        <el-form-item label="测试名称" prop="name">
          <el-input v-model="infoForm.name" />
        </el-form-item>
        <el-form-item label="测试描述" prop="content">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model="infoForm.content" />
        </el-form-item>
        <el-form-item label="生效时间" required>
          <el-col :span="11">
            <el-form-item prop="beginTime">
              <el-date-picker type="datetime" placeholder="开始日期" v-model="infoForm.beginTime" style="width:100%"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-date-picker type="datetime" placeholder="结束日期" v-model="infoForm.endTime" style="width:100%"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="渠道选择" prop="channelKey">
          <el-select v-model="channelVal" multiple clearable filterable placeholder="请选择" @change="channelChange">
            <el-option v-for="item in channelList" :key="item.channelKey" :label="item.channelName" :value="item.channelKey">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型选择" prop="typeDictId">
          <el-select v-model="infoForm.typeDictId" clearable filterable placeholder="请选择">
            <el-option v-for="item in typeList" :key="item.id" :label="item.typeName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-switch v-model="infoForm.state" active-text="生效" :active-value="1" inactive-text="无效" :inactive-value="0" />
        </el-form-item>
        <div v-if="isEdit === true" style="margin-bottom: 20px">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="addTab">新增对照组</el-button>
        </div>
        <el-tabs v-model="editableTabsValue" type="card" closable @tab-remove="removeTab">
          <el-tab-pane v-for="(item, index) in infoForm.groupData" :key="item.groupName" :label="item.groupName" :name="item.groupName">
            <div>
              <el-form-item label="组别名称">
                <el-input v-model="item.name" />
              </el-form-item>
              <el-form-item label="组别描述">
                <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model="item.content" />
              </el-form-item>
              <el-form-item label="分流占比">
                <el-input v-model="item.flowPercent" placeholder="请输入小数" />
                <div style="color: red">请输入小数如0.5，各组占比之和为1</div>
              </el-form-item>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="infoShow = false">取 消</el-button>
        <el-button type="primary" @click="editNum===0?createTest():editTest()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { secondChannel, abtestList, removeAbtest, typeListApi, createAbtest, editAbtest } from './ABtestApi'
export default {
  name: "abtestIndex",
  data () {
    return {
      //  搜索相关内容
      searchForm: {
        name: null,
        state: null,
        pageNo: 1,
        pageSize: 10,
      },
      // 表格数据
      loading: true,
      tableData: [],
      total: 0,
      infoShow: false,
      infoForm: {
        name: "",
        content: "",
        beginTime: "",
        endTime: "",
        channelKey: "",
        typeDictId: "",
        state: 0,
        groupData: [
          {
            "content": "",
            "flowPercent": 0,
            "groupName": "对照组",
            "name": "对照组",
            "state": 1,
            "strategyId": 0,
            "type": 0
          },
          {
            "content": "",
            "flowPercent": 0,
            "groupName": "控制组1",
            "name": "控制组1",
            "state": 1,
            "strategyId": 0,
            "type": 1
          }
        ]
      },
      channelList: [],   //渠道列表
      channelVal: [],  //渠道key
      typeList: [],  // 类型列表
      // 表单规则
      rules: {
        name: [{ required: true, message: "请填写名称", trigger: "blur" }],
        content: [{ required: true, message: "请填写描述", trigger: "blur" }],
        beginTime: [{ type: 'date', required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [{ type: 'date', required: true, message: '请选择结束日期', trigger: 'change' }],
        channelKey: [{ required: true, message: "请绑定渠道", trigger: 'change' }],
        typeDictId: [{ required: true, message: "请选择测试类型", trigger: 'change' }],
      },
      // 标签页
      editableTabsValue: "对照组",
      tabIndex: 1,
      thisIndex: 0,
      isEdit: true,
      // 修改新增/编辑标识
      editNum: 0
    };
  },
  mounted () {
    this.init();  // 获取abtest数据
    this.getSecondChannel() // 获取二级渠道列表数据
    this.getTypeList()    //获取类型选择
  },
  methods: {

    channelChange (e) {
      if (e) {
        this.infoForm.channelKey = this.channelVal.join(',')
      }
    },
    // 时间格式转换
    getTimeStr (timeStamp) {
      var now = new Date(timeStamp),
        y = now.getFullYear(),
        m = ("0" + (now.getMonth() + 1)).slice(-2),
        d = ("0" + now.getDate()).slice(-2);
      return y + "-" + m + "-" + d + " " + now.toTimeString().substr(0, 8);
    },
    // 判定当前时间是否大于测试开始时间  大于等于返回1  小于返回0
    returnTime (date) {
      let nowTime = new Date().getTime();
      let dateTime = new Date(date).getTime();
      if (nowTime >= dateTime) {
        return 1
      } else {
        return 0
      }
    },
    // 获取列表
    init () {
      this.loading = true
      abtestList(this.searchForm).then(res => {
        this.tableData = res.data.list;
        this.total = res.data.total;
        this.loading = false
      })
    },
    // 重置
    reset () {
      this.searchForm = {
        name: null,
        state: null,
        pageNo: 1,
        pageSize: 10,
      },
        this.init();
    },
    // 列表选择每页数量
    handleSizeChange (val) {
      this.searchForm.pageNo = 1
      this.searchForm.pageSize = val
      this.init();
    },
    // 列表选择当前页
    handleCurrentChange (val) {
      this.searchForm.pageNo = val
      this.init();
    },
    //获取二级渠道列表
    getSecondChannel () {
      secondChannel({ pageNo: 1, pageSize: 99 }).then(res => {
        this.channelList = res.data.list
      })
    },
    // 获取类型列表
    getTypeList () {
      typeListApi({ pageNo: 1, pageSize: 99 }).then(res => {
        this.typeList = res.data.list
      })
    },
    // 新增控制组
    addTab () {
      if (this.infoForm.groupData.length <= 4) {
        let num = this.infoForm.groupData.length;
        let name = "控制组" + num
        this.infoForm.groupData.push({
          "content": "",
          "flowPercent": null,
          "groupName": name,
          "name": name,
          "state": 1,
          "strategyId": null,
          "type": 1
        });
        this.editableTabsValue = name;
      } else {
        this.$message({
          message: '对照组最多4组',
          type: 'warning',
          duration: 3000,
          offset: 360
        })
      }
    },
    // 删除对照组
    removeTab (targetName) {
      if (targetName !== "对照组") {
        let tabs = this.infoForm.groupData;
        let item = tabs.find(val => {
          return val.groupName === targetName
        })
        tabs.splice(tabs.indexOf(item), 1)
      } else {
        this.$message({
          message: "对照组不可删除",
          type: "warning",
          duration: 3000,
          offset: 360,
        });
      }
      this.editableTabsValue = '对照组'
    },
    // 新建abtest
    createTest () {
      console.log(this.infoForm)
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          createAbtest(this.infoForm).then(res => {
            this.$message.success('新增成功!')
            this.infoShow = false
            this.init()
          })
        }
      });
    },
    // 删除数据
    removeInfo (id) {
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        removeAbtest({ ids: id }).then(res => {
          this.init()
        })
      })
    },
    // 编辑数据
    editClick (item) {
      this.channelVal = item.channelKey.split(',')
      this.editNum = 1
      this.infoShow = true
      let { beginTime, channelKey, content, endTime, groupData, id, name, state, typeDictId } = item
      this.infoForm = { beginTime, channelKey, content, endTime, groupData, id, name, state, typeDictId }
    },
    editTest () {
      this.$confirm("此操作将修改该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.infoForm.beginTime = new Date(this.infoForm.beginTime).getTime()
        this.infoForm.endTime = new Date(this.infoForm.endTime).getTime()
        editAbtest(this.infoForm).then(res => {
          this.$message.success('修改成功!')
          this.infoShow = false
          this.init()
        })
      })
    },
    //复制数据
    copy (item) {
      this.channelVal = item.channelKey.split(',')
      this.infoShow = true
      let { beginTime, channelKey, content, endTime, groupData, name, state, typeDictId } = item
      name = name + '副本'
      this.infoForm = { beginTime, channelKey, content, endTime, groupData, name, state, typeDictId }

    },
    // 弹窗关闭清空值
    dialogClose () {
      this.channelVal = [];
      this.editNum = 0
      this.infoForm = {
        name: "",
        content: "",
        beginTime: "",
        endTime: "",
        channelKey: "",
        typeDictId: "",
        state: 0,
        groupData: [
          {
            "content": "",
            "flowPercent": 0,
            "groupName": "对照组",
            "name": "对照组",
            "state": 1,
            "strategyId": 0,
            "type": 0
          },
          {
            "content": "",
            "flowPercent": 0,
            "groupName": "控制组1",
            "name": "控制组1",
            "state": 1,
            "strategyId": 0,
            "type": 1
          }
        ]
      }
    }
  },
};
</script>
<style scoped>
.dialog /deep/ .el-dialog {
  height: 85vh;
  overflow: auto;
}
</style>
<style lang="scss">
.abtestIndex {
  padding: 20px;
  box-sizing: border-box;

  // .searchBox {
  //   background-color: #fff;
  //   border-radius: 4px;
  //   box-shadow: #bfbfbf 0 0 2px;
  //   height: unset !important;
  //   padding: 10px 10px;

  //   form {
  //     margin: auto;

  //     .el-form-item {
  //       margin: 5px 5px;
  //     }
  //   }
  // }

  // .tableBox {
  //   margin-top: 10px;
  //   background-color: #fff;
  //   border-radius: 4px;
  //   box-shadow: #bfbfbf 0 0 2px;

  //   .block {
  //     .el-pagination {
  //       margin-top: 30px;
  //       float: right;
  //     }
  //   }
  // }
}
</style>
