<template>
  <div>
    <s-header :name="titleName" :noback="false"></s-header>
    <van-form show-error-message @submit="onSubmit">
      <div class="cust_vantBorder">
        <van-field colon :border="false" required v-model="cofficentForm.name" clearable name="name"
          :label="$t('advertManage.advertRule.addRule.ruleName')"
          :placeholder="$t('advertManage.advertRule.addRule.ruleNamePlace')" :rules="[
            {
              required: true,
              message: $t('advertManage.advertRule.addRule.ruleNamePlace'),
            },
          ]" />
        <van-field colon :border="false" v-model="cofficentForm.userNames" clearable name="userNames"
          :label="$t('advertManage.advertRule.addRule.pushMerchant')"
          :placeholder="$t('advertManage.advertRule.addRule.pushMerchantPlace')" />
        <van-field readonly colon :border="false" v-model="cofficentForm.A_advertList" clearable name="A_advertList"
          :placeholder="$t('advertManage.advertRule.addRule.AScreenPlace')"
          :label="$t('advertManage.advertRule.addRule.AScreen')">
          <template #button>
            <van-button @click="searchClk(0)" type="primary">{{
              $t("advertManage.advertRule.addRule.screen")
            }}</van-button>
          </template>
        </van-field>
        <van-field required readonly colon :border="false" v-model="cofficentForm.B_advertList" clearable
          name="B_advertList" :placeholder="$t('advertManage.advertRule.addRule.BScreennPlace')"
          :label="$t('advertManage.advertRule.addRule.BScreen')" :rules="[
            {
              required: true,
              message: $t('advertManage.advertRule.addRule.BScreennPlace'),
            },
          ]">
          <template #button>
            <van-button @click="searchClk(1)" type="primary">{{
              $t("advertManage.advertRule.addRule.screen")
            }}</van-button>
          </template>
        </van-field>
      </div>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          {{ $t("advertManage.advertRule.addRule.submit") }}
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
// 导入公用方法
import { setLocal, styleUrl } from "@/common/js/utils";
// 导入接口
import {
  Api_postAddAdRule,
  Api_postUpdateAdRule,
  Api_getAdRuleDetail,
  Api_getAdListByTimeRule,
} from "@/service/advertManage";
import sHeader from "@/components/SimpleHeader";
import { useI18n } from "vue-i18n";
import { onMounted, ref, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { showToast } from 'vant';
export default {
  name: "advertRuleAdd",
  components: { sHeader },
  setup() {
    const { t } = useI18n();
    const titleName = ref(t("advertManage.advertRule.addRule.title"));
    const route = useRoute();
    const router = useRouter();
    // 定义参数
    const cofficentForm = reactive({
      name: "",
      rule: [],
      userNames: "",
      A_advertList: "",
      B_advertList: "",
    });
    // 广告规则的id
    const adRuleId = ref("");
    // 导入vuex
    const store = useStore();
    // 刚进页面
    onMounted(() => {
      // 加载样式
      styleUrl('advertManage');
      // 如果是第一次进入页面就请求接口
      const id = route.query.id || "";
      adRuleId.value = id;
      // 看路径有没有id，有就是编辑
      if (id) {
        titleName.value = t("advertManage.advertRule.addRule.editTitle");
        getDetail(id);
      }
      console.log(11111111);
      // 获取广告规则
      const A_advertList = store.state.$S_advertManage_A_advertList;
      const B_advertList = store.state.$S_advertManage_B_advertList;
      // 如果vuex有值，那么表面是从筛选页面回来的，否则是从主页面进来的
      if (
        (A_advertList && A_advertList.length > 0) ||
        (B_advertList && B_advertList.length > 0)
      ) {
        // 初始化广告回显
        initAdList();
      } else {
        if (id) {
          // 根据广告规则id获取广告集合
          getAdsByRuleId(id);
        }
      }
    });
    // 初始化广告回显
    const initAdList = () => {
      // 获取广告规则
      const A_advertList = store.state.$S_advertManage_A_advertList;
      const B_advertList = store.state.$S_advertManage_B_advertList;
      if (A_advertList && A_advertList.length > 0) {
        const Aads = A_advertList.map((item) => item.name);
        const AadsIds = A_advertList.map((item) => item.id);
        cofficentForm.A_advertList = Aads.join(",");
        cofficentForm.rule = cofficentForm.rule.concat(AadsIds);
        console.log("AadsIds", AadsIds);
      }
      if (B_advertList && B_advertList.length > 0) {
        const Bads = B_advertList.map((item) => item.name);
        const BadsIds = B_advertList.map((item) => item.id);
        cofficentForm.B_advertList = Bads.join(",");
        cofficentForm.rule = cofficentForm.rule.concat(BadsIds);
      }
    };
    const getAdsByRuleId = (id) => {
      Api_getAdListByTimeRule({ id }).then((res) => {
        console.log("res111111111", res);
        const { data } = res.data || [];
        if (data.length > 0) {
          const AadsList = data.filter((item) => item.screenType === 0);
          const BadsList = data.filter((item) => item.screenType === 1);
          // 储存数据到vuex
          store.commit("MUTA_A_ADVERTLIST", AadsList);
          setLocal("advertManage-A-advertList", JSON.stringify(AadsList));
          // 储存数据到vuex
          store.commit("MUTA_B_ADVERTLIST", BadsList);
          setLocal("advertManage-B-advertList", JSON.stringify(BadsList));
          // 初始化广告回显
          initAdList();
        }
      });
    };
    // 获取广告规则详情
    const getDetail = (id) => {
      Api_getAdRuleDetail({ id }).then((res) => {
        const resData = res.data.data;
        console.log("resData", resData);
        cofficentForm.name = resData.name;
        cofficentForm.userNames = resData.userNames;
      });
    };
    // 点击提交规则
    const onSubmit = () => {
      // 如果有id就是修改
      if (adRuleId.value) {
        let param = {
          id: adRuleId.value,
          name: cofficentForm.name,
          rule: JSON.stringify(cofficentForm.rule),
          userNames: cofficentForm.userNames,
        };
        Api_postUpdateAdRule(param).then((res) => {
          console.log(res);
          if (res.data.code === "00000") {
            showToast(res.data.message);
            setTimeout(() => {
              router.back();
            }, 1000);
          }
        });
      } else {
        let param = {
          name: cofficentForm.name,
          rule: JSON.stringify(cofficentForm.rule),
          userNames: cofficentForm.userNames,
        };
        Api_postAddAdRule(param).then((res) => {
          if (res.data.code === "00000") {
            showToast(res.data.message);
            setTimeout(() => {
              router.back();
            }, 1000);
          }
        });
      }
    };
    // 点击筛选
    const searchClk = (val) => {
      router.push(`/advertRuleAddScreen?val=${val}`);
    };
    return {
      titleName,
      cofficentForm,
      onSubmit,
      searchClk,
    };
  },
};
</script>

<style lang="less" scoped></style>
