<template>
  <div class="rule-form-container">
    <!-- 头部导航 -->
    <s-header :name="titleName" :noback="false" />

    <!-- 表单区域 -->
    <van-form show-error-message @submit="onSubmit" class="rule-form">
      <div class="form-section">
        <!-- 规则名称字段 -->

        <van-field
          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'),
            },
          ]"
          class="custom-field"
        >
          <template #left-icon>
            <van-icon name="label" color="#1989fa" />
          </template>
        </van-field>

        <!-- 推送商户字段 -->
        <van-field
          v-model="cofficentForm.userNames"
          clearable
          name="userNames"
          :label="$t('advertManage.advertRule.addRule.pushMerchant')"
          :placeholder="$t('advertManage.advertRule.addRule.pushMerchantPlace')"
          class="custom-field"
        >
          <template #left-icon>
            <van-icon name="shop" color="#1989fa" />
          </template>
        </van-field>
      </div>

      <!-- 屏幕广告设置部分 -->
      <div class="form-section">

        <!-- A屏幕广告设置 -->
        <div class="screen-config">
          <div class="screen-header">
            <div class="screen-title">
              <van-icon name="tv-o" color="#ee0a24" class="screen-icon" />
              <span>{{ $t("advertManage.advertRule.addRule.AScreen") }}</span>
            </div>
            <van-button
              size="small"
              icon="search"
              type="primary"
              @click="searchClk(0)"
              class="select-button"
            >
              {{ $t("advertManage.advertRule.addRule.screen") }}
            </van-button>
          </div>
          <div class="selected-content" v-if="cofficentForm.A_advertList">
            {{ cofficentForm.A_advertList }}
          </div>
          <div v-else class="placeholder">
            {{ $t("advertManage.advertRule.addRule.AScreenPlace") }}
          </div>
        </div>

        <!-- B屏幕广告设置 -->
        <div class="screen-config">
          <div class="screen-header">
            <div class="screen-title">
              <van-icon name="tv-o" color="#1989fa" class="screen-icon" />
              <span>{{ $t("advertManage.advertRule.addRule.BScreen") }}</span>
            </div>
            <van-button
              size="small"
              icon="search"
              type="primary"
              @click="searchClk(1)"
              class="select-button"
            >
              {{ $t("advertManage.advertRule.addRule.screen") }}
            </van-button>
          </div>
          <div class="selected-content" v-if="cofficentForm.B_advertList">
            {{ cofficentForm.B_advertList }}
          </div>
          <div v-else class="placeholder">
            {{ $t("advertManage.advertRule.addRule.BScreennPlace") }}
          </div>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-section">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          icon="passed"
          size="large"
          class="submit-button"
        >
          {{ $t("advertManage.advertRule.addRule.submit") }}
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
// 导入公用方法
import { setLocal } 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(() => {
      // 加载样式
      // 如果是第一次进入页面就请求接口
      const id = route.query.id || "";
      adRuleId.value = id;
      // 看路径有没有id，有就是编辑
      if (id) {
        titleName.value = t("advertManage.advertRule.addRule.editTitle");
        getDetail(id);
      }
      // 获取广告规则
      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);
      }
      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) => {
        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;
        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) => {
          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>
@primary-color: #4d6add;

.rule-form-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  // padding: 0 16px 20px;
  display: flex;
  flex-direction: column;
}

.rule-form {
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
  flex: 1;
}

.form-section {
  margin-bottom: 24px;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;

  .form-icon {
    margin-right: 10px;
    color: @primary-color;
  }

  h3 {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

.custom-field {
  background-color: #fafafa;
  border-radius: 10px;
  padding: 10px 16px;
  margin-bottom: 15px;

  :deep(.van-field__label) {
    font-weight: 500;
    color: #555;
  }

  :deep(.van-field__control) {
    color: #333;
  }
}

.screen-config {
  background: #f9f9f9;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  border: 1px solid #eee;

  .screen-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }

  .screen-title {
    display: flex;
    align-items: center;
    font-size: 15px;
    font-weight: 500;
    color: #333;

    .screen-icon {
      margin-right: 8px;
      font-size: 18px;
    }
  }

  .select-button {
    border-radius: 20px;
    padding: 0 15px;
  }

  .selected-content {
    padding: 12px;
    background-color: #e6f7ff;
    border-radius: 8px;
    border: 1px dashed #91d5ff;
    color: #0050b3;
    font-size: 14px;
    line-height: 1.4;
    margin-top: 8px;
  }

  .placeholder {
    padding: 12px;
    color: #bfbfbf;
    font-style: italic;
    text-align: center;
    font-size: 14px;
    background-color: #fafafa;
    border-radius: 8px;
    margin-top: 8px;
  }
}

.submit-section {
  padding-top: 16px;
  margin-top: 20px;
  border-top: 1px dashed #f0f0f0;

  .submit-button {
    height: 46px;
    font-size: 16px;
    font-weight: 500;
    box-shadow: 0 4px 10px rgba(24, 144, 255, 0.3);

    &:active {
      opacity: 0.9;
      transform: scale(0.98);
    }
  }
}

@media (max-width: 480px) {
  .rule-form {
    padding: 16px;
  }

  .screen-config {
    padding: 12px;
  }

  .form-header {
    h3 {
      font-size: 15px;
    }
  }
}
</style>
