<template>
  <div>
    <el-container>
      <el-main>
        <el-form label-width="100px">
          <el-divider content-position="left">编辑基本信息</el-divider>
          <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
            <el-row :gutter="10">
              <el-col :span="17">
                <el-form-item label="策略名称" prop="name">
                  <el-input style="width: 300px" v-model="form.name" @change="changeInputer" />
                </el-form-item>
                <el-form-item label="策略描述" prop="maskText">
                  <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model="form.content" />
                </el-form-item>

                <el-form-item label="策略类型" prop="type">
                  <el-select style="width: 300px" v-model="form.type" placeholder="请选择策略类型" :disabled="this.edit">
                    <el-option label="A/B策略" :value="1" />
                    <el-option label="地域投放" :value="2" />
                    <el-option label="活动投放" :value="3" />
                    <el-option label="智能投放" :value="4">
                      <span style="float: left">智能投放</span>
                      <span style="float: right; color: #f56c6c">内测中</span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="生效状态" v-if="this.edit">
                  <el-select style="width: 300px" v-model="form.state" placeholder="请选择生效状态">
                    <el-option label="有效" :value="1" />
                    <el-option label="无效" :value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-divider content-position="left">规则配置 </el-divider>
          <!-- ab策略-->
          <div v-if="form.type == 1">
            <el-form :model="abform" label-width="100px">
              <div class="tip">
                <span class="req">*</span>
                <el-form-item label="日期选择" prop="datetimerange">
                  <el-date-picker type="datetimerange" clearable v-model="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至" value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                </el-form-item>
              </div>
              <el-tabs v-model="editableTabsValue" type="card" closable @tab-click="clickTab">
                <el-tab-pane v-for="item in abform.groupInfo" :key="item.groupName" :label="item.groupName" :name="item.groupName">
                  <div>
                    <div class="tip">
                      <span class="req">*</span>
                      <el-form-item label="选择策略" prop="strategyTemplateId">
                        <el-select v-model="item.strategyTemplateId" clearable filterable placeholder="请选择">
                          <el-option v-for="item in strategyList" :key="item.id" :label="item.strategyName" :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                    <div class="tip">
                      <span class="req">*</span>
                      <el-form-item label="分流占比" prop="flowPercent">
                        <el-input style="width: 90%" v-model="item.flowPercent" placeholder="请输入小数" />
                        <div style="color: red">
                          请输入小数如0.5，各组占比之和为1
                        </div>
                      </el-form-item>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </el-form>
          </div>
          <div v-if="form.type == 2">
            <el-form label-width="100px">
              <div class="tip">
                <span class="req">*</span>
                <el-form-item label="地域选择" prop="locatioName">
                  <el-select v-model="locationForm.locatioName" clearable filterable placeholder="请选择">
                    <el-option v-for="item in provinceListAll" :key="item" :value="item" :label="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div class="tip">
                <span class="req">*</span>
                <el-form-item label="选用策略" prop="strategyTemplateId">
                  <el-select v-model="locationForm.strategyTemplateId" clearable filterable placeholder="请选择">
                    <el-option v-for="item in strategyList" :key="item.id" :label="item.strategyName" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-form>
          </div>
          <div v-if="form.type == 3">
            <el-form label-width="100px">
              <div class="tip">
                <span class="req">*</span>
                <el-form-item label="日期选择" prop="datetimerange">
                  <el-date-picker type="datetimerange" clearable v-model="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至" value-format="yyyy-MM-dd">
                  </el-date-picker>
                </el-form-item>
              </div>
              <el-form-item label="星期选择">
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">
                  全选
                </el-checkbox>
                <div style="margin: 15px 0"></div>
                <el-checkbox-group v-model="checkedWeeks" @change="handleCheckedCitiesChange">
                  <el-checkbox v-for="item in weeksList" :label="item" :key="item">{{ item }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>

              <div class="tip">
                <span class="req">*</span>
                <el-form-item label="时间选择" prop="startTime">
                  <el-time-picker v-model="activeForm.startTime" :picker-options="{ start: '00:00', end: '18:30' }" format="HH:mm:ss" value-format="HH:mm:ss" placeholder="开始时间">
                  </el-time-picker>
                  -
                  <el-time-picker v-model="activeForm.endTime" format="HH:mm:ss" value-format="HH:mm:ss" placeholder="结束时间">
                  </el-time-picker>
                </el-form-item>
              </div>
              <div class="tip">
                <span class="req">*</span>
                <el-form-item label="投放策略" prop="strategyTemplateId">
                  <el-select v-model="activeForm.strategyTemplateId" 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>
                </el-form-item>
              </div>
            </el-form>
          </div>
          <div v-if="form.type == 4">
            <el-form-item>
              <el-checkbox-group v-model="checkVideo">
                <el-checkbox v-for="item in checkList" :label="item" :key="item.id">{{ item }}</el-checkbox>
              </el-checkbox-group>
              <el-button class="elbut" style="float: right">拉取</el-button>
            </el-form-item>

            <el-form-item label="投放策略">
              <el-select v-model="form.strategyTemplateId" 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>
            </el-form-item>
          </div>
        </el-form>
      </el-main>
      <el-footer style="z-index: 9999">
        <div class="bodyBox" style="display: flex; justify-content: flex-end">
          <el-button> 清空 </el-button>
          <el-button style="display: flex; justify-content: flex-end" type="primary" @click="onSubmit('ruleForm')">
            保存
          </el-button>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>
<script>
import { post, get } from "@/api/common";
const weekOptions = ["周日", "周一", "周二 ", "周三", "周四", "周五", "周六"];
import { parseTimee } from "@/utils";
export default {
  data () {
    return {
      form: {
        id: null,
        strategyTemplateId: null,
        name: "",
        content: "",
        type: 1,
        state: "",
      },

      abform: {
        //ab表单
        effectBeginTime: "",
        effectEndTime: "",
        groupInfo: [
          {
            flowPercent: null,
            groupName: "对照组",
            state: 1,
            strategyTemplateId: "",
          },
          {
            flowPercent: null,
            groupName: "控制组",
            state: 1,
            strategyTemplateId: "",
          },
        ],
      },
      idd: "",
      edit: false,
      activeForm: {
        //活动表单
        weeks: "0,1,2,3,4,5,6",
        startDate: "",
        endDate: "",
        startTime: "00:00:00",
        endTime: "23:59:59",
        strategyTemplateId: "",
      },
      locationForm: {
        //地域表单
        strategyTemplateId: "",
        locatioName: "",
      },
      checkList: [
        "爱奇艺视频",
        "腾讯视频",
        "优酷视频",
        "B站视频",
        "投诉风险",
        "黑名单",
      ],
      time: [],
      datetimerange: [],
      timerange: [],
      checkedWeeks: [],
      checkVideo: [],
      //策略列表
      strategyList: {},
      weeksList: weekOptions,
      editableTabsValue: "对照组",
      isIndeterminate: true,
      //全选
      checkAll: false,
      provinceListAll: [
        "北京",
        "上海",
        "天津",
        "重庆",
        "黑龙江",
        "吉林",
        "辽宁",
        "内蒙古",
        "河北",
        "新疆",
        "甘肃",
        "青海",
        "陕西",
        "宁夏",
        "河南",
        "山东",
        "山西",
        "安徽",
        "湖北",
        "湖南",
        "江苏",
        "四川",
        "贵州",
        "云南",
        "广西",
        "西藏",
        "浙江",
        "江西",
        "广东",
        "福建",
        "台湾",
        "海南",
        "香港",
        "澳门",
      ],
      rules: {
        name: [
          //策略名字
          { required: true, message: "请输入策略名称", trigger: "blur" },
        ],
        type: [
          //策略类型
          { required: true, message: "请选择测试类型", trigger: "change" },
        ],
        // datetimerange: [
        //   //日期
        //   {
        //     type: "date",
        //     required: true,
        //     message: "请选择日期",
        //     trigger: "blur",
        //   },
        // ],
        // strategyTemplateId: [
        //   //投放策略
        //   { required: true, message: "请选择策略", trigger: "blur" },
        // ],
        // flowPercent: [
        //   { required: true, message: "请选择分流占比", trigger: "blur" },
        // ],
        //   // locatioName: [
        //   //   { required: true, message: "请选择地区", trigger: "blur", },
        //   // ],
        //   startTime: [//时间
        //     { type: 'date', required: true, message: '请选择时间', trigger: 'blur' }
        //   ]
      },
    };
  },
  created () {
    // console.log(this.edit);
    get("/strategytemplate/list", { pageSize: 999, pageNum: 1 }).then((res) => {
      this.strategyList = res.data.list;
    });
  },
  mounted () {
    //数据回显
    if (this.$route.query.id) {
      //编辑
      this.edit = true;
      post("/strategysenior/" + this.$route.query.id, {
        id: this.$route.query.id,
      }).then((res) => {
        res = res.data;
        this.form = {
          name: res.name,
          content: res.content,
          type: res.type,
          state: res.state,
        };

        if (res.type === 1) {
          //ab回显
          if (res.groupInfo) {
            res.groupInfo = JSON.parse(res.groupInfo);
          }
          this.idd = res.abId;
          this.abform = {
            groupInfo: [
              {
                flowPercent: res.groupInfo[0].flowPercent,
                groupName: "对照组",
                state: 1,
                strategyTemplateId: res.groupInfo[0].strategyTemplateId,
              },
              {
                flowPercent: res.groupInfo[1].flowPercent,
                groupName: "控制组",
                state: 1,
                strategyTemplateId: res.groupInfo[1].strategyTemplateId,
              },
            ],
          };
          if (res.effectBeginTime) {
            let effectBeginTime = parseTimee(
              res.effectBeginTime,
              "{y}-{m}-{d} {h}:{i}:{s}"
            );
            let effectEndTime = parseTimee(
              res.effectEndTime,
              "{y}-{m}-{d} {h}:{i}:{s}"
            );
            this.datetimerange = [effectBeginTime, effectEndTime];
          }
        }
        if (res.type === 2) {
          //地域回显
          this.locationForm = {
            locatioName: res.locatioName,
            strategyTemplateId: res.strategyTemplateId,
          };
          this.idd = res.locationId;
          let checkedWeeks = res.weeks.split(",");
          checkedWeeks.forEach((item) => {
            this.checkedWeeks.push(weekOptions[item]);
          });
        }
        if (res.type === 3) {
          //活动回显
          if (res.weeks) {
            let checkedWeeks = res.weeks.split(",");
            checkedWeeks.forEach((item) => {
              this.checkedWeeks.push(weekOptions[item]);
            });
          }
          if (res.startDate) {
            let startDate = res.startDate;
            let endDate = res.endDate;
            this.datetimerange = [startDate, endDate];
          }

          this.idd = res.activityId;
          this.activeForm = {
            //活动表单
            weeks: res.weeks,
            startTime: res.startTime,
            endTime: res.endTime,
            strategyTemplateId: res.strategyTemplateId,
          };
        }
      });
    }
  },
  watch: {
    datetimerange (val) {
      if (val) {
        console.log(val);
        //ab
        this.abform.effectBeginTime = val[0];
        this.abform.effectEndTime = val[1];
        //活动
        this.activeForm.startDate = val[0];
        this.activeForm.endDate = val[1];
      } else {
        //ab
        this.abform.effectBeginTime = "";
        this.abform.effectEndTime = "";
        //活动
        this.activeForm.startDate = "";
        this.activeForm.endDate = "";
      }
    },
    checkedWeeks (val) {
      this.activeForm.weeks = val
        .map((i) => weekOptions.findIndex((j) => j == i))
        .sort()
        .toString();
      // console.log(this.activeForm.weeks)
    },
  },
  methods: {
    //提交
    onSubmit (formName) {
      if (this.$route.query.id) {
        //修改
        this.form.id = this.$route.query.id;
        if (this.form.type === 1) {
          //ab修改
          this.abform.abId = this.idd;

          let upform1 = { ...this.form, ...this.abform };
          post("/strategysenior/update/ab", upform1).then((res) => {
            // console.log(res)
            this.$message({
              message: res.message,
              type: "success",
              duration: 3000,
              offset: 360,
            });
            setTimeout(() => {
              window.close();
            }, 1200);
          });
        }
        if (this.form.type === 2) {
          //地域修改
          this.locationForm.locationId = this.idd;
          let upform2 = { ...this.form, ...this.locationForm };
          post("/strategysenior/update/location/", upform2).then((res) => {
            // console.log(res)
            this.$message({
              message: res.message,
              type: "success",
              duration: 3000,
              offset: 360,
            });
            setTimeout(() => {
              window.close();
            }, 1200);
          });
        }
        if (this.form.type === 3) {
          //活动修改
          this.activeForm.activityId = this.idd;
          let upform3 = { ...this.form, ...this.activeForm };
          post("/strategysenior/update/activity", upform3).then((res) => {
            // console.log(res)
            this.$message({
              message: res.message,
              type: "success",
              duration: 3000,
              offset: 360,
            });
            setTimeout(() => {
              window.close();
            }, 1200);
          });
        }
      } else {
        //新增
        this.$refs[formName].validate((valid) => {
          console.log(valid);
          if (valid) {
            if (this.form.type == 1) {
              //ab策略新增
              if (!this.abform.effectBeginTime) {
                alert("请选择日期");
              } else if (
                !this.abform.groupInfo[0].strategyTemplateId ||
                !this.abform.groupInfo[1].strategyTemplateId
              ) {
                alert("请选择策略");
              } else if (
                !this.abform.groupInfo[0].flowPercent ||
                !this.abform.groupInfo[1].flowPercent
              ) {
                alert("请填写分流");
              } else {
                let form1 = { ...this.form, ...this.abform };
                post("/strategysenior/create/abtest", form1).then((res) => {
                  this.$message({
                    message: res.message,
                    type: "success",
                    duration: 3000,
                    offset: 360,
                  });
                  // setTimeout(() => {
                  //   window.close()
                  // }, 1200)
                });
              }
            }
            if (this.form.type == 2) {
              //地域投放新增
              if (!this.locationForm.locatioName) {
                alert("请选择地区");
              } else if (!this.locationForm.strategyTemplateId) {
                alert("请选择策略");
              } else {
                let form3 = { ...this.form, ...this.locationForm };
                post("/strategysenior/create/location", form3).then((res) => {
                  this.$message({
                    message: res.message,
                    type: "success",
                    duration: 3000,
                    offset: 360,
                  });
                  setTimeout(() => {
                    window.close();
                  }, 1200);
                });
              }
            }
            if (this.form.type == 3) {
              //活动策略新增
              if (!this.activeForm.endDate) {
                alert("请选择日期");
              } else if (!this.activeForm.startDate) {
                alert("请选择时间");
              } else if (!this.activeForm.strategyTemplateId) {
                alert("请选择策略");
              } else {
                let form2 = { ...this.form, ...this.activeForm };
                post("/strategysenior/create/activity", form2).then((res) => {
                  this.$message({
                    message: res.message,
                    type: "success",
                    duration: 3000,
                    offset: 360,
                  });
                  setTimeout(() => {
                    window.close();
                  }, 1200);
                });
              }
            }
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      }
    },
    changeInputer () {
      //新增自动添加名字
      if (!this.$route.query.id) {
        if (this.form.name) {
          this.form.name = `${this.$store.state.user.name}--${this.form.name}`;
        }
      }
    },
    clickTab (tab) {
      console.log(this.abform.groupInfo[tab.index]);
    },
    handleCheckAllChange (val) {
      this.checkedWeeks = val ? weekOptions : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange (value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.weeksList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.weeksList.length;
    },
  },
};
</script>
<style lang="scss">
.bodyBox {
  position: fixed;
  bottom: 20px;
  right: 20px;
}
.el-main {
  height: 93vh;
  padding-bottom: 100px;
}

.avatar {
  width: 100%;
  max-width: 500px;
}

.el-divider {
  margin-bottom: 40px !important;

  .el-divider__text {
    font-size: 17px !important;
    font-weight: bold !important;
  }
}

.tip {
  display: flex;
  color: rgb(245, 108, 108);
  margin-left: 22px;
}
.req {
  height: 10px;
  margin-top: 12px;
  width: 3px;
  // margin-right: 0;
  margin-right: -25px;
}
.elbut {
  margin-top: -40px;
  // margin-right: 500px;
}
</style>
