<template>
  <div class="apps-form">
    <el-dialog :title="'修改营销配置'" width="880" v-model="visible" :close-on-click-modal="false" :destroy-on-close="true" draggable>
        <el-form-item :label="'应用名称'" prop="appName">
          <el-input style="width: 200px;" v-model="state.ruleForm.appName" disabled />
        </el-form-item>
        <el-form ref="menuDialogFormRef"
          :model="state.ruleForm"
          class="demo-form-inline"
          v-loading="loading">
        <el-form-item :label="'营销开关'" prop="isMarketing">
          <el-switch v-model="state.ruleForm.isMarketing" style="--el-switch-on-color: rgb(48, 185, 113);" 
            inline-prompt :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item :label="'域名限制'" prop="domainLimit">
          <el-switch v-model="state.ruleForm.domainLimit" style="--el-switch-on-color: rgb(48, 185, 113);" 
            inline-prompt :active-value="true" :inactive-value="false" />
        </el-form-item>
        <el-form-item :label="'触发频率'" prop="triggerNum">
          <el-input style="width: 200px;" v-model="state.ruleForm.triggerNum" :placeholder="'请输入触发频率'" clearable />
        </el-form-item>
        <el-form-item :label="'触发规则'" prop="triggerRule">
          <el-select style="width: 200px;" v-model="state.ruleForm.triggerRule" placeholder="">
            <el-option v-for="item in triggerRules" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <JCollapse
        :data="[
          { title: 'IP集合', id: '1'},
        ]"
        @update="(item: any) => listEditOpen = true"
        @delete="(item: any) => ipDeletable = !ipDeletable"
        :deleteText="t('marketingConfig.deleteText')"
        :updateText="'新增'"
        style="margin-top: 30px;"
        :activeNames="['1']"
      >
        <template #default>
          <div class="border-b p-2 items-center flex flex-wrap collapse-group">
            <div class="collapse-group-name">白名单：</div>
            <div class="tag-content">
              <template v-for="item in ips.whitelist" :key="item.id">
                <!-- 具体IP(段) -->
                <el-tag v-if="item.sourceType == 2" @click="getIpList(item)" effect="light" :closable="ipDeletable"
                  @close="handleDelectIp(item)"
                  color="#f4f4f4" round class="ml-1 cursor-pointer" style="margin-bottom: 4px;">
                  {{ item.startIp }}{{ item.ipMode == 2 ? (' / ' + item.endIp.split('.').pop()) : '' }}
                </el-tag>
                <!-- 分组 -->
                <el-popover v-else width="200" trigger="hover" placement="top">
                  <div class="flex flex-wrap">
                    <!-- <span v-for="ip in item.ips" :key="ip" class="ml-2">
                      {{ ip }}
                    </span> -->
                    {{ item.groupName }}
                  </div>
                  <template #reference>
                    <el-tag @click="getIpList(item)" effect="light" :closable="ipDeletable"
                      @close="handleDelectIp(item)"
                      color="#f4f4f4" round class="ml-1 cursor-pointer" style="margin-bottom: 4px;">
                      {{ item.groupName }}
                    </el-tag>
                  </template>
                </el-popover>
              </template>
            </div>
          </div>
          <div class="p-2 items-center flex flex-wrap collapse-group">
            <div class="collapse-group-name">黑名单：</div>
            <div class="tag-content">
              <template v-for="item in ips.blacklist" :key="item.id">
                <!-- 具体IP(段) -->
                <el-tag v-if="item.sourceType == 2" @click="getIpList(item)" effect="light" :closable="ipDeletable"
                  @close="handleDelectIp(item)"
                  color="#f4f4f4" round class="ml-1 cursor-pointer" style="margin-bottom: 4px;">
                  {{ item.startIp }}{{ item.ipMode == 2 ? (' / ' + item.endIp.split('.').pop()) : '' }}
                </el-tag>
                <!-- 分组 -->
                <el-popover v-else width="200" trigger="hover" placement="top">
                  <div class="flex flex-wrap">
                    <!-- <span v-for="ip in item.ips" :key="ip" class="ml-2">
                      {{ ip }}
                    </span> -->
                    {{ item.groupName }}
                  </div>
                  <template #reference>
                    <el-tag @click="getIpList(item)" effect="light" :closable="ipDeletable"
                      @close="handleDelectIp(item)"
                      color="#f4f4f4" round class="ml-1 cursor-pointer" style="margin-bottom: 4px;">
                      {{ item.groupName }}
                    </el-tag>
                  </template>
                </el-popover>
              </template>
            </div>
          </div>
        </template>
      </JCollapse>
      <JCollapse
        :data="[
          { title: '域名集合', id: '1'},
        ]"
        @update="(item: any) => domainEditOpen = true"
				@delete="(item: any) => domainDeletable = !domainDeletable"
        :deleteText="t('marketingConfig.deleteText')"
        :updateText="'新增'"
        style="margin-top: 30px;"
        :activeNames="['1']"
      >
        <template #default>
          <div class="p-2 items-center flex flex-wrap">
            <el-tag v-for="item in domains" :key="item"
              @close="handleDelectDomain(item)" effect="light" :closable="domainDeletable"
              style="margin-bottom: 4px;" color="#f4f4f4" round class="ml-1 cursor-pointer">
              {{ item.domain }}
            </el-tag>
          </div>
        </template>
      </JCollapse>
      <div class="title">备注</div>
      <el-input
        :rows="4"
        v-model="state.ruleForm.remark"
        type="textarea"
        placeholder="请输入备注"
      ></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">{{ t('common.cancelButtonText') }}</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">{{ t('common.confirmButtonText') }}</el-button>
        </span>
      </template>
    </el-dialog>
    <ListEdit v-model:open="listEditOpen" />
		<DomainEdit v-model:open="domainEditOpen" />
  </div>
