<template>
  <div class="group-select">
    <a-form
      :label-col="{ span: 2 }"
      :wrapper-col="{ span: 8 }"
      :rules="rules"
      :model="form"
      ref="formCheck"
    >
      <a-form-item label="创建方式">
        <a-radio-group v-model:value="form.build_mode" @change="getAdviseList">
          <a-radio value="1">新建广告组</a-radio>
          <a-radio value="2">已有广告组</a-radio>
        </a-radio-group>
      </a-form-item>
      <div v-if="form.build_mode === '1'">
        <a-form-item label="营销链路" name="marketing_purpose">
          <a-radio-group v-model:value="form.marketing_purpose" @change="makeGroupName">
            <a-radio-button value="CONVERSION">行动转化</a-radio-button>
            <!-- <a-radio-button value="INTENTION">用户意向</a-radio-button>
            <a-radio-button value="ACKNOWLEDGE">品牌认知</a-radio-button> -->
          </a-radio-group>
        </a-form-item>
        <a-form-item name="landing_type" style="margin-left: 100px">
          <a-radio-group v-model:value="form.landing_type" @change="makeGroupName">
            <a-radio-button value="LINK">销售线索收集</a-radio-button>
            <!-- <a-radio-button value="APP">应用推广</a-radio-button> -->
          </a-radio-group>
        </a-form-item>
        <a-form-item label="广告类型" name="campaign_type">
          <a-select v-model:value="form.campaign_type" placeholder="请选择">
            <a-select-option value="FEED">所有广告</a-select-option>
            <a-select-option value="SEARCH">搜索广告</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="广告组预算">
          <a-radio-group v-model:value="form.budget_mode">
            <a-radio value="BUDGET_MODE_INFINITE">不限</a-radio>
            <a-radio value="BUDGET_MODE_DAY">指定预算</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="日预算" name="budget" v-if="form.budget_mode === 'BUDGET_MODE_DAY'">
          <a-input addon-after="元" type="number" v-model:value="form.budget" />
        </a-form-item>
        <a-form-item label="广告组名称" name="campaign_name">
          <a-input v-model:value="form.campaign_name" :maxlength="50" />
        </a-form-item>
      </div>
      <div v-else class="ad-group-box">
        <div class="title-box">
          <h3>选择广告组</h3>
        </div>
        <div class="main-box">
          <div class="search-box">
            <a-input-search
              v-model:value="groupNameSearch"
              placeholder="请输入广告组名称"
              style="width: 200px"
              @search="onSearch"
            />
          </div>
          <div class="table-title">
            <h3>广告组名称</h3>
          </div>
          <div class="list-box">
            <a-radio-group v-model:value="form.campaign_id">
              <!-- <a-radio :style="radioStyle" :value="1"
                >广告组1 <span class="desc">测试广告组</span></a-radio
              >-->
              <a-radio
                :style="radioStyle"
                v-for="item in groupList"
                :key="item.campaign_id"
                :value="item.campaign_id"
              >
                {{ item.campaign_name }}
                <span
                  class="desc"
                  v-show="item.landing_type === 'LINK'"
                >销售线索搜集</span>
                <span class="desc" v-show="item.landing_type === 'APP'">应用推广</span>
              </a-radio>
            </a-radio-group>
            <a-empty v-show="groupList.length === 0"></a-empty>
          </div>
        </div>
      </div>
    </a-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref, createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { getAdCampaigns, createAdCampaign } from "@/api";
import { message, Modal } from "ant-design-vue";
import {
  RuleObject,
  ValidateErrorEntity,
} from "ant-design-vue/es/form/interface";
import Bus from "@/utils/bus";

const GroupSelect = defineComponent({
  setup() {
    const formCheck = ref();
    const state = reactive({
      form: {
        build_mode: "1", // 创建方式
        landing_type: "", // 广告链路 广告组推广目的
        marketing_purpose: "", // 营销目的
        campaign_type: undefined, // 广告类型
        budget_mode: "BUDGET_MODE_INFINITE", // 广告组预算
        budget: 0, // 日预算
        campaign_name: "", // 广告组名称
        campaign_id: 0, // 选择的已有广告组
      },
      groupNameSearch: "", // 搜索广告组名称
      groupList: ref<any[]>([]),
      groupListOrigin: ref<any[]>([]),
      campaign_id: 0,
    });
    const radioStyle = reactive({
      display: "block",
      height: "40px",
      lineHeight: "40px",
      width: "560px",
      padding: "0 10px",
      borderBottom: "1px solid rgb(230, 230, 230)",
    });
    let checkBudget = async (rule: RuleObject, value: string | number) => {
      if (value < 300) {
        return Promise.reject("预算不得少于300元");
      } else {
        formCheck.value.validateField("checkPass");
        return Promise.resolve();
      }
    };
    const rules = {
      build_mode: [
        {
          required: false,
          message: "请选择",
          trigger: "change",
        },
      ],
      landing_type: [
        {
          required: true,
          message: "请选择",
          trigger: "change",
        },
      ],
      marketing_purpose: [
        {
          required: true,
          message: "请选择",
          trigger: "change",
        },
      ],
      campaign_type: [
        {
          required: true,
          message: "请选择广告类型",
          trigger: "change",
        },
      ],
      campaign_name: [
        {
          required: true,
          message: "请输入广告组名称",
          trigger: "blur",
        },
      ],
      budget: [
        {
          validator: checkBudget,
          trigger: "blur",
        },
      ],
    };

    return { ...toRefs(state), radioStyle, rules, formCheck, checkBudget };
  },
  beforeRouteLeave(to: any, from, next) {
    console.log("离开", to);
    if (
      to.href.indexOf("plan-create/account-select") > -1 ||
      to.href.indexOf("plan-create/plan-edit") > -1
    ) {
      window.localStorage.setItem(
        "plan-create-campaign",
        JSON.stringify(this.form)
      );
      return next();
    }
    Modal.confirm({
      title: "确认离开当前页面吗?",
      icon: createVNode(ExclamationCircleOutlined),
      content: createVNode(
        "div",
        { style: "color:gray;" },
        "未保存内容将会丢失"
      ),
      onOk() {
        next();
      },
      onCancel() {
        next(false);
      },
      class: "test",
    });
  },
  mounted() {
    if (window.localStorage.getItem("plan-create-campaign"))
      this.form = JSON.parse(
        String(window.localStorage.getItem("plan-create-campaign"))
      );
    this.getGroups();
    Bus.$on("stepTwoCheck", (val?: any) => {
      let data: any = {};
      if (val) {
        data = val;
      } else {
        data = this.check();
      }
      if (data.flag) {
        window.localStorage.setItem(
          "plan-create-campaign",
          JSON.stringify(this.form)
        );
        Bus.$emit("stepTwoBack", {
          campaign_id: data.campaign_id,
          advertiser_id: this.$route.query.advertiser_id,
        });
      }
    });
  },
  methods: {

    //更新广告组列表
    getAdviseList() {
      this.getGroups()
    },
    // 搜索广告组名称

    // step2创建广告组页面校验
    check() {
      if (window.localStorage.getItem("plan-create-campaign")) {
        if (
          this.campaign_id !== 0 &&
          this.isObjEqual(
            JSON.parse(
              String(window.localStorage.getItem("plan-create-campaign"))
            ),
            this.form
          )
        )
          return { flag: true, campaign_id: this.form.campaign_id };
      }
      let campaign_id = 0;
      if (this.form.build_mode === "1") {
        // 校验表单
        this.formCheck
          .validate()
          .then(() => {
            // 请求创建广告主接口
            let param: any = {
              ...this.form,
              budget:Number(this.form.budget),
              advertiser_id: Number(this.$route.query.advertiser_id),
            };
            delete param.build_mode;
            delete param.campaign_id;
            if (param.budget_mode === "BUDGET_MODE_INFINITE")
              delete param.budget;
            console.log("创建广告组传递数据", param);

            // 接口
            createAdCampaign(param)
              .then(({ data }) => {
                console.log("创建广告组返回", data);
                this.campaign_id = data.campaign_id;
                campaign_id = data.campaign_id;
                this.form.campaign_id = campaign_id;
                message.success("广告组创建成功");
                Bus.$emit("stepTwoCheck", {
                  flag: true,
                  campaign_id: campaign_id,
                });
              })
              .catch((error: any) => {
                console.log("error", error);
              });
          })
          .catch((error: any) => {
            console.log("error", error);
          });
      } else {
        if (!this.form.campaign_id) {
          message.warning("请选择广告组");
        } else {
          campaign_id = this.form.campaign_id;
        }
      }
      // 返回处理
      let data = { flag: campaign_id ? true : false, campaign_id: campaign_id };
      return data;
    },
    async getGroups() {
      let param: any = {
        advertiser_id: String(this.$route.query.advertiser_id),
        page: 1,
        pageSize: 200,
      };
      if (this.groupNameSearch) {
        param.campaign_name = this.groupNameSearch;
      }
      let { data } = await getAdCampaigns(param);
      console.log("获取广告组", data);
      this.groupList = data.list;
    },
    // 生成广告组名称
    makeGroupName() {
      console.log(this.form.landing_type)
      console.log(1)
      localStorage.setItem('langding_type',this.form.landing_type)
      if (!this.form.landing_type || !this.form.marketing_purpose) return;
      let langdingTypeName = "",
        marketingPurposeName = "";
      let nameArr: any = [
        { name: "销售线索收集", value: "LINK" },
        { name: "应用推广", value: "APP" },
        { name: "行动转化", value: "CONVERSION" },
        { name: "用户意向", value: "INTENTION" },
        { name: "品牌认知", value: "ACKNOWLEDGE" },
      ];
      nameArr.forEach((item: any) => {
        if (this.form.landing_type === item.value) langdingTypeName = item.name;
        if (this.form.marketing_purpose === item.value)
          marketingPurposeName = item.name;
      });
      let time = this.getNowFormatDate();
      this.form.campaign_name = `${marketingPurposeName}_${langdingTypeName}_${time}`;
    },
    //搜索广告组名字
    onSearch() {
      console.log(this.groupNameSearch)
      console.log(this.groupList)
      this.groupList = this.groupList.filter((item: any) => {
        let arr = []
        if (this.groupNameSearch == '') {
          this.getGroups()
        }
        if (item.campaign_name.indexOf(this.groupNameSearch) > -1) {
          arr.push(item)
          return arr
        } 
      }

      )
    },
    // 工具函数 获取当前时间
    getNowFormatDate() {
      var date = new Date();
      var seperator1 = "-";
      var seperator2 = ":";
      var month: any = date.getMonth() + 1;
      var strDate: any = date.getDate();
      var strHours: any = date.getHours();
      var strMinutes: any = date.getMinutes();
      var strSeconds: any = date.getSeconds();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      if (strHours >= 0 && strHours <= 9) {
        strHours = "0" + strHours;
      }
      if (strMinutes >= 0 && strMinutes <= 9) {
        strMinutes = "0" + strMinutes;
      }
      if (strSeconds >= 0 && strSeconds <= 9) {
        strSeconds = "0" + strSeconds;
      }
      var currentdate =
        date.getFullYear() +
        seperator1 +
        month +
        seperator1 +
        strDate +
        " " +
        strHours +
        seperator2 +
        strMinutes +
        seperator2 +
        strSeconds;
      currentdate = currentdate.replace(/-/g, "_").replace(/ /g, "_");
      currentdate = currentdate.slice(5, 19);
      return currentdate;
    },
    //工具函数 比较2个对象是否相同
    isObjEqual(o1: any, o2: any) {
      var props1 = Object.getOwnPropertyNames(o1);
      var props2 = Object.getOwnPropertyNames(o2);
      if (props1.length != props2.length) {
        return false;
      }
      for (var i = 0, max = props1.length; i < max; i++) {
        var propName = props1[i];
        if (o1[propName] !== o2[propName]) {
          return false;
        }
      }
      return true;
    },
  },
  beforeUnmount() {
    Bus.$off("stepTwoCheck");
  },
});

export default GroupSelect;
</script>
<style lang="scss" scoped>
// @import "@/assets/common-style/scroll-bar.scss";
.group-select {
  .ad-group-box {
    width: 600px;
    height: 350px;
    border: 1px solid rgb(230, 230, 230);
    margin-left: 100px;
    .title-box {
      height: 40px;
      line-height: 40px;
      border-bottom: 1px solid rgb(230, 230, 230);
      padding-left: 10px;
    }
    .main-box {
      padding: 10px;
      .table-title {
        border: 1px solid rgb(230, 230, 230);
        background: rgba(241, 241, 241, 0.548);
        height: 40px;
        line-height: 40px;
        padding-left: 10px;
        margin: 10px 0;
      }
      .list-box {
        height: 200px;
        overflow: auto;
        .desc {
          float: right;
          margin-right: 10px;
          display: block;
          width: 200px;
          color: rgb(167, 163, 163);
        }
      }
    }
  }
}
</style>
