<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { ContestItem, ContestCreateParams, ContestUpdateParams } from '../types'

import { ElMessage } from 'element-plus'
import { pick } from 'lodash-es'
import dayjs from 'dayjs'
import isBetween from 'dayjs/plugin/isBetween'

import { createContest, updateContest, getExamList } from '../api'
import { useMapStore } from '@/stores/map'
import { useGetTeacherList } from '../composables/useGetTeacherList'
import { useAppConfig } from '@/composables/useAppConfig'
const appConfig = useAppConfig()

interface Props {
  data?: ContestItem | null
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

dayjs.extend(isBetween)

// 赛项类型
const types = useMapStore().getMapValuesByKey('competition_type')
// 主办单位
const hostUnitList = useMapStore().getMapValuesByKey('host_unit')
// 承办单位
const organizerList = useMapStore().getMapValuesByKey('organizer')
// 技术支持单位
const technicalSupportUnitList = useMapStore().getMapValuesByKey('technical_support_unit')
// 数据状态
const status = useMapStore().getMapValuesByKey('system_status')
// 指导老师
const { teachers } = useGetTeacherList()

const formRef = $ref<FormInstance>()
const form = reactive({
  id: '',
  name: '',
  client_id: 'client_1',
  host_unit_id: '',
  organizer_ids: [],
  technical_support_unit_id: '',
  type: '1',
  teacher_ids: [],
  apply_expiration_date: '',
  status: '1',
  logo: '',
  cover: '',
  train_platform_uri: '',
  competition_uri: '',
  dateRange: undefined,
  date: undefined,
  datetimeRange: undefined,
  datetimeRange2: undefined,
  is_switchable_theory_practice: 0,
  is_customer_anti_cheat: 0,
  practical_competition_tag_name: '',
  practical_environment_tag_name: '',
  practical_answer_tag_name: '',
  practical_report_abel_ame: '',
  train_platform_configs: [
    { name: appConfig.xTrainLabel || '理论', is_show: '1', type: '1', url: '', platform_key: 'x_exam' },
    // {
    //   name: appConfig.labTrainLabel || '商业数据分析实验',
    //   is_show: '0',
    //   type: '2',
    //   url: '',
    //   platform_key: 'career_data_analysis'
    // },
    { name: '实操', is_show: '0', type: '2', url: '', platform_key: 'data_marketing' }
  ],
  competition_platform_configs: [
    {
      name: appConfig.xExamLabel || '理论',
      is_show: '1',
      type: '1',
      url: '',
      exam_id: '',
      platform_key: 'x_exam'
    },
    // {
    //   name: appConfig.labExamLabel || '商业数据分析实验',
    //   is_show: '0',
    //   type: '2',
    //   url: '',
    //   platform_key: 'career_data_analysis'
    // },
    { name: '实操', is_show: '0', type: '2', url: '', platform_key: 'data_marketing' }
  ]
})
watchEffect(() => {
  if (!props.data) return
  const host_unit_id = props.data.host_unit.id
  const organizer_ids = props.data.organizers.map(item => item.id)
  const technical_support_unit_id = props.data.technical_support_unit.id
  const teacher_ids = props.data.teachers.map(item => item.id)
  const dateRange = [new Date(props.data.start_range * 1000), new Date(props.data.end_range * 1000)]
  const date = new Date(props.data.start_at * 1000)
  const datetimeRange = [new Date(props.data.start_at * 1000), new Date(props.data.end_at * 1000)]
  const datetimeRange2 = [
    new Date(props.data.operational_start_time * 1000),
    new Date(props.data.operational_end_time * 1000)
  ]
  const is_switchable_theory_practice = parseInt(props.data.is_switchable_theory_practice)
  const type = props.data?.type + ''
  const status = props.data?.status + ''
  const apply_expiration_date = props.data.apply_expiration_date * 1000

  let is_customer_anti_cheat = 0
  let practical_competition_tag_name = ''
  let practical_environment_tag_name = ''
  let practical_answer_tag_name = ''
  let practical_report_abel_ame = ''
  if (props.data.extended_field) {
    is_customer_anti_cheat = props.data.extended_field?.is_customer_anti_cheat
    practical_competition_tag_name = props.data.extended_field?.practical_competition_tag_name
    practical_environment_tag_name = props.data.extended_field?.practical_environment_tag_name
    practical_answer_tag_name = props.data.extended_field?.practical_answer_tag_name
    practical_report_abel_ame = props.data.extended_field?.practical_report_abel_ame
  }
  Object.assign(form, props.data, {
    host_unit_id,
    organizer_ids,
    technical_support_unit_id,
    teacher_ids,
    dateRange,
    date,
    datetimeRange,
    datetimeRange2,
    apply_expiration_date,
    is_switchable_theory_practice,
    type,
    status,
    is_customer_anti_cheat,
    practical_competition_tag_name,
    practical_environment_tag_name,
    practical_answer_tag_name,
    practical_report_abel_ame
  })
})
const checkApplyExpirationDate = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请选择报名截止日期'))
  } else {
    const [firstDate, secondDate] = form.dateRange || []
    if (
      !dayjs(value).isBetween(firstDate, secondDate, 'date', '[]') ||
      !dayjs(value).isBefore(dayjs(form.date), 'date')
    ) {
      callback(new Error('请选择赛项周期内的日期，且必须早于正式比赛日期'))
    }
    callback()
  }
}

const checkTrainPlatformConfigs = (rule: any, value: any, callback: any) => {
  const findItem = function (a: any, b: any) {
    return form.train_platform_configs.find((item: any) => item[a] === b)
  }
  // 判断最少选择一项目
  if (!findItem('is_show', '1')) {
    callback(new Error('最少选择一项'))
  } else {
    form.train_platform_configs.forEach((item: any) => {
      if (item.is_show === '1') {
        if (item.type === '1') {
          if (item.exam_id === '') {
            callback(new Error(`请选择${item.name}`))
          } else {
            callback()
          }
        } else {
          if (item.url === '') {
            callback(new Error(`请填写${item.name}的链接`))
          } else {
            callback()
          }
        }
      }
    })
  }
}

const checkCompetitionPlatformConfigs = (rule: any, value: any, callback: any) => {
  const findItem = function (a: any, b: any) {
    return form.competition_platform_configs.find((item: any) => item[a] === b)
  }
  // 判断最少选择一项目
  if (!findItem('is_show', '1')) {
    callback(new Error('最少选择一项'))
  } else {
    form.competition_platform_configs.forEach((item: any) => {
      if (item.is_show === '1') {
        if (item.type === '1') {
          if (item.exam_id === '') {
            callback(new Error(`请选择${item.name}`))
          } else {
            callback()
          }
        } else {
          if (item.url === '') {
            callback(new Error(`请填写${item.name}的链接`))
          } else {
            callback()
          }
        }
      }
    })
  }
}
const rules = ref<FormRules>({
  name: [{ required: true, message: '请输入赛项名称' }],
  practical_competition_tag_name: [{ required: true, message: '请输入' }],
  practical_environment_tag_name: [{ required: true, message: '请输入' }],
  practical_answer_tag_name: [{ required: true, message: '请输入' }],
  practical_report_abel_ame: [{ required: true, message: '请输入' }],
  host_unit_id: [{ required: true, message: '请选择主办单位' }],
  organizer_ids: [{ type: 'array', required: true, message: '请选择承办单位' }],
  technical_support_unit_id: [{ required: true, message: '请选择技术支持单位' }],
  type: [{ required: true, message: '请选择赛项类型' }],
  teacher_ids: [{ type: 'array', required: true, message: '请选择指导教师', trigger: 'change' }],
  dateRange: [{ type: 'array', required: true, message: '请选择赛项周期', trigger: 'change' }],
  date: [{ required: true, message: '请选择正式比赛日期', trigger: 'change' }],
  datetimeRange: [{ type: 'array', required: true, message: '正式比赛理论答题时间', trigger: 'change' }],
  datetimeRange2: [{ type: 'array', required: true, message: '正式比赛实操答题时间', trigger: 'change' }],
  apply_expiration_date: [
    { required: true, message: '请选择报名截止日期' },
    {
      validator: checkApplyExpirationDate,
      message: '请选择赛项周期内的日期，且必须早于正式比赛日期'
    }
  ],
  // train_platform_uri: [{ required: true, message: '请输入训练平台地址' }],
  // competition_uri: [{ required: true, message: '请输入正式比赛地址' }],
  status: [{ required: true, message: '请选择有效状态' }],
  is_switchable_theory_practice: [{ required: true, message: '请选择' }],
  is_customer_anti_cheat: [{ required: true, message: '请选择' }],
  logo: [{ required: true, message: '请上传赛项LOGO' }],
  cover: [{ required: true, message: '请上传赛项封面' }],
  train_platform_configs: [{ required: true, message: '' }, { validator: checkTrainPlatformConfigs }],
  competition_platform_configs: [{ required: true, message: '' }, { validator: checkCompetitionPlatformConfigs }]
})
const isUpdate = $computed(() => {
  return !!form.id
})
// 是否禁用赛项周期
// const disabledRange = $computed(() => {
//   const [firstDate, secondDate] = form.dateRange || []
//   return isUpdate && dayjs().isBetween(firstDate, secondDate, 'date', '[]')
// })
// 提交
function handleSubmit() {
  function containsNumber(A: number, B: number): boolean {
    // 将数字A和B转换成字符串，并检查A的字符串是否包含B的字符串
    return A.toString().includes(B.toString())
  }
  formRef?.validate().then(() => {
    const [firstDate, secondDate] = form.dateRange || []
    const [firstDatetime, secondDatetime] = form.datetimeRange || []
    const [firstDatetime2, secondDatetime2] = form.datetimeRange2 || []
    const year = dayjs(form.date).year()
    const month = dayjs(form.date).month()
    const date = dayjs(form.date).date()
    const mergedForm = {
      ...form,
      organizer_ids: JSON.stringify(form.organizer_ids),
      // teacher_ids: form.teacher_ids.join(','),
      start_range: dayjs(firstDate).unix(),
      end_range: dayjs(secondDate).endOf('date').unix(),
      start_at: dayjs(firstDatetime).year(year).month(month).date(date).unix(),
      end_at: dayjs(secondDatetime).year(year).month(month).date(date).unix(),
      operational_start_time: dayjs(firstDatetime2).year(year).month(month).date(date).unix(),
      operational_end_time: dayjs(secondDatetime2).year(year).month(month).date(date).unix(),
      apply_expiration_date: dayjs(form.apply_expiration_date).endOf('date').unix(),
      extended_field: JSON.stringify({
        practical_competition_tag_name: form.practical_competition_tag_name,
        practical_environment_tag_name: form.practical_environment_tag_name,
        practical_answer_tag_name: form.practical_answer_tag_name,
        practical_report_abel_ame: form.practical_report_abel_ame,
        is_customer_anti_cheat: form.is_customer_anti_cheat
      })
    }

    // 判断正式比赛理论答题时间和选择的考试
    const findExam = examList.find(item => item.exam_id === form.competition_platform_configs[0].exam_id)
    const examStartTime = new Date(findExam?.start_time || '').getTime()
    const examEndTime = new Date(findExam?.end_time || '').getTime()
    // console.log(containsNumber(examStartTime, mergedForm.start_at), containsNumber(examEndTime, mergedForm.end_at))
    const findXItem = form.competition_platform_configs.find(item => item.type === '1')
    if (findXItem?.is_show === '1') {
      if (
        containsNumber(examStartTime, mergedForm.start_at) !== true ||
        containsNumber(examEndTime, mergedForm.end_at) !== true
      ) {
        ElMessage({ message: `正式比赛理论答题时间与${findExam?.name}的考试时间不符`, type: 'warning' })
        return false
      }
    }

    const params: ContestUpdateParams = pick(mergedForm, [
      'operational_start_time',
      'operational_end_time',
      'id',
      'name',
      'client_id',
      'host_unit_id',
      'organizer_ids',
      'technical_support_unit_id',
      'type',
      'start_range',
      'end_range',
      'start_at',
      'end_at',
      'apply_expiration_date',
      'status',
      'logo',
      'cover',
      // 'train_platform_uri',
      // 'competition_uri',
      'teacher_ids',
      'train_platform_configs',
      'competition_platform_configs',
      'is_switchable_theory_practice',
      'extended_field'
    ])
    isUpdate ? handleUpdate(params) : handleCreate(params)
  })
}
// 新增
function handleCreate(params: ContestCreateParams) {
  // console.log(params, 'aaa')
  createContest(params).then(() => {
    ElMessage({ message: '创建成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
// 修改
function handleUpdate(params: ContestUpdateParams) {
  updateContest(params).then(() => {
    ElMessage({ message: '修改成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}

// 赛项周期改变
function handleDateRangeChange(value: any) {
  if (value) {
    const [, secondDate] = form.dateRange || []
    form.date = secondDate
  }
}

const clientList = [
  // { label: '商务数据分析师赛项', value: 'business_data_analyst' },
  // { label: '全媒体运营师赛项', value: 'all_media_operator' },
  // { label: '网络主播赛项', value: 'network_anchor_competition' }
  { label: '客户端1', value: 'client_1' },
  { label: '客户端2', value: 'client_2' },
  { label: '客户端3', value: 'client_3' },
  { label: '客户端4', value: 'client_4' },
  { label: '客户端5', value: 'client_5' }
]

let examList = $ref<Record<string, any>[]>([])
// 获取关联考试列表
function fetchExamList() {
  getExamList({ project: 'x1', 'per-page': 1000 }).then(res => {
    examList = res.data.list || []
  })
}
onMounted(() => {
  fetchExamList()
})
</script>

<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="165px">
    <div style="display: flex">
      <div style="flex: 1; margin-right: 10px">
        <el-form-item label="赛项名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="承办单位" prop="organizer_ids">
          <el-select v-model="form.organizer_ids" multiple style="width: 100%">
            <el-option v-for="item in organizerList" :key="item.id" :label="item.label" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="赛项类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio v-for="item in types" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="赛项周期" prop="dateRange">
          <el-date-picker
            type="daterange"
            range-separator="至"
            v-model="form.dateRange"
            style="width: 100%"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item label="正式比赛日期" prop="date">
          <el-date-picker type="date" v-model="form.date" style="width: 100%" />
        </el-form-item>
        <el-form-item label="正式比赛理论答题时间" prop="datetimeRange">
          <el-time-picker
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            v-model="form.datetimeRange"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="训练平台地址" prop="train_platform_configs">
          <el-checkbox
            true-label="1"
            false-label="0"
            style="margin-bottom: 10px"
            v-model="item.is_show"
            v-for="item in form.train_platform_configs"
            :key="item.platform_key"
          >
            <div style="display: flex; align-items: center">
              <!-- <span style="margin-right: 10px; width: 180px">{{ item.name }}</span> -->
              <el-input v-model="item.name" style="margin-right: 10px; max-width: 130px" />
              <el-input v-model="item.url" style="width: 200px" />
            </div>
          </el-checkbox>
        </el-form-item>
        <el-form-item label="指导教师" prop="teacher_ids">
          <el-select v-model="form.teacher_ids" multiple style="width: 100%">
            <el-option v-for="item in teachers" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实操赛题标签名称" prop="practical_competition_tag_name">
          <el-input placeholder="请输入" v-model="form.practical_competition_tag_name" />
        </el-form-item>
        <el-form-item label="实操环境标签名称" prop="practical_environment_tag_name">
          <el-input placeholder="请输入" v-model="form.practical_environment_tag_name" />
        </el-form-item>
        <el-form-item label="实操答题标签名称" prop="practical_answer_tag_name">
          <el-input placeholder="请输入" v-model="form.practical_answer_tag_name" />
        </el-form-item>
        <el-form-item label="实操报告标签名称" prop="practical_report_abel_ame">
          <el-input placeholder="请输入" v-model="form.practical_report_abel_ame" />
        </el-form-item>
        <el-form-item label="有效状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="item in status" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <div style="flex: 1; margin-left: 10px">
        <el-form-item label="主办单位" prop="host_unit_id">
          <el-select v-model="form.host_unit_id" style="width: 100%">
            <el-option v-for="item in hostUnitList" :key="item.id" :label="item.label" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="技术支持单位" prop="technical_support_unit_id">
          <el-select v-model="form.technical_support_unit_id" style="width: 100%">
            <el-option
              v-for="item in technicalSupportUnitList"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="客户端" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio v-for="item in types" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="客户端标识" prop="client_id">
          <!-- <el-select v-model="form.client_id" style="width: 100%" clearable>
            <el-option v-for="item in clientList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select> -->
          <el-radio-group v-model="form.client_id">
            <el-radio v-for="item in clientList" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="报名截止日期" prop="apply_expiration_date">
          <el-date-picker type="date" v-model="form.apply_expiration_date" style="width: 100%" />
        </el-form-item>
        <el-form-item label="正式比赛实操答题时间" prop="datetimeRange2">
          <el-time-picker
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            v-model="form.datetimeRange2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="正式比赛地址" prop="competition_platform_configs">
          <el-checkbox
            true-label="1"
            false-label="0"
            style="margin-bottom: 10px"
            v-model="item.is_show"
            v-for="item in form.competition_platform_configs"
            :key="item.platform_key"
          >
            <div style="display: flex; align-items: center">
              <!-- <span style="margin-right: 10px; width: 180px">{{ item.name }}</span> -->
              <el-input v-model="item.name" style="margin-right: 10px; max-width: 130px" />
              <el-input v-model="item.url" v-if="item.type === '2'" style="width: 200px" />
              <el-select v-model="item.exam_id" filterable style="width: 200px" v-if="item.type === '1'">
                <el-option
                  v-for="item in examList"
                  :key="item.exam_id"
                  :label="item.name"
                  :value="item.exam_id"
                ></el-option>
              </el-select>
            </div>
          </el-checkbox>
        </el-form-item>
        <el-form-item label="客户端切换理论与实操" prop="is_switchable_theory_practice">
          <el-radio-group v-model="form.is_switchable_theory_practice">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="客户端防作弊" prop="is_customer_anti_cheat">
          <el-radio-group v-model="form.is_customer_anti_cheat">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="赛项LOGO" prop="logo">
          <AppUpload v-model="form.logo" accept="image/*"></AppUpload>
        </el-form-item>
        <el-form-item label="赛项封面" prop="cover">
          <AppUpload v-model="form.cover" accept="image/*"></AppUpload>
        </el-form-item>
      </div>
    </div>

    <el-row justify="center">
      <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
      <el-button round auto-insert-space @click="$emit('update:modelValue', false)">取消</el-button>
    </el-row>
  </el-form>
</template>
