<template>
  <div class="app-container">
    <h2>广告创建</h2>
    <el-form
      ref="formCampaign"
      :model="formCampaign"
      :rules="rules"
      label-width="150px"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>广告计划</span>
            </div>

            <el-form-item label="选择账户" prop="accountId">
              <el-select
                v-model="formCampaign.accountId"
                placeholder="选择账户类型"
                clearable
                filterable
                style="width: 240px"
                :disabled="editVisble"
              >
                <el-option
                  v-for="(item, index) in formList.accountList"
                  :key="index"
                  :label="item.label + '(' + item.value + ')'"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="推广方式" prop="promotionType">
              <el-radio-group v-model="formCampaign.promotionType">
                <el-radio-button
                  v-for="(item, index) in formList.promotionTypeList"
                  :key="index"
                  :label="item.value"
                  :disabled="item.value != '2'"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="营销目标" prop="campaignType">
              <el-radio-group v-model="formCampaign.campaignType">
                <el-radio-button
                  v-for="(item, index) in formList.campaignTypeList"
                  :key="index"
                  :label="item.value"
                  :disabled="item.value != '14'"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="计划预算" prop="dayBudgetType">
              <el-radio-group v-model="formCampaign.dayBudgetType">
                <el-radio-button
                  v-for="(item, index) in formList.dayBudgetTypeList"
                  :key="index"
                  :label="item.value"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label=" "
              prop="dayBudget"
              v-if="formCampaign.dayBudgetType == '2'"
            >
              <el-input
                placeholder="请输入单日预算"
                v-model.number="formCampaign.dayBudget"
                style="width: 450px"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item
              label=" "
              prop="budgetSchedule"
              v-if="formCampaign.dayBudgetType == '3'"
            >
              <el-row class="only-the-class">
                <el-col
                  :span="3"
                  v-for="(item, index) of budgetSchedule"
                  :key="index"
                >
                  <el-card shadow="never">
                    <div slot="header" class="clearfix">
                      {{ "周" + numberReturn(index) }}
                    </div>
                    <el-input-number
                      style="width: 100%"
                      :min="500"
                      :max="100000000"
                      v-model="item.one"
                      :precision="1"
                    />
                  </el-card>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="计划名称" prop="campaignName">
              <el-input
                v-model="formCampaign.campaignName"
                style="width: 450px"
              />
            </el-form-item>
          </el-card>
        </el-col>

        <el-col :span="24" style="margin-top: 15px">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>广告组</span>
            </div>
            <el-form-item label="日预算" prop="groupDayBudget">
              <el-radio-group
                v-model="formCampaign.groupDayBudget"
                @change="$set(formCampaign, 'groupDayBudgetInput', undefined)"
              >
                <el-radio-button
                  v-for="(item, index) in formList.groupDayBudgetList"
                  :key="index"
                  :label="item.value"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label=" "
              prop="groupDayBudgetInput"
              v-if="formCampaign.groupDayBudget == 1"
            >
              <el-input
                placeholder="请输入单日预算"
                v-model.number="formCampaign.groupDayBudgetInput"
                style="width: 450px"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="投放方式" prop="speed">
              <el-radio-group v-model="formCampaign.speed">
                <el-radio-button
                  v-for="(item, index) in formList.speedList"
                  :key="index"
                  :label="item.value"
                  :disabled="item.value != 5"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="投放时间" prop="timeType">
              <el-radio-group
                v-model="formCampaign.timeType"
                @change="formCampaign.scheduleTime = undefined"
              >
                <el-radio-button
                  v-for="(item, index) in formList.timeTypeList"
                  :key="index"
                  :label="item.value"
                  :disabled="item.value == 1"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label=" "
              prop="timeStr"
              v-if="formCampaign.timeType == 3"
            >
              <el-date-picker
                v-model="formCampaign.timeStr"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                style="width: 450px"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item
              label="投放时段"
              prop="scheduleTime"
              v-if="formCampaign.timeType == 2"
            >
              <ScheduleTime
                v-if="formCampaign.timeType == 2"
                style="width: 100%; margin-right: 5px"
                :scheduleTime.sync="formCampaign.scheduleTime"
              />
            </el-form-item>

            <el-form-item label="创意组成方式" prop="showModeTwo">
              <el-radio-group v-model="formCampaign.showModeTwo">
                <el-radio-button
                  v-for="(item, index) in formList.showModeList"
                  :key="index"
                  :label="item.value"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>

            <el-form-item label="创意展示方式" prop="showMode">
              <el-radio-group v-model="formCampaign.showMode">
                <el-radio-button
                  v-for="(item, index) in formList.showModeOneList"
                  :key="index"
                  :label="item.value"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="资源位置"
              prop="sceneId"
              :rules="{
                required: true,
                message: '资源位置不能为空',
                trigger: 'change',
              }"
            >
              <el-checkbox-group v-model="formCampaign.sceneId">
                <el-checkbox-button
                  v-for="(item, index) in formList.sceneIdList"
                  :label="item.value"
                  :key="item.value"
                  :disabled="item.disabled"
                  >{{ item.label }}</el-checkbox-button
                >
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="电商广告类型" prop="merchantItemPutType">
              <el-radio-group v-model="formCampaign.merchantItemPutType">
                <el-radio-button
                  v-for="(item, index) in formList.merchantItemPutTypeList"
                  :key="index"
                  :label="item.value"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="辅助类型" prop="supportType">
              <el-radio-group v-model="formCampaign.supportType">
                <el-radio-button
                  v-for="(item, index) in formList.supportTypeList"
                  :key="index"
                  :label="item.value"
                  :disabled="item.disabled"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="广告组名称" prop="unitName">
              <el-input
                v-model="formCampaign.unitName"
                style="width: 450px"
                id="unitName"
              />
              <br />
              <el-tag
                @click="getChangeAll('定向包名', 'formInformation', 'unitName')"
                >+定向包名</el-tag
              >
              <el-tag
                @click="
                  getChangeAll('人群定向名', 'formInformation', 'unitName')
                "
                >+人群定向名</el-tag
              >
              <el-tag
                @click="
                  getChangeAll('人群排除名', 'formInformation', 'unitName')
                "
                >+人群排除名</el-tag
              >
              <el-tag
                @click="getChangeAll('转化目标', 'formInformation', 'unitName')"
                >+转化目标</el-tag
              >
              <el-tag
                @click="getChangeAll('出价', 'formInformation', 'unitName')"
                >+出价</el-tag
              >
              <el-tag
                @click="getChangeAll('日期', 'formInformation', 'unitName')"
                >+日期</el-tag
              >
            </el-form-item>
          </el-card>
        </el-col>

        <el-col :span="24" style="margin-top: 15px">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>创意设置</span>
            </div>

            <el-form-item label="作品类型" prop="liveCreativeType">
              <el-radio-group v-model="formCampaign.liveCreativeType">
                <el-radio-button
                  v-for="(item, index) in formList.liveCreativeTypeList"
                  :key="index"
                  :label="item.value"
                  :disabled="item.disabled"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="创意名称" prop="creativeName">
              <el-input
                v-model="formCampaign.creativeName"
                style="width: 450px"
              />
            </el-form-item>
          </el-card>
        </el-col>
        <el-col :span="24">
          <div class="dialog-footer" style="float: right; margin-top: 15px">
            <el-button
              type="primary"
              @click="submitForm"
              :loading="confirmLoading"
              >确 定</el-button
            >
            <el-button @click="close">取 消</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { refreshCache } from "@/api/system/dict/type";
import vueUpload from "../trader/components/vueUpload";
import FileUpload from "../trader/components/upload";

import { editLaunch, addLaunchList, getById } from "@/api/live/live";

import { getAccountList } from "@/api/trader/trader";
export default {
  name: "create-live",
  components: {
    vueUpload,
    FileUpload,
  },
  data() {
    return {
      userId: undefined,
      confirmLoading: false,
      //广告创建表单
      formCampaign: {
        promotionType: "2",
        campaignType: "14",
        dayBudgetType: "1",
        groupDayBudget: 300,
        speed: 5,
        timeType: 3,
        showModeTwo: 3,
        showMode: 1,
        sceneId: [6],
        merchantItemPutType: 2,
        supportType: 0,
        liveCreativeType: 1,
      },
      budgetSchedule: [
        { one: undefined },
        { one: undefined },
        { one: undefined },
        { one: undefined },
        { one: undefined },
        { one: undefined },
        { one: undefined },
      ],
      //表单使用的下拉列表
      formList: {
        accountList: [
          { value: "1", label: "极速推广" },
          { value: "2", label: "专业推广" },
        ],
        promotionTypeList: [
          { value: "1", label: "极速推广" },
          { value: "2", label: "专业推广" },
        ],
        campaignTypeList: [
          { value: "3", label: "获取电商下单" },
          { value: "12", label: "小店商品推广" },
          { value: "14", label: "直播推广" },
        ],
        dayBudgetTypeList: [
          { value: "1", label: "不限" },
          { value: "2", label: "单日预算" },
          { value: "3", label: "分日预算" },
        ],
        groupDayBudgetList: [
          { value: 300, label: "￥300" },
          { value: 500, label: "￥500" },
          { value: 1000, label: "￥1000" },
          { value: 3000, label: "￥3000" },
          { value: 5000, label: "￥5000" },
          { value: 1, label: "自定义" },
        ],
        speedList: [
          { value: 5, label: "最大转化" },
          { value: 1, label: "成本保护" },
        ],
        timeTypeList: [
          { value: 1, label: "固定时长" },
          { value: 2, label: "从今天开始长期投放" },
          { value: 3, label: "设置开始结束日期" },
        ],
        showModeList: [
          { value: 1, label: "自主选择" },
          { value: 2, label: "系统优选" },
          { value: 3, label: "自主选择+系统优选" },
        ],
        showModeOneList: [
          { value: 1, label: "轮播" },
          { value: 2, label: "优选" },
        ],
        sceneIdList: [
          { value: 6, label: "上下划大屏广告", disabled: false },
          { value: 7, label: "优选信息流广告", disabled: false },
          { value: 10, label: "联盟场景", disabled: true },
          { value: 41, label: "激励广告", disabled: true },
        ],
        merchantItemPutTypeList: [
          { value: 0, label: "商品" },
          { value: 2, label: "个人主页" },
        ],
        supportTypeList: [
          { value: 0, label: "小店", disabled: false },
          { value: 3, label: "金牛", disabled: true },
        ],
        liveCreativeTypeList: [
          { value: 1, label: "直播投流", disabled: false },
          { value: 2, label: "视频引流", disabled: true },
        ],
      },
      //表单验证
      rules: {
        accountId: [
          {
            required: true,
            message: "账户必选",
            trigger: "change",
          },
        ],
        dayBudget: [
          {
            required: true,
            message: "单日预算不能为空",
            trigger: "change",
          },
          {
            type: "number",
            min: 500,
            max: 100000000,
            message: "预算不能少于500，不能超过100000000",
            trigger: "change",
          },
        ],
        groupDayBudgetInput: [
          {
            required: true,
            message: "单日预算不能为空",
            trigger: "change",
          },
          {
            type: "number",
            min: 300,
            max: 2000000,
            message: "预算不能少于300，不能超过2000000",
            trigger: "change",
          },
        ],
        campaignName: [
          {
            required: true,
            message: "计划名称不能为空",
            trigger: "blur",
          },
          {
            min: 1,
            max: 50,
            message: "请填写广告计划名称, 最多50字",
            trigger: "change",
          },
        ],
        timeStr: [
          {
            required: true,
            message: "时间段必填",
            trigger: "change",
          },
        ],
        unitName: [
          {
            required: true,
            message: "广告组名称不能为空",
            trigger: "blur",
          },
          {
            min: 1,
            max: 50,
            message: "请填写广告组名称, 最多50字",
            trigger: "change",
          },
        ],
        creativeName: [
          {
            required: true,
            message: "广告创意名称不能为空",
            trigger: "blur",
          },
          {
            min: 1,
            max: 50,
            message: "请填写广告创意名称, 最多50字",
            trigger: "change",
          },
        ],
        editRecordId: null,
        editVisble: false,
      },
    };
  },
  created() {
    this.userId = this.$store.getters.userId;
    this.getAccountList();
    if (this.$route && this.$route.query.id) {
      this.editRecordId = this.$route.query.id;
      this.editVisble = true;
      this.getDetail(this.editRecordId);
    }
  },
  filters: {},
  methods: {
    getDetail(item) {
      getById({ id: item })
        .then((res) => {
          var data = res.data;
          this.$set(this.formCampaign, "accountId", data.accountId);
          this.$set(this.formCampaign, "promotionType", data.promotionType);
          this.$set(this.formCampaign, "campaignType", data.campaignType);

          if (!!data.dayBudget && data.dayBudget != -1) {
            this.$set(this.formCampaign, "dayBudgetType", "2");
            setTimeout(() => {
              this.$set(this.formCampaign, "dayBudget", data.dayBudget / 1000);
            }, 0);
          } else if (!!data.budgetSchedule) {
            var index = JSON.parse(data.budgetSchedule).findIndex((item) => {
              return item != 0;
            });
            if (index > -1) {
              this.$set(this.formCampaign, "dayBudgetType", "3");

              this.budgetSchedule = JSON.parse(data.budgetSchedule).map(
                (item) => {
                  return { one: item > 0 ? item / 1000 : undefined };
                }
              );
            } else {
              this.$set(this.formCampaign, "dayBudgetType", "1");
            }
          }

          this.$set(this.formCampaign, "campaignName", data.campaignName);
          if (!!data.groupDayBudget) {
            if (
              data.groupDayBudget / 1000 == 300 ||
              data.groupDayBudget / 1000 == 500 ||
              data.groupDayBudget / 1000 == 1000 ||
              data.groupDayBudget / 1000 == 3000 ||
              data.groupDayBudget / 1000 == 5000
            ) {
              this.$set(
                this.formCampaign,
                "groupDayBudget",
                data.groupDayBudget / 1000
              );
            } else {
              this.$set(this.formCampaign, "groupDayBudget", 1);
              this.$set(
                this.formCampaign,
                "groupDayBudgetInput",
                data.groupDayBudget / 1000
              );
            }
          } else {
            this.$set(this.formCampaign, "groupDayBudget", 300);
          }

          this.$set(this.formCampaign, "speed", data.speed);

          if (data.scheduleTime == "") {
            this.$set(this.formCampaign, "timeType", 3);
            setTimeout(() => {
              this.$set(
                this.formCampaign,
                "timeStr",
                !!data.beginTimeStr
                  ? [data.beginTimeStr, data.endTimeStr]
                  : undefined
              );
            }, 0);
          } else {
            this.$set(this.formCampaign, "timeType", 2);
            this.$set(this.formCampaign, "scheduleTime", data.scheduleTime);
          }
          this.$set(this.formCampaign, "unitName", data.unitName);
          this.$set(this.formCampaign, "creativeName", data.creativeName);

          this.$set(this.formCampaign, "showMode", data.showMode);
          this.$set(this.formCampaign, "sceneId", JSON.parse(data.sceneId));
          this.$set(
            this.formCampaign,
            "merchantItemPutType",
            data.merchantItemPutType
          );
          this.$set(this.formCampaign, "supportType", data.supportType);
          this.$set(
            this.formCampaign,
            "liveCreativeType",
            data.liveCreativeType
          );
        })
        .catch(() => {});
    },
    getAccountList() {
      getAccountList({
        userId: this.userId,
        pageNum: 1,
        pageSize: 100000,
      }).then((response) => {
        this.formList.accountList = response.rows.map((item) => {
          return {
            value: item.accountId,
            label: item.accountName,
          };
        });
      });
    },
    numberReturn(num) {
      var arr = ["一", "二", "三", "四", "五", "六", "日"];
      return arr[num];
    },
    // 失去焦点金额格式化
    nowInputMoney(el) {
      this.inputMoney(el).then((res) => {
        this.formCampaign.dayBudget = res;
      });
    },
    // 获得焦点金额去掉格式
    nowUninputMoney(el) {
      if (!!el.target.value) {
        this.uninputMoney(el).then((res) => {
          this.formCampaign.dayBudget = res;
        });
      }
    },
    //设置通配符
    getChangeAll(type, form, field) {
      var node = document.getElementById(field);
      var v = "-{{" + type + "}}-";
      if (document.selection) {
        //IE
        node.focus();
        var sel = document.selection.createRange();
        sel.text = v;
        sel.select();
        this.$set(this.formCampaign, field, sel.text);
      } else if (node.selectionStart || node.selectionStart == "0") {
        //MOZILLA/GOOGLE
        var startPos = node.selectionStart;
        var endPos = node.selectionEnd;
        var restoreTop = node.scrollTop;
        node.value =
          node.value.substring(0, startPos) +
          v +
          node.value.substring(endPos, node.value.length);
        if (restoreTop > 0) {
          node.scrollTop = restoreTop;
        }

        // this.formCampaign[field] = node.value;
        this.$set(this.formCampaign, field, node.value);
        node.focus();
        node.selectionStart = startPos + v.length;
        node.selectionEnd = startPos + v.length;
        // this.campaignName = node.value
      } else {
        //OTHER
        node.value += v;
        // console.log(node.value)
        this.$set(this.formCampaign, field, node.value);
        node.focus();
        // this.campaignName = node.value
      }
    },
    close() {
      if (this.editRecordId) {
        const obj = {
          path: "/live/create",
          query: { id: this.editRecordId },
        };
        const objOpen = { path: "/live/index" };
        this.$tab.closeOpenPage(obj);
        this.$tab.closePage(obj);
        this.$router.push(objOpen.path);
      } else {
        const obj = { path: "/live/create" };
        const objOpen = { path: "/live/index" };
        this.$tab.closeOpenPage(obj);
        this.$tab.closePage(obj);
        this.$router.push(objOpen.path);
      }
    },
    // 创建
    submitForm() {
      this.$refs["formCampaign"].validate((valid) => {
        if (valid) {
          var params = { ...this.formCampaign };
          if (params.dayBudgetType == "1") {
            params.budgetSchedule = [0, 0, 0, 0, 0, 0, 0];
            params.dayBudget = -1;
          } else if (params.dayBudgetType == "2") {
            params.dayBudget = params.dayBudget * 1000;
            params.budgetSchedule = [];
          } else if (params.dayBudgetType == "3") {
            var index = this.budgetSchedule.findIndex((item) => {
              return !item.one;
            });
            if (index > -1) {
              this.$message.error("分日预算必须全部填写");
              return;
            } else {
              params.budgetSchedule = this.budgetSchedule.map((item) => {
                return !!item.one ? item.one * 1000 : 0;
              });
              params.dayBudget = -1;
            }
          }

          if (params.groupDayBudget == 1) {
            params.groupDayBudget =
              this.formCampaign.groupDayBudgetInput * 1000;
          } else {
            params.groupDayBudget = params.groupDayBudget * 1000;
          }

          if (params.timeType == 3) {
            if (!this.formCampaign.timeType) {
            } else {
              params.beginTimeStr = this.formCampaign.timeStr[0];
              params.endTimeStr = this.formCampaign.timeStr[1];
            }
            params.scheduleTime = "";
          } else if (params.timeType == 2) {
            params.scheduleTime = !!params.scheduleTime
              ? params.scheduleTime
              : "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
            params.beginTimeStr = "";
            params.endTimeStr = "";
          }
          params.createrId = this.userId;

          params.showMode = this.formCampaign.showMode;
          params.sceneId = this.formCampaign.sceneId;
          params.merchantItemPutType = this.formCampaign.merchantItemPutType;
          params.supportType = this.formCampaign.supportType;
          params.liveCreativeType = this.formCampaign.liveCreativeType;
          var that = this;
          if (this.editRecordId) {
            params.id = this.editRecordId;
            editLaunch(params)
              .then((res) => {
                const obj = {
                  path: "/live/create",
                  query: { id: this.editRecordId },
                };
                const objOpen = { path: "/live/index" };
                this.$tab.closeOpenPage(obj);
                this.$tab.closePage(obj);
                this.$router.push(objOpen.path);
              })
              .catch((err) => {});
          } else {
            addLaunchList(params)
              .then((res) => {
                const obj = { path: "/live/create" };
                const objOpen = { path: "/live/index" };
                this.$tab.closeOpenPage(obj);
                this.$tab.closePage(obj);
                this.$router.push(objOpen.path);
              })
              .catch((err) => {});
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.entire-line {
  width: 100%;
  ::v-deep .el-form-item__content {
    width: 60%;
  }
}
::v-deep .el-form-item__label {
  white-space: nowrap;
}
::v-deep .el-tag {
  margin-right: 15px;
}
::v-deep .only-the-class .el-input__inner {
  padding: 0;
}
::v-deep .el-input-number__decrease {
  display: none;
}

::v-deep .el-input-number__increase {
  display: none;
}
</style>
