<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 } from '../api'
import { useMapStore } from '@/stores/map'
import { useGetTeacherList } from '../composables/useGetTeacherList'

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: '',
  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,
  train_platform_configs: [
    { name: '1+X理论考试', is_show: '1', type: '1', url: '', platform_key: 'x_exam' },
    { name: '商业数据分析实验', 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: '1+X理论考试', is_show: '1', type: '1', url: '', platform_key: 'x_exam' },
    { name: '商业数据分析实验', 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 apply_expiration_date = props.data.apply_expiration_date * 1000
  Object.assign(form, props.data, {
    host_unit_id,
    organizer_ids,
    technical_support_unit_id,
    teacher_ids,
    dateRange,
    date,
    datetimeRange,
    apply_expiration_date
  })
})
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.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.url === '') {
          callback(new Error(`请填写${item.name}的链接`))
        } else {
          callback()
        }
      }
    })
  }
}
const rules = ref<FormRules>({
  name: [{ 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' }],
  apply_expiration_date: [
    { required: true, message: '请选择报名截止日期' },
    {
      validator: checkApplyExpirationDate,
      message: '请选择赛项周期内的日期，且必须早于正式比赛日期'
    }
  ],
  // train_platform_uri: [{ required: true, message: '请输入训练平台地址' }],
  // competition_uri: [{ required: true, message: '请输入正式比赛地址' }],
  status: [{ 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 title = $computed(() => {
  return isUpdate ? '编辑赛项' : '新增赛项'
})
// 是否禁用赛项周期
const disabledRange = $computed(() => {
  const [firstDate, secondDate] = form.dateRange || []
  return isUpdate && dayjs().isBetween(firstDate, secondDate, 'date', '[]')
})
// 提交
function handleSubmit() {
  formRef?.validate().then(() => {
    const [firstDate, secondDate] = form.dateRange || []
    const [firstDatetime, secondDatetime] = form.datetimeRange || []
    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(),
      apply_expiration_date: dayjs(form.apply_expiration_date).endOf('date').unix()
    }
    const params: ContestUpdateParams = pick(mergedForm, [
      'id',
      'name',
      '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'
    ])
    console.log(isUpdate, 'isUpdate')
    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
  }
}
</script>

<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    align-center
    width="600px"
    @update:modelValue="$emit('update:modelValue')"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
      <el-form-item label="赛项名称" prop="name">
        <el-input v-model="form.name" :disabled="isUpdate" />
      </el-form-item>
      <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="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="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="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="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="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="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.url" />
          </div>
        </el-checkbox>
      </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.url" />
          </div>
        </el-checkbox>
      </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>
      <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>
      <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>
  </el-dialog>
</template>
