<template>
  <div>
    <el-container>
      <el-main>
        <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
          <el-form-item label="测试名称" prop="name">
            <el-input style="width: 40%" v-model="form.name" />
          </el-form-item>
          <el-form-item label="测试描述" prop="content">
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="form.content" style="width: 40%" />
          </el-form-item>
          <el-form-item label="生效时间" prop="timeBox">
            <el-date-picker v-model="timeBox" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change=handleChangeTime>
            </el-date-picker>
          </el-form-item>
          <el-form-item label="渠道选择" prop="channelKey">
            <el-select v-model="channelBox" style="width: 40%" multiple clearable filterable placeholder="请选择" @change=handleChangeChannel>
              <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="form.typeDictId" pr style="width: 40%" 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="状态">
            <el-switch style="width: 300px" v-model="form.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" @click="addTab(editableTabsValue)">新增分组</el-button>
          </div>
          <el-tabs v-model="editableTabsValue" type="card" closable @tab-remove="removeTab" @tab-click="clickTab">
            <el-tab-pane v-for="(item, index) in form.groupData" :key='item.groupName' :label="item.groupName" :name='item.groupName'>
              <div>
                <el-form-item label="组别名称" prop="name">
                  <el-input style="width: 40%" v-model="item.name" />
                </el-form-item>
                <el-form-item label="组别描述" prop="content">
                  <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="item.content" style="width: 40%" />
                </el-form-item>

                <el-form-item label="选择策略">
                  <el-select v-model="item.strategyId" style="width: 40%" clearable filterable placeholder="请选择">
                    <el-option v-for="item in strategyList" :key="item.id" :label="item.strategyName" :value="item.id">
                    </el-option>
                  </el-select>
                  <span style="margin-left: 20px">
                    <vxe-button @click="refresh" icon="el-icon-refresh" size="mini" content="刷新"></vxe-button>
                  </span>
                  <span style="margin-left: 20px">
                    <vxe-button @click="toAdd" icon="el-icon-plus" size="mini" content="新建"></vxe-button>
                  </span>
                  <span style="margin-left: 20px">
                    <vxe-button @click="toEdit(item.strategyId)" icon="el-icon-edit" size="mini" content="编辑"></vxe-button>
                  </span>
                </el-form-item>

                <el-form-item label="分流占比" prop="flowPercent">
                  <el-input style="width: 40%" v-model="item.flowPercent" placeholder="请输入小数" />
                  <div style="color: red">请输入小数如0.5，各组占比之和为1</div>
                </el-form-item>
              </div>
            </el-tab-pane>
          </el-tabs>

        </el-form>
      </el-main>
      <el-footer style="z-index: 9999">
        <div v-if="isEdit === true" class="bodyBox">
          <div style="display: flex;justify-content: flex-end">
            <el-button type="primary" @click="onSubmit('ruleForm')">
              {{btn}}
            </el-button>
            <el-button @click="close">
              取消
            </el-button>
          </div>
        </div>
        <div v-else class="bodyBox">
          <div style="display: flex;justify-content: flex-end">
            <el-button style="width: 200px;margin-right: 100px" type="primary" @click="closeTwo">
              关闭
            </el-button>
          </div>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import { post, get } from '@/api/common'

export default {
  name: 'ABclassEdit',
  data () {
    return {
      //类型列表
      typeList: {},
      //渠道列表
      channelList: {},
      //策略列表
      strategyList: {},
      //编辑表单
      form: {
        state: 1,
        groupData: [
          {
            "content": "",
            "flowPercent": null,
            "groupName": "对照组",
            "name": "对照组",
            "state": 1,
            "strategyId": null,
            "type": 0
          },
          {
            "content": "",
            "flowPercent": null,
            "groupName": "控制组1",
            "name": "控制组1",
            "state": 1,
            "strategyId": null,
            "type": 1
          }
        ],
      },
      timeBox: [],
      channelBox: [],
      btn: '立即创建',
      // 表单验证
      rules: {
        channelKey: [
          { required: true, message: '请绑定渠道', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请填写测试名称', trigger: 'blur' },
        ],
        typeDictId: [
          { required: true, message: '请选择测试类型', trigger: 'blur' },
        ]
      },
      // 标签页
      editableTabsValue: '对照组',
      tabIndex: 1,
      thisIndex: 0,
      isEdit: true
    }
  },
  created () {
    document.title = '编辑测试'
    get('/abtest/typedict/list', { pageNum: 1, pageSize: 99999 }).then(res => {
      this.typeList = res.data.list
    })
    get('/channelInfo/listChannels', { 'pageSize': 9999, 'pageNum': 1 }).then(res => {
      this.channelList = res.data.list
    })
    get('/strategyInfoNew/page', { 'pageSize': 9999, 'pageNum': 1, 'strategyType': 2 }).then(res => {
      this.strategyList = res.data.list
    })

  },
  mounted () {
    if (this.$route.query.id) {
      get('/abtest/info/list', { 'id': this.$route.query.id }).then(res => {
        let nres = JSON.parse(JSON.stringify(res.data.list[0]));
        this.timeBox = [nres.begintime, nres.endtime]
        this.channelBox = nres.channelKey.split(',')
        let now = Date.parse(new Date());
        let begintime = Date.parse(nres.begintime)
        let endtime = Date.parse(nres.endtime);
        this.form = nres;
        if (now > endtime) {
          this.form.state = 0
          post('/abtest/info/update/' + this.$route.query.id, this.form)
        }
        if (now > begintime) {
          this.isEdit = false
        }
      });
      this.btn = '编辑保存'
    }

    if (this.$route.query.copyId) {
      get('/abtest/info/list', { 'id': this.$route.query.copyId }).then(res => {
        let nres = JSON.parse(JSON.stringify(res.data.list[0]));
        this.timeBox = [nres.begintime, nres.endtime]
        this.channelBox = nres.channelKey.split(',')
        this.form = nres;
        this.form.name = nres.name + ' 副本'
        console.log(this.form)
      });
    }
  },
  methods: {
    // 提交按钮
    onSubmit (formName) {
      this.$confirm('您确定编辑该类型？当前操作会影响所有相关测试', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs[formName].validate((valid) => {
          console.log(valid)
          if (valid) {
            if (this.form.groupData.length < 2) {
              this.$message({
                message: '至少保留一组控制组',
                type: 'warning',
                duration: 3000,
                offset: 360
              })
              return false
            }
            let sum = 0
            let havestag = true
            this.form.groupData.forEach((item, index) => {
              sum = item.flowPercent * 1 + sum
              if (!item.strategyId) {
                this.$message({
                  message: '请选择策略',
                  type: 'warning',
                  duration: 3000,
                  offset: 360
                })
                havestag = false
              }
            });
            if (sum !== 1) {
              this.$message({
                message: '分流之和需要等于1',
                type: 'warning',
                duration: 3000,
                offset: 360
              })
              return false
            }
            if (havestag === false) return false

            if (this.$route.query.id) {
              console.log(this.form)
              post('/abtest/info/update/' + this.$route.query.id, this.form).then(res => {
                this.$message({
                  message: res.message,
                  type: 'success',
                  duration: 3000,
                  offset: 360
                })

                setTimeout(() => {
                  window.close()
                }, 1500)
              })
            } else {
              post('/abtest/info/create', this.form).then(res => {
                this.$message({
                  message: res.message,
                  type: 'success',
                  duration: 3000,
                  offset: 360
                })
                setTimeout(() => {
                  window.close()
                }, 1500)
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },

    // 取消按钮
    close () {
      this.$confirm('此操作不会保存已编辑数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.location.href = 'about:blank'
        window.close()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    closeTwo () {
      window.location.href = 'about:blank'
      window.close()
    },

    // 表填格式转换
    handleChangeTime (value) {
      this.form.begintime = value[0]
      this.form.endtime = value[1]
    },
    handleChangeChannel (value) {
      let text = ''
      for (var i = 0; i < value.length; i++) {
        if (i === 0) {
          text = value[i]
        } else {
          text = text + ',' + value[i]
        }
      }
      this.form.channelKey = text
      // console.log(this.channelBox)
    },

    // 标签页
    addTab (targetName) {
      if (this.form.groupData.length <= 4) {
        this.tabIndex++
        this.form.groupData.push({
          "content": "",
          "flowPercent": null,
          "groupName": "控制组" + this.tabIndex,
          "name": "控制组" + this.tabIndex,
          "state": 1,
          "strategyId": null,
          "type": 1
        });
        this.editableTabsValue = "控制组" + this.tabIndex;
      } else {
        this.$message({
          message: '对照组最多4组',
          type: 'warning',
          duration: 3000,
          offset: 360
        })
      }
      console.log(this.form.groupData)
    },
    removeTab (targetName) {
      if (targetName !== '对照组') {
        let tabs = this.form.groupData;
        let newTabs = []
        tabs.forEach((tab, index) => {
          if (tab.groupName !== targetName) {
            newTabs.push(tab)
          }
        });
        this.editableTabsValue = '对照组'
        this.form.groupData = newTabs
      } else {
        this.$message({
          message: '对照组不可删除',
          type: 'warning',
          duration: 3000,
          offset: 360
        })
      }
      console.log(this.form.groupData)
    },
    clickTab (tab) {
      console.log(this.form.groupData[tab.index])
    },
    toAdd (e) {
      const routeUrl = this.$router.resolve({ path: '/schemeV2/schemeAdd', query: { id: e.id } })
      window.open(routeUrl.href, '_blank')
    },
    toEdit (e) {
      if (e === null) {
        this.$message({
          message: '请先选择一个策略',
          type: 'warning',
          duration: 3000,
          offset: 360
        })
      } else {
        const routeUrl = this.$router.resolve({ path: '/schemeV2/schemeAdd', query: { id: e.id } })
        window.open(routeUrl.href + '?id=' + e, '_blank')
      }

    },
    refresh () {
      get('/strategyInfoNew/page', { 'pageSize': 9999, 'pageNum': 1 }).then(res => {
        this.strategyList = res.data.list
      })
    },
  }

}
</script>

<style lang="scss">
.el-date-editor--datetimerange.el-input,
.el-date-editor--datetimerange.el-input__inner {
  width: 40%;
}

.el-footer {
  position: fixed;
  bottom: 0;
  right: 0;
}

.avatar {
  width: 100%;
  max-width: 500px;
}
</style>
