<script lang="ts" setup>
/**
 * @Name: timer-bid.vue
 * @Description: 自动化-分时调价组件
 * @Author: Cheney
 */

import { ref } from 'vue';
import TimerBidTable from '/@/components/TimerBidTable/index.vue';
import SelectTmpl from './select-tmpl.vue';
import { userFormData } from './common';
import SaveRuleDialog from '/@/views/components/auto/auto-campaigns/save-rule-dialog.vue';
import { ElMessage } from 'element-plus';


interface Props {
  data: {
    campaignId: string;
    campaignType: string;
    profileId: string;
    ruleType: number;
  };
  RuleStatusButton?: { [key: string]: any };
  // data: AutoCampaignRule;
}

const props = defineProps<Props>();
const emits = defineEmits(['refresh', 'updateRuleStatusButton']);

const formRef = ref();
const { formData, submitFormData } = userFormData(props);

const tableRef = ref(null);
const timeRange = ref('Option1');
const schedule = ref('Option1');
const bid = ref('1.0');
const bidError = ref(''); // 错误信息
const timeRangeOptions = [
  {
    value: 'Option1',
    label: '24小时: 00:00-23:59',
  },
  {
    value: 'Option2',
    label: '凌晨: 00:00-06:59',
  },
  {
    value: 'Option3',
    label: '上午: 7:00-11:59',
  },
  {
    value: 'Option4',
    label: '工作时: 9:00-16:59',
  },
  {
    value: 'Option5',
    label: '下午: 12:00-16:59',
  },
  {
    value: 'Option6',
    label: '晚上: 17:00-20:59',
  },
  {
    value: 'Option7',
    label: '深夜: 21:00-23:59',
  },
];
const scheduleOptions = [
  {
    value: 'Option1',
    label: '每一天',
  },
  {
    value: 'Option2',
    label: '仅在工作日',
  },
  {
    value: 'Option3',
    label: '仅在周末',
  },
];
const isVisible = ref(true);

const submitDialogVisible = ref(false);

async function submit() {
  await submitFormData();
  ElMessage.success('保存成功');
  emits('refresh');
}

async function handleSubmit() {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    } else {
      if (formData.value.useTmpl) {
        await submit();
      } else {
        submitDialogVisible.value = true;
      }
    }
  });
}

function cancel() {
  emits('refresh');
}

function handleClose() {
  isVisible.value = false;
}

// 验证bid输入值是否合法
function validateBid(value: string) {
  if (value === '') {
    bidError.value = ''; // 空值时不显示错误信息
  } else if (Number(value) >= 100 || Number(value) <= 0) {
    bidError.value = '请输入数值大于0且小于100的数值，可精确到小数点后2位';
  } else {
    bidError.value = '';
  }
}

function handleBidChange(value: string) {
  validateBid(value);
}

const handleApply = () => {
  validateBid(bid.value);
  const bidValue = bid.value === '' ? 0 : parseFloat(bid.value);
  if (!bidError.value && tableRef.value) {
    tableRef.value.applyBid(timeRange.value, schedule.value, bidValue);
  }
};

watch(() => formData.value, (newData) => {
  emits('updateRuleStatusButton', newData.RuleStatusButton);
});

</script>

<template>
  <div class="mx-5">
    <div class="asj-h2">分时调价</div>
    <div class="mt-3.5">
      规则执行时区: PDT
      <div>
        <el-tag v-if="isVisible" class="custom-tag" closable color="#e7edf4" @close="handleClose">
          <template #default>
            <div class="tag-content">
              <strong>自动化分时规则：</strong>
              <p>
                1.
                应用分时调价后，如需手动修改竞价，只能在此操作。在亚马逊后台或其他第三方系统进行的调价操作，竞价将会被当前时段的自动化执行结果覆盖。
              </p>
              <p>2. 广告活动开启分时调价，规则的修改将在下一个整点生效。</p>
            </div>
          </template>
        </el-tag>
      </div>
    </div>
    <SelectTmpl :data="formData" />
    <el-card class="mt-3">
      <el-form ref="formRef" :model="formData" label-position="top" style="margin-top: 20px">
        <el-form-item prop="rule.conditions">
          <template #label>
            <span class="custom-title-icon"></span>
            <span class="asj-h3">设置竞价</span>
          </template>
          <div class="flex flex-col">
            <div class="flex gap-2 my-2">
              <el-select v-model="timeRange" :disabled="formData.useTmpl" style="width: 186px">
                <el-option v-for="item in timeRangeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-select v-model="schedule" :disabled="formData.useTmpl" style="width: 186px">
                <el-option v-for="item in scheduleOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-input v-model="bid" :disabled="formData.useTmpl"
                        clearable
                        oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
                        placeholder="1.0"
                        style="width: 150px"
                        @change="handleBidChange"
              ></el-input>
              <div v-if="bidError" style="font-size: 12px;">{{ bidError }}</div>
              <el-button :disabled="formData.useTmpl" class="active-btn" link style="color: #3c58af"
                         @click="handleApply">应用
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <TimerBidTable
          ref="tableRef"
          :data="formData.rule.conditions"
          :disabled="formData.useTmpl"
          @click="formRef.clearValidate('rule.conditions')" />
    </el-card>

    <SaveRuleDialog
        v-model="submitDialogVisible"
        :formData="formData"
        :formRef="formRef"
        @submit="submit"
    />
    <div class="auto-page-foot">
      <el-button style="width: 200px" @click="cancel">取消</el-button>
      <el-button style="width: 200px" type="primary" @click="handleSubmit">提交</el-button>
    </div>
  </div>
</template>

<style scoped>
.active-btn:hover {
  color: #7a9ce4 !important; /* 如果需要改变字体颜色 */
  transition: all 0.3s; /* 添加过渡效果 */
}

.active-btn:disabled {
  color: #c0c4cc !important;
  cursor: not-allowed;
  /* pointer-events: none; !* 禁用点击事件 *! */
}

.custom-title-icon {
  padding-right: 10px;
}

.custom-title-icon:before {
  content: '';
  width: 4px;
  height: 15px;
  background: #3569d6;
  position: absolute;
  transform: translateY(25%);
}

.custom-tag {
  height: auto;
  padding: 8px 8px 8px 16px;
  color: #505968;
  border-color: #abbbd8;
  align-items: flex-start !important;
  white-space: normal;
  line-height: 1.5;
}

.tag-content {
  display: block;
  max-width: 100%;
}
</style>