</template>

<script setup lang="ts" name="systemMenuDialog">
import { ElMessage } from 'element-plus';
import {useI18n} from 'vue-i18n';
const JCollapse = defineAsyncComponent(() => import('/@/components/JCollapse/index.vue'));
const ListEdit = defineAsyncComponent(() => import('./listEdit.vue'));
const DomainEdit = defineAsyncComponent(() => import('./domainEdit.vue'));

interface IpItem {
  id: String;
  ipMode: Number;
  ipType: Number;
  sourceType: Number; // 1:分组 2:具体Ip(段)
  startIp: String;
  endIp: String;
  groupId: String;
  groupName: String;
}

interface Ips {
  blacklist: IpItem[];
  whitelist: IpItem[];
}

interface DomianItem {
  id: String;
  domain: String;
  sourceType: Number; // 1:分组 2:具体域名
  groupId: String;
  groupName: String;
}

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const {t} = useI18n();

// 定义变量内容
const visible = ref(false);
const loading = ref(false);
const add = ref(false);
const menuDialogFormRef = ref();
const ips = ref<Ips>({
  blacklist: [],
  whitelist: []
});
const domains = ref<DomianItem[]>([]);
const ipDeletable = ref(false);// 控制 IP 列表项是否可删除
const domainDeletable = ref(false);// 控制域名列表项是否可删除
const ipAdd = ref(false);
const domainAdd = ref(false);
const listEditOpen = ref(false);
const domainEditOpen = ref(false);

const triggerRules = [
  {
    label: '仅一次',
    value: 1,
  },
  {
    label: '多次',
    value: 2,
  },
]

// 定义需要的数据
const state = reactive({
  ruleForm: {
    marketingEnabled: false, 
    domainRestriction: false,
    ipSets: [''], // ip集合
    domainSets: [''], // ip集合
    remark: '',
  },
  domainSets: [] as any[], // 应用下拉框列表
});

const handleDelect = ()=>{
  console.log('delect')
}

const getIpList = (detail) => {
  if(detail.sourceType == 1) {
    // 获取ip组
    console.log(detail.groupId);

  }
}

// 删除ip
const handleDelectIp = (deleteItem: IpItem)=>{
  ips.value.whitelist = ips.value.whitelist.filter((item: any) => item.id != deleteItem.id);
  ips.value.blacklist = ips.value.blacklist.filter((item: any) => item.id != deleteItem.id);
}

// 删除域名
const handleDelectDomain = (deleteItem: DomianItem)=>{
  console.log('delectDomain')
  domains.value = domains.value.filter((item: any) => item.id != deleteItem.id);
}

// 打开弹窗
const openDialog = async (type: string, row: any, str: string = 'domain') => {
  state.ruleForm = {
    marketingEnabled: false, 
    domainRestriction: false,
    ipSets: [''],
    domainSets: [''],
    remark: '',
  };
  visible.value = true;
  
  state.ruleForm = row;
  console.log(row);
  ips.value.whitelist = row.ips.filter((item: any) => item.ipType == '1');
  ips.value.blacklist = row.ips.filter((item: any) => item.ipType == '2');
  console.log(ips.value);
  
  domains.value = row.domains;
};

// 保存数据
const onSubmit = async () => {
  console.log(state.ruleForm)
  ElMessage.success('提交成功！');
  visible.value = false;
  // try {
  //   loading.value = true;
  //   await save(state.ruleForm);
  //   useMessage().success(t(state.ruleForm.id ? 'common.editSuccessText' : 'common.addSuccessText'));
  //   visible.value = false;
  //   emit('refresh');
  // } catch (err: any) {
  //   useMessage().error(err.msg);
  // } finally {
  //   loading.value = false;
  // }
};

// 暴露变量 只有暴漏出来的变量 父组件才能使用
defineExpose({
  openDialog,
});
</script>
<style lang="scss">
.config-container {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: 400;
  width: 100%;
  justify-content: start;
}
.config-actions {
  width: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.apps-loadmore.el-select-dropdown .el-scrollbar__wrap {
  height: 330px !important;
}
.apps-form {
  .collapse-group {
    display: flex;
    justify-content: start;
    align-items:first baseline;
  }
  .collapse-group-name {
    // width: 100px;
  }
  .tag-content {
    flex: 1;
  }
  .el-overlay {
    .el-overlay-dialog {
      .el-dialog {
        .el-dialog__body {
          padding: 0 !important;
        }
      }
    }
  }
  .demo-form-inline .el-switch {
    margin-right: 50px;
  }
  .title {
    line-height: 20px;
    font-family: Source Han Sans SC;
    font-size: 14px;
    color: rgba(18, 18, 18, 1);
    margin: 30px 0 12px;
  }

  .el-collapse-item__content {
    padding: 0;
  }
}
</style>