<script lang="ts" setup>/**
 * @Name: CreateDialog.vue
 * @Description: 数据录入-创建
 * @Author: xinyan
 */
import { computed, onMounted, reactive, ref } from 'vue';
import { FormInstance, FormRules } from 'element-plus';
import { dayColumns, monthColumns, weekColumns } from '/src/views/reportManage/dataCenter/utils/columns';
import { flattenColumns, validateNumber } from '/src/views/reportManage/dataCenter/utils/tools';
import { postCreateDayData, postCreateMonthData, postCreateWeekData } from '/src/views/reportManage/dataCenter/api';
import TipDialog from '/src/views/reportManage/dataCenter/normalDisplay/components/DataEntryTable/components/TipDialog.vue';


const props = defineProps({
  currentRow: Object,
  dateType: String,
  ySalesData: Object,
  currentDate: Object,
});
const { currentRow, dateType, ySalesData, currentDate } = props;

const createOpen = defineModel({ default: false });
const emit = defineEmits(['refresh']);

const openTip = ref(false);
const dialogMessage = ref('');
const isSubmitting = ref(false);
const isNormal = ref(false);

interface taskDataForm {
  sales_original: number,
  ad_sales_original: number,
  ad_cost_original: number,
  total_sales_current_monthly_original: number;
  impression: number;
  ad_click: number;
  ad_order: number;
  money_by_amazon: number;
  money_by_other: number;
  session: number;
  order: number;
  availableSalesDay: number;
  intransitInventory: number;
  overseasStorage: number;
  refundRate: number;
}

const taskDataFormRef = ref<FormInstance>();
const taskDataForm = reactive({
  sales_original: null,
  ad_sales_original: null,
  ad_cost_original: null,
  total_sales_current_monthly_original: null,
  impression: null,
  ad_click: null,
  ad_order: null,
  session: null,
  order: null,
  availableSalesDay: null,
  intransitInventory: null,
  overseasStorage: null,
  refundRate: null,
  money_by_amazon: null,
  money_by_other: null,
});

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const rules = reactive<FormRules>({
  sales_original: [
    { required: true, message: '请输入销售额', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },
  ],
  ad_sales_original: [
    { required: true, message: '请输入广告销售额', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },
  ],
  ad_cost_original: [
    { required: true, message: '请输入广告花费', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },
  ],
  total_sales_current_monthly_original: [
    { required: true, message: '请输入当月销售额', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },
  ],
  impression: [{ required: true, message: '请输入广告展示量', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },],
  ad_click: [{ required: true, message: '请输入广告点击量', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },],
  ad_order: [{ required: true, message: '请输入广告订单量', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },],
  money_by_amazon: [{ required: true, message: '请输入截止目前Amazon回款金额', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },],
  money_by_other: [{ required: true, message: '请输入截止目前Other回款金额', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },],
  session: [{ required: true, message: '请输入会话数', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },],
  order: [{ required: true, message: '请输入订单', trigger: 'blur' }],
  availableSalesDay: [{ required: true, message: '请输入可用销量天数', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },],
  intransitInventory: [{ required: true, message: '请输入在途库存', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },],
  overseasStorage: [{ required: true, message: '请输入海外仓库存', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },],
  refundRate: [{ required: true, message: '请输入最近90天平台退货率', trigger: 'blur' }],
});

const flatDayColumns = ref(flattenColumns(dayColumns.value));
const flatWeekColumns = ref(flattenColumns(weekColumns.value));
const flatMonthColumns = ref(flattenColumns(monthColumns.value));

const filteredDayColumns = computed(() => {
  const flat = flatDayColumns.value;
  return flat.filter(item => !['平台编号', '平台名称', '国家', '品牌', '操作', '运营', '销售额', '广告销售额', '广告花费', '平台币种'].includes(item.title));
});

const filteredWeekColumns = computed(() => {
  const flat = flatWeekColumns.value;
  return flat.filter(item => !['平台编号', '平台名称', '国家', '品牌', '操作', '运营', '销售额', '广告销售额', '广告花费', '当月累计销售额', '平台币种', '回款/余额币种'].includes(item.title));
});

const filteredMonthColumns = computed(() => {
  const flat = flatMonthColumns.value;
  return flat.filter(item => !['平台编号', '平台名称', '国家', '品牌', '操作', '运营', '销售额', '广告销售额', '广告花费', '平台币种'].includes(item.title));
});

//表单规则
function createDayDataRules() {
  if (dateType === 'day') {
    rules.ad_sales_original[0].required = false;
    rules.ad_cost_original[0].required = false;
  }
  if (dateType === 'month') {
    rules.ad_sales_original[0].required = false;
    rules.ad_cost_original[0].required = false;
    rules.impression[0].required = false;
    rules.ad_click[0].required = false;
    rules.ad_order[0].required = false;
  }
}

//创建日数据
async function createDayData() {
  const body = {
    sales_original: taskDataForm.sales_original,
    ad_sales_original: taskDataForm.ad_sales_original,
    ad_cost_original: taskDataForm.ad_cost_original,
    data_datetime: currentDate.day_start_date,
    task: currentRow.task,
  };
  if (!currentRow.id) {
    try {
      const resp = await postCreateDayData(body);
      if (resp.code === 2000) {
        createOpen.value = false;
        emit('refresh');
        taskDataFormRef.value.resetFields();
        await VXETable.modal.message({ content: '创建成功', status: 'success' });
      }
    } catch (e) {
      await VXETable.modal.message({ content: '创建失败', status: 'error' });
    }
  } else {
    createOpen.value = false;
    await VXETable.modal.message({ content: '此日期对应数据已存在', status: 'error' });
  }
}

//创建周数据
async function createWeekData() {
  const body = {
    sales_original: taskDataForm.sales_original,
    ad_sales_original: taskDataForm.ad_sales_original,
    ad_cost_original: taskDataForm.ad_cost_original,
    total_sales_current_monthly_original: taskDataForm.total_sales_current_monthly_original,
    impression: taskDataForm.impression,
    ad_click: taskDataForm.ad_click,
    ad_order: taskDataForm.ad_order,
    money_by_amazon: taskDataForm.money_by_amazon,
    money_by_other: taskDataForm.money_by_other,
    session: taskDataForm.session,
    order: taskDataForm.order,
    availableSalesDay: taskDataForm.availableSalesDay,
    intransitInventory: taskDataForm.intransitInventory,
    overseasStorage: taskDataForm.overseasStorage,
    refundRate: taskDataForm.refundRate,
    sales_start_time: currentDate.week_start_date,
    sales_end_time: currentDate.week_end_date,
    ad_start_time: currentDate.ad_start_time,
    ad_end_time: currentDate.ad_end_time,
    task: currentRow.task,
  };
  if (!currentRow.id) {
    try {
      const resp = await postCreateWeekData(body);
      if (resp.code === 2000) {
        createOpen.value = false;
        emit('refresh');
        taskDataFormRef.value.resetFields();
        await VXETable.modal.message({ content: '创建成功', status: 'success' });
      }
    } catch (e) {
      await VXETable.modal.message({ content: '创建失败', status: 'error' });
    }
  } else {
    createOpen.value = false;
    await VXETable.modal.message({ content: '此日期对应数据已存在', status: 'error' });
  }
}

//创建月数据
async function createMonthData() {
  const body = {
    sales_original: taskDataForm.sales_original,
    ad_sales_original: taskDataForm.ad_sales_original,
    ad_cost_original: taskDataForm.ad_cost_original,
    impression: taskDataForm.impression,
    ad_click: taskDataForm.ad_click,
    ad_order: taskDataForm.ad_order,
    data_start_time: currentDate.month_start_date,
    data_end_time: currentDate.month_end_date,
    task: currentRow.task,
  };
  if (!currentRow.id) {
    try {
      const resp = await postCreateMonthData(body);
      if (resp.code === 2000) {
        createOpen.value = false;
        emit('refresh');
        taskDataFormRef.value.resetFields();
        await VXETable.modal.message({ content: '创建成功', status: 'success' });
      }
    } catch (e) {
      await VXETable.modal.message({ content: '创建失败', status: 'error' });
    }
  } else {
    createOpen.value = false;
    await VXETable.modal.message({ content: '此日期对应数据已存在', status: 'error' });
  }
}

//创建任务
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl || isSubmitting.value) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const fieldsToWarn = validateForm();
      isNormal.value = validateForm2();
      if (fieldsToWarn.length > 0 || isNormal.value) {
        openTip.value = true;
        dialogMessage.value = `${ fieldsToWarn.join(', ') }`;
        return;
      } else {
        isSubmitting.value = true;
        try {
          await submit(formEl);
        } finally {
          isSubmitting.value = false;
        }
      }
    }
  });
};

const submit = async () => {
  openTip.value = false;
  if (dateType === 'day') {
    // const fieldsToValidate = ['sales_original'];
    // if (!validateNumericFields(taskDataForm, fieldsToValidate)) return; // 验证字段
    await createDayData();
  }
  if (dateType === 'week') {
    // const fieldsToValidate = ['sales_original', 'ad_sales_original', 'ad_cost_original', 'total_sales_current_monthly_original', 'impression', 'ad_click', 'ad_order', 'money_by_amazon', 'money_by_other', 'session', 'order', 'availableSalesDay', 'intransitInventory', 'overseasStorage', 'refundRate'];
    // if (!validateNumericFields(taskDataForm, fieldsToValidate)) return; // 验证字段
    await createWeekData();
  }
  if (dateType === 'month') {
    // const fieldsToValidate = ['sales_original'];
    // if (!validateNumericFields(taskDataForm, fieldsToValidate)) return; // 验证字段
    await createMonthData();
  }
};

function handleClose(done: Function) {
  if (taskDataFormRef.value) taskDataFormRef.value.resetFields();
  done();
}

// 验证与前一天偏移值
const validateForm = () => {
  const fieldsToWarn = [];
  const fieldsToValidate = ['sales_original', 'total_sales_current_monthly_original'];
  if (ySalesData) {
    for (const key of fieldsToValidate) {
      const newValue = taskDataForm[key];
      const yDayValue = ySalesData[key];
      const column = flatWeekColumns.value.find(col => col.field === key);
      const title = column ? column.title : key;

      if (newValue != null && yDayValue !== null && yDayValue !== undefined) {
        const diffPercentage = Math.abs((newValue - yDayValue) / yDayValue) * 100;
        if (diffPercentage > 50) {
          fieldsToWarn.push(title);
        }
      }
    }
  }
  return fieldsToWarn;
};

// 验证ROI
const validateForm2 = () => {
  const adSalesValue = taskDataForm['ad_sales_original'];
  const adCostValue = taskDataForm['ad_cost_original'];

  if (adSalesValue != null && adCostValue != null && adCostValue !== 0) {
    const ratio = (adSalesValue - adCostValue) / adCostValue;
    return ratio < 0;
  }
};

onMounted(() => {
  createDayDataRules();
});
</script>

<template>
  <el-dialog v-model="createOpen" :before-close="handleClose" :close-on-click-modal="false"
             :close-on-press-escape="false"
             style="border-radius: 10px;"
             width="600">
    <template #title>
      <span class="text-xl">数据录入 - 创建</span>
      <div class="mt-2" style="display: flex; align-items: center;color: darkgray">
        <div style="margin-right: 8px;">
          平台编号:
          <span class="italic pl-1 pr-2">{{ currentRow.platformNumber }}</span>
        </div>
        <div>
          平台名称:
          <span class="italic pl-1">{{ currentRow.platformName }}</span>
        </div>
      </div>
    </template>
    <el-form
        ref="taskDataFormRef"
        :model="taskDataForm"
        :rules="rules"
        label-position="top"
        label-width="auto"
        status-icon
        style="max-width: 600px;">
      <div v-if="dateType === 'day'">
        <el-form-item v-for="item in filteredDayColumns" :key="item.field" :label="item.title" :prop="item.field">
          <el-input v-model="taskDataForm[item.field]" :placeholder="`请输入${item.title}`" />
        </el-form-item>
      </div>
      <div v-if="dateType === 'week'" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 5px">
        <el-form-item v-for="item in filteredWeekColumns" :key="item.field" :label="item.title" :prop="item.field">
          <el-input v-model="taskDataForm[item.field]" style="width: 100%" />
        </el-form-item>
      </div>
      <div v-if="dateType === 'month'">
        <el-form-item v-for="item in filteredMonthColumns" :key="item.field" :label="item.title" :prop="item.field">
          <el-input v-model="taskDataForm[item.field]" :placeholder="`请输入${item.title}`" />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="createOpen = false ;resetForm(taskDataFormRef)">取消</el-button>
        <el-button
            :disabled="isSubmitting"
            type="primary"
            @click="submitForm(taskDataFormRef)"
        >
          {{ isSubmitting ? '提交中...' : '确认' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
  <TipDialog v-if="openTip" v-model="openTip" :message="dialogMessage" :isNormal="isNormal"
             @submit="submit()"></TipDialog>
</template>

<style scoped>

</style>