import { ref, unref } from 'vue';
import XEUtils from 'xe-utils';
import { ElMessage } from 'element-plus';
import { weekColumns } from '/@/views/reportManage/dataCenter/utils/columns';
import { weekMetricsEnum } from '/@/views/reportManage/dataCenter/utils/enum';


export function buildChartOpt(option: any, metrics: any[]) {
  const tmp: any = {};
  const opt: any = {
    legend: { selected: {} },
    yAxis: [],
    series: [],
  };
  for (const info of metrics) {
    tmp[info.color] = info;
  }
  for (const info of option.series) {
    const color = info.itemStyle.color;
    const metricInfo = tmp[color];
    if (metricInfo) {
      opt.series.push({
        id: info.id,
        name: metricInfo.label,
        encode: { y: metricInfo.metric },
      });
      opt.yAxis.push({ id: info.id, name: metricInfo.label, show: true });
    } else {
      opt.yAxis.push({ id: info.id, show: false });
    }
  }
  for (const label of Object.keys(option.legend.selected)) {
    if (XEUtils.findIndexOf(metrics, (info) => info.label === label) === -1) {
      opt.legend.selected[label] = false;
    } else {
      opt.legend.selected[label] = true;
    }
  }
  //console.log(opt)
  return opt;
}

export function parseQueryParams(body: any) {
  const ret: any = {};

  for (const key in body) {
    const val = unref(body[key]);
    if (key === 'currentDate') {
      if (val.dailyStartDate && val.dailyTime) {
        ret['data_start_date'] = val.dailyStartDate;
        ret['data_end_date'] = val.dailyTime;
      }
      if (val.weekStartDate && val.weekEndDate) {
        ret['data_start_date'] = val.weekStartDate;
        ret['data_end_date'] = val.weekEndDate;
      }
      if (val.startDate && val.endDate) {
        ret['data_start_date'] = val.startDate;
        ret['data_end_date'] = val.endDate;
      }
    } else if (key === 'taskIds') {
      ret['task_ids'] = val; // 将 task_ids 直接赋给返回对象的属性
    } else {
      ret[key] = val;
    }
  }
  return ret;
}

export function monthlyQueryParams(body: any) {
  const date: any = {};
  for (const key in body) {
    const val = unref(body[key]);
    if (key === 'monthCurrentDate') {
      date['month_start_date'] = val.startDate;
      date['month_end_date'] = val.endDate;
    } else if (key === 'taskIds') {
      date['task_ids'] = val; // 将 task_ids 直接赋给返回对象的属性
    } else {
      date[key] = val;
    }
  }
  return date;
}

export function flattenColumns(columns) {
  let result = [];
  columns.forEach(column => {
    if (column.children && column.children.length > 0) {
      result = result.concat(flattenColumns(column.children));
    } else {
      result.push(column);
    }
  });
  return result;
}

export function validateNumericFields(fields: Record<string, any>, fieldsToValidate: string[]): boolean {
  const numericFields = ['sales_original', 'total_sales_current_monthly_original', 'ad_sales_original', 'ad_cost_original', 'money_by_amazon', 'money_by_other', 'refundRate'];
  const integerFields = ['impression', 'ad_click', 'ad_order', 'session', 'order', 'availableSalesDay', 'intransitInventory', 'overseasStorage'];

  for (const field of fieldsToValidate) {
    const value = fields[field];
    const flatWeekColumns = ref(flattenColumns(weekColumns.value));
    const column = flatWeekColumns.value.find(col => col.field === field);
    const title = column ? column.title : field;

    if (numericFields.includes(field)) {
      if (value === null || value === undefined || value === '') {
        ElMessage.warning(`${ title } 不能为空`);
        return false;
      }
      if (isNaN(Number(value))) {
        ElMessage.warning(`${ title } 必须为数字`);
        return false;
      }
    } else if (integerFields.includes(field)) {
      if (value === null || value === undefined || value === '') {
        ElMessage.warning(`${ title } 不能为空`);
        return false;
      }
      if (!Number.isInteger(Number(value)) || isNaN(Number(value))) {
        ElMessage.warning(`${ title } 必须为整数`);
        return false;
      }
    }
  }
  return true;
}

export function validateNumber(rule, value) {
  if (value !== '' && isNaN(value)) {
    const fieldName = rule.field; // 获取当前字段名称
    const flatWeekColumns = ref(flattenColumns(weekColumns.value));
    const column = flatWeekColumns.value.find(col => col.field === fieldName);
    const title = column ? column.title : field;

    if (title) {
      return new Error(`${title} 必须为数字`);
    } else {
      return new Error('输入值必须为数字'); // 如果无法找到对应的 label，使用通用错误信息
    }
  }
  return true; // 输入有效
}

