<script lang="ts" setup>
/**
 * @Name: select-target.vue
 * @Description: 选择定向组件
 * @Author: xinyan
 */

import { Share } from '@element-plus/icons-vue';
import { reactive, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { getCampaignRuleList } from '/@/views/components/auto/auto-campaigns/api';
import { useShopInfo } from '/@/stores/shopInfo';
import { storeToRefs } from 'pinia';
import { getTargetingRuleList } from '/@/views/efTools/automation/api';
import { MatchType } from '/@/views/efTools/utils/enum';

const shopInfo = useShopInfo();
const { profile } = storeToRefs(shopInfo);
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  },
  selectedTargetedRow: {
    type: Object,
    required: true,
  },
});
const emits = defineEmits(['update:modelValue']);
const targetRuleDialogVisible = ref(props.modelValue);
const { selectedTargetedRow } = toRefs(props);
const adGroupId = ref(props.adGroupId);
const campaignInfo = ref(null);
const targetType = ref(null);


const keyWordColumn = ref([
  { field: 'keywordText', title: '关键词', width: 220, },
  { field: 'matchType', title: '匹配方式', formatter: ({ cellValue }) => getMatchTypeLabel(cellValue).label, },
  { type: 'checkbox', align: 'right', width: 55 }
]);
const targetColumn = ref([
  { field: 'expressionDesc', title: '品牌', slots: { default: 'expressionDesc_default' } },
  { type: 'checkbox', align: 'right', width: 55 }
]);
const productColumn = ref([
  { field: 'itemName', title: '商品/分类', slots: { default: 'itemName_default' } },
  { type: 'checkbox', align: 'right', width: 55 }
]);

const gridOptions = reactive({
  height: 550,
  showOverflow: true,
  loading: false,
  checkboxConfig: {
    checkField: 'isSelected'
  },
  rowConfig: {
    isHover: true,
    height: 85,
  },
  columns: keyWordColumn,
  data: []
});

async function fetchTargetRuleList() {
  try {
    gridOptions.loading = true;
    const resp = await getTargetingRuleList({
      campaignType: selectedTargetedRow.value.campaignType,
      campaignId: selectedTargetedRow.value.campaignId,
      adGroupId: selectedTargetedRow.value.adGroupId,
    });

    targetType.value = resp.data.targetType;

    if (targetType.value === 'keyword') {
      gridOptions.columns = keyWordColumn;
      gridOptions.rowConfig.height = 34;
      gridOptions.data = resp.data.targetData.map(item => ({
        ...item,
        isSelected: selectedTargetedRow.value.keywordInfo.some(keyword => keyword.keywordId === item.keywordId)
      }));
    } else if (targetType.value === 'target') {
      gridOptions.rowConfig.height = 85;
      gridOptions.columns = targetColumn;
      gridOptions.data = resp.data.targetData.map(item => ({
        ...item,
        isSelected: selectedTargetedRow.value.campaignTargetInfo.some(target => target.targetId === item.targetId)
      }));

      // 处理 ASIN_SAME_AS 字段
      const asinSameAsList = gridOptions.data
          .filter(item => item.expressionDesc && item.expressionDesc.ASIN_SAME_AS)
          .map(item => item.expressionDesc.ASIN_SAME_AS);

      if (asinSameAsList.length > 0) {
        gridOptions.columns = productColumn;
        gridOptions.rowConfig.height = 120;
        const products = await fetchProductsList(asinSameAsList);

        // 创建一个映射，用于快速查找原始定向规则数据
        const targetMap = new Map(
            gridOptions.data
                .filter(item => item.expressionDesc && item.expressionDesc.ASIN_SAME_AS)
                .map(item => [item.expressionDesc.ASIN_SAME_AS, item])
        );

        gridOptions.data = products.map(product => {
          const originalTarget = targetMap.get(product.asin);
          return {
            ...product,
            targetId: originalTarget?.targetId,
            adGroup_id: originalTarget?.adGroup_id,
            bid: originalTarget?.bid,
            isSelected: selectedTargetedRow.value.campaignTargetInfo.some(
                target => target.targetId === originalTarget?.targetId
            )
          };
        });
      }
    }

    // 预选已选择的定向规则
    campaignInfo.value = gridOptions.data.filter(item => item.isSelected);

    gridOptions.loading = false;
  } catch (error) {
    console.error('Error fetching target rule list:', error);
    ElMessage.error('请求定向数据失败');
    gridOptions.loading = false;
  }
}

function handleCheckChange({ records, row, checked }) {
  if (row) {
    // 单个选择/取消选择
    row.isSelected = checked;
  } else {
    // 全选/取消全选
    records.forEach(record => record.isSelected = checked);
  }
  campaignInfo.value = gridOptions.data.filter(item => item.isSelected);
}

function getMatchTypeLabel(type: string) {
  const matchType = MatchType.find(item => item.value === type);
  if (matchType) {
    return { label: matchType.label, type: type };
  }
  return { label: type, type: '' };
}

function cancel() {
  targetRuleDialogVisible.value = false;
}

function confirm() {
  targetRuleDialogVisible.value = false;
  emits('confirm:selectTarget', {
    campaignInfo: campaignInfo.value,
    targetType: targetType.value,
    adGroupId: selectedTargetedRow.value.adGroupId,  // 添加这行
    campaignId: selectedTargetedRow.value.campaignId  // 添加这行
  });
}

const openProductUrl = (url) => {
  if (url) {
    window.open(url, '_blank');  // 在新标签页中打开链接
  } else {
    console.warn('Product URL is not available');
  }
};

const headerCellStyle = () => {
  return {
    fontSize: '13px',
    // height: '34px',
  };
};

const cellStyle = () => {
  return {
    fontSize: '13px',
    //fontWeight: '500',
  };
};

watch(() => props.modelValue, (newValue) => {
  targetRuleDialogVisible.value = newValue;
});

watch(targetRuleDialogVisible, (newValue) => {
  emits('update:modelValue', newValue);
  fetchTargetRuleList();
});

watch(() => props.selectedTargetedRow, () => {
  // fetchTargetRuleList();
});

</script>


<template>
  <el-dialog v-model="targetRuleDialogVisible"
             style="border-radius: 10px;"
             title="关联广告活动 > 选择定向"
             width="1158px">
    <vxe-grid :cell-style="cellStyle" :header-cell-style="headerCellStyle" v-bind="gridOptions"
              v-on="gridEvents" @checkbox-change="handleCheckChange">
      <template #expressionDesc_default="{ row }">
        <div v-if="row.expressionDesc.ASIN_CATEGORY_SAME_AS">分类:{{ row.expressionDesc.ASIN_CATEGORY_SAME_AS }}</div>
        <div v-if="row.expressionDesc.ASIN_BRAND_SAME_AS">品牌:{{ row.expressionDesc.ASIN_BRAND_SAME_AS }}</div>
        <div v-if="row.expressionDesc.ASIN_PRICE_BETWEEN">商品价格:{{ row.expressionDesc.ASIN_PRICE_BETWEEN }}</div>
        <div v-if="row.expressionDesc.ASIN_REVIEW_RATING_BETWEEN">评分:{{
            row.expressionDesc.ASIN_REVIEW_RATING_BETWEEN
          }}
        </div>
        <div v-if="row.expressionDesc.ASIN_SAME_AS">asin:{{ row.expressionDesc.ASIN_SAME_AS }}</div>
      </template>
      <template #itemName_default="{ row }">
        <div style="display: flex; align-items: flex-start;">
          <!-- 左边图片部分 -->
          <div style="flex-shrink: 0;">
            <img :src="row.main_image" alt="Product Image" height="53" width="53" />
          </div>
          <!-- 右边文字部分 -->
          <div style="margin-left: 10px;">
            <div><strong>{{ row.itemName }}</strong></div>
            <span>ASIN: {{ row.asin }}</span>
            <el-button :icon="Share" link type="primary" @click="openProductUrl(row.productUrl)"></el-button>
          </div>
        </div>
      </template>
    </vxe-grid>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>