<template>
  <div class="addIdx">
    <s-header :name="titleName" :noback="false"></s-header>
    <van-form show-error-message @submit="onSubmit">
      <div class="cust_vantBorder">
        <div class="kBordBott">
          <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'),
              },
            ]" />
        </div>
        <div class="kBordBott">
          <van-field colon :border="false" @click-input="busiInpClk(1)" readonly clearable v-model="cofficentForm.Atype"
            :placeholder="$t('advertManage.advertRule.addRule.adTypePlace')"
            :label="$t('advertManage.advertRule.addRule.adType')">
            <template #right-icon>
              <div class="l-flex-RC">
                <van-icon v-if="cofficentForm.Atype" @click="cofficentForm.Atype = ''" class="o-mr-6" name="clear" />
                <van-icon @click="busiInpClk(1)" name="arrow-down" />
              </div>
            </template>
          </van-field>
          <van-field colon :border="false" v-model="cofficentForm.Ausername" clearable
            :placeholder="$t('advertManage.advertRule.addRule.userNamePlace')"
            :label="$t('advertManage.advertRule.addRule.userName')">
            <template #button>
              <van-button @click="searchClk(0)" type="primary">{{
                $t("advertManage.advertRule.addRule.search")
              }}</van-button>
            </template>
          </van-field>
          <van-field colon :border="false" required @click-input="busiInpClk(2)" readonly clearable
            v-model="cofficentForm.AName" :placeholder="$t('advertManage.advertRule.addRule.AScreenPlace')"
            :label="$t('advertManage.advertRule.addRule.AScreen')" name="AName" :rules="[
              {
                required: true,
                message: $t('advertManage.advertRule.addRule.AScreenPlace'),
              },
            ]">
            <template #right-icon>
              <div class="l-flex-RC">
                <van-icon v-if="cofficentForm.AName" @click="
                  cofficentForm.AName = '';
                cofficentForm.AId = '';
                " class="o-mr-6" name="clear" />
                <van-icon @click="busiInpClk(2)" name="arrow-down" />
              </div>
            </template>
          </van-field>
        </div>
        <div class="kBordBott">
          <van-field colon :border="false" @click-input="busiInpClk(3)" readonly clearable v-model="cofficentForm.Btype"
            :placeholder="$t('advertManage.advertRule.addRule.adTypePlace')"
            :label="$t('advertManage.advertRule.addRule.adType')">
            <template #right-icon>
              <div class="l-flex-RC">
                <van-icon v-if="cofficentForm.Btype" @click="cofficentForm.Btype = ''" class="o-mr-6" name="clear" />
                <van-icon @click="busiInpClk(3)" name="arrow-down" />
              </div>
            </template>
          </van-field>
          <van-field colon :border="false" v-model="cofficentForm.Busername" clearable
            :placeholder="$t('advertManage.advertRule.addRule.userNamePlace')"
            :label="$t('advertManage.advertRule.addRule.userName')">
            <template #button>
              <van-button @click="searchClk(1)" type="primary">{{
                $t("advertManage.advertRule.addRule.search")
              }}</van-button>
            </template>
          </van-field>
          <van-field colon :border="false" required @click-input="busiInpClk(4)" readonly clearable
            v-model="cofficentForm.BName" :placeholder="$t('advertManage.advertRule.addRule.BScreennPlace')"
            :label="$t('advertManage.advertRule.addRule.BScreen')" name="BName" :rules="[
              {
                required: true,
                message: $t('advertManage.advertRule.addRule.BScreennPlace'),
              },
            ]">
            <template #right-icon>
              <div class="l-flex-RC">
                <van-icon v-if="cofficentForm.BName" @click="
                  cofficentForm.BName = '';
                cofficentForm.BId = '';
                " class="o-mr-6" name="clear" />
                <van-icon @click="busiInpClk(4)" name="arrow-down" />
              </div>
            </template>
          </van-field>
        </div>
      </div>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          {{ $t("advertManage.advertRule.addRule.submit") }}
        </van-button>
      </div>
    </van-form>
    <!-- 广告类型选择框 -->
    <van-popup v-model:show="busiPopShow" position="bottom">
      <van-picker :default-index="busiDefaIdx" :title="$t('advertManage.advertRule.addRule.adTypePlace')"
        :columns="busiPopList" :columns-field-names="busiPopFieldName" @confirm="busiPopConfirm"
        @cancel="busiPopCancel" />
    </van-popup>
    <!-- A屏/B屏选择框 -->
    <van-popup v-model:show="screenPopShow" position="bottom">
      <van-picker :default-index="screenDefaIdx" :title="$t('advertManage.advertRule.addRule.selectAd')"
        :columns="screenPopList" :columns-field-names="screenPopFieldName" @confirm="screenPopConfirm"
        @cancel="screenPopCancel" />
    </van-popup>
  </div>
</template>

<script>
// 导入接口
import {
  Api_getAdDetail,
  Api_getAdRuleList,
  Api_postAddAdRule,
  Api_getAdRuleDetail,
  Api_postUpdateAdRule,
} from "@/service/advertManage";
import sHeader from "@/components/SimpleHeader";
import { onMounted, reactive, ref, toRefs } from "vue";
import { showToast } from 'vant';
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
export default {
  components: { sHeader },
  setup() {
    const { t } = useI18n();
    const titleName = ref(t("advertManage.advertRule.addRule.title"));
    const route = useRoute();
    // 广告规则的id
    const adRuleId = ref("");
    onMounted(() => {
      const id = route.query.id || "";
      adRuleId.value = id;
      // 看路径有没有id，有就是编辑
      if (id) {
        titleName.value = t("advertManage.advertRule.addRule.editTitle");
        getDetail(id);
      }
    });
    // 获取广告规则详情
    const getDetail = (id) => {
      Api_getAdRuleDetail({ id }).then((res) => {
        const resData = res.data.data;
        cofficentForm.name = resData.name;
        const rule = JSON.parse(resData.rule);
        if (rule.length > 0) {
          rule.forEach((item) => {
            getAdDetail(item);
          });
        }
      });
    };
    // 根据广告id获取广告详情，填充在屏幕上
    const getAdDetail = (id) => {
      Api_getAdDetail({ id }).then((res) => {
        console.log("res", res);
        if (res.data.code === "00000") {
          const resData = res.data.data;
          // screenType：0：A屏  1：B屏
          if (resData.screenType === 0) {
            cofficentForm.AId = resData.id;
            cofficentForm.AName = resData.name;
            cofficentForm.Atype = resData.equipmentType;
            cofficentForm.Ausername = resData.username;
            // 根据广告类型和商家名称获取广告实体
            // 根据广告类型弹窗找到默认选中下标
            if (cofficentForm.Atype) {
              busiPopList.forEach((item, index) => {
                if (item.id === cofficentForm.Atype) {
                  busiDefaParam.screenA = index;
                }
              });
            }
          } else {
            cofficentForm.BId = resData.id;
            cofficentForm.BName = resData.name;
            cofficentForm.Btype = resData.equipmentType;
            cofficentForm.Busername = resData.username;
            if (cofficentForm.Btype) {
              busiPopList.forEach((item, index) => {
                if (item.id === cofficentForm.Btype) {
                  busiDefaParam.screenB = index;
                }
              });
            }
          }
          getList(resData.screenType);
        }
      });
    };
    // 定义参数
    const cofficentForm = reactive({
      name: "",
      Atype: "",
      Ausername: "",
      AId: "",
      AName: "",
      Btype: "",
      Busername: "",
      BId: "",
      BName: "",
    });
    const router = useRouter();
    // 点击提交规则
    const onSubmit = () => {
      // 如果有id就是修改
      if (adRuleId.value) {
        let param = {
          id: adRuleId.value,
          rule: JSON.stringify([cofficentForm.AId, cofficentForm.BId]),
          name: cofficentForm.name,
        };
        Api_postUpdateAdRule(param).then((res) => {
          console.log(res);
          if (res.data.code === "00000") {
            showToast(res.data.message);
            setTimeout(() => {
              router.back();
            }, 1000);
          }
        });
      } else {
        let param = {
          rule: JSON.stringify([cofficentForm.AId, cofficentForm.BId]),
          name: cofficentForm.name,
        };
        Api_postAddAdRule(param).then((res) => {
          console.log(res);
          if (res.data.code === "00000") {
            showToast(res.data.message);
            setTimeout(() => {
              router.back();
            }, 1000);
          }
        });
      }
    };
    // 选择框类型 1：a广告类型 2：a屏  3：b广告类型 4：b屏
    const selectType = ref(1);
    // 广告类型弹窗
    const busiPopShow = ref(false);
    const busiDefaIdx = ref(0);
    // A屏和B屏不同的
    const busiDefaParam = reactive({
      screenA: 0,
      screenB: 0,
    });
    const busiPopList = reactive([
      {
        name: "280",
        id: "280",
      },
      {
        name: "280en",
        id: "280en",
      },
      {
        name: "301",
        id: "301",
      },
      {
        name: "301en",
        id: "301en",
      },
      {
        name: "320",
        id: "320",
      },
      {
        name: "320en",
        id: "320en",
      },
      {
        name: "330",
        id: "330",
      },
      {
        name: "330en",
        id: "330en",
      },
      {
        name: "P30",
        id: "P30",
      },
      {
        name: "P30en",
        id: "P30en",
      },
    ]);
    const busiPopFieldName = reactive({
      text: "name",
      value: "id",
    });
    const busiInpClk = (idx) => {
      selectType.value = idx;
      switch (idx) {
        case 1:
          busiDefaIdx.value = busiDefaParam.screenA;
          busiPopShow.value = true;
          break;
        case 3:
          busiDefaIdx.value = busiDefaParam.screenB;
          busiPopShow.value = true;
          break;
        case 2:
          screenDefaIdx.value = screenDefaParam.screenA;
          screenPopList.value = searchForm.AList;
          screenPopShow.value = true;
          break;
        case 4:
          screenDefaIdx.value = screenDefaParam.screenA;
          screenPopList.value = searchForm.BList;
          screenPopShow.value = true;
          break;
      }
    };
    const busiPopConfirm = ({ selectedOptions }) => {
      busiPopShow.value = false;
      switch (selectType.value) {
        case 1:
          cofficentForm.Atype = selectedOptions[0].name;
          // 查询广告实体
          getList(0);
          break;
        case 3:
          cofficentForm.Btype = selectedOptions[0].name;
          // 查询广告实体
          getList(1);
          break;
      }
    };
    const busiPopCancel = () => {
      busiPopShow.value = false;
    };
    const searchForm = reactive({
      AList: [],
      BList: [],
    });
    const ABScreen = ref(0);
    // 根据广告类型和商家名称获取广告实体
    const getList = (screenType) => {
      ABScreen.value = screenType;
      let type = "";
      let username = "";
      if (screenType === 0) {
        type = cofficentForm.Atype;
        username = cofficentForm.Ausername;
      } else {
        type = cofficentForm.Btype;
        username = cofficentForm.Busername;
      }
      let param = {
        screenType,
        type,
        username,
      };
      Api_getAdRuleList(param).then((res) => {
        if (screenType === 0) {
          console.log("a屏", res);
          searchForm.AList = res.data.data;
          screenPopList.value = searchForm.AList;
          if (searchForm.AList.length > 0) {
            searchForm.AList.forEach((item, index) => {
              if (item.id === cofficentForm.AId) {
                screenDefaParam.screenA = index;
              }
            });
          }
        } else {
          console.log("b屏", res);
          searchForm.BList = res.data.data;
          screenPopList.value = searchForm.BList;
          if (searchForm.BList.length > 0) {
            searchForm.BList.forEach((item, index) => {
              if (item.id === cofficentForm.BId) {
                screenDefaParam.screenB = index;
              }
            });
          }
        }
      });
    };
    // 屏选择弹窗
    // 默认选择中下标
    const screenPopShow = ref(false);
    const screenDefaIdx = ref(0);
    // A屏和B屏不同的
    const screenDefaParam = reactive({
      screenA: 0,
      screenB: 0,
    });
    const screenPopList = ref([]);
    const screenPopFieldName = reactive({
      text: "name",
      value: "id",
    });
    const screenPopConfirm = ({ selectedOptions }) => {
      if (selectedOptions[0] != null) {
        if (ABScreen.value === 0) {
          cofficentForm.AId = selectedOptions[0].id;
          cofficentForm.AName = selectedOptions[0].name;
        } else {
          cofficentForm.BId = selectedOptions[0].id;
          cofficentForm.BName = selectedOptions[0].name;
        }
      }
      screenPopShow.value = false;
    };
    const screenPopCancel = () => {
      screenPopShow.value = false;
    };
    // 点击搜索按钮
    const searchClk = (idx) => {
      getList(idx);
      screenPopShow.value = true;
    };
    return {
      getList,
      cofficentForm,
      onSubmit,
      busiPopShow,
      busiPopList,
      busiPopFieldName,
      busiInpClk,
      busiPopConfirm,
      busiPopCancel,
      ...toRefs(searchForm),
      screenPopShow,
      screenPopList,
      screenPopFieldName,
      screenPopConfirm,
      screenPopCancel,
      searchClk,
      titleName,
      screenDefaIdx,
      busiDefaIdx,
    };
  },
};
</script>

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