<template>
  <view class="container">
    <u-navbar
      leftIconSize="40rpx"
      leftIconColor="#333333"
      :title="title"
    >
    </u-navbar>
    <view class="section">
      <view class="section-title">{{ title }}</view>
      <view class="form-view">
        <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" label-width="180rpx"
          :labelStyle="{ color: '#333333', fontSize: '30rpx', marginRight: '24rpx' }">
          <u-form-item label="任务名称" prop="jobName" required>
            <u--input v-model="form.jobName" placeholder="请输入任务名称"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>

          <u-form-item label="任务组名" prop="jobGroup" required>
            <u--input v-model="form.jobGroup" placeholder="请输入任务组名"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>

          <u-form-item label="调用目标" prop="invokeTarget" required>
            <u--input v-model="form.invokeTarget" placeholder="请输入调用目标字符串"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>

          <u-form-item label="cron表达式" prop="cronExpression" required>
            <u--input v-model="form.cronExpression" placeholder="请输入cron执行表达式"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>

          <u-form-item label="状态" prop="statusName" @click="showStatusPicker = true">
            <view class="input-with-arrow">
              <u--input v-model="statusName" readonly disabledColor="#ffffff" placeholder="请选择状态"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>

          <u-form-item label="是否并发" prop="concurrentName" @click="showConcurrentPicker = true">
            <view class="input-with-arrow">
              <u--input v-model="concurrentName" readonly disabledColor="#ffffff" placeholder="请选择是否并发"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>

          <u-form-item label="错失策略" prop="misfirePolicyName" @click="showMisfirePolicyPicker = true">
            <view class="input-with-arrow">
              <u--input v-model="misfirePolicyName" readonly disabledColor="#ffffff" placeholder="请选择错失执行策略"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>

          <u-form-item label="备注" prop="remark" labelPosition="top">
            <u--textarea v-model="form.remark" placeholder="请输入备注" autoHeight inputAlign="left" count
              maxlength="500" style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
        </u--form>
        <view class="form-btn">
          <u-button type="primary" text="提交" @click="submit"></u-button>
        </view>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
    <u-picker itemHeight="88" :show="showStatusPicker" :columns="statusColumns" keyName="dictLabel" @cancel="showStatusPicker = false"
      @confirm="handleStatusConfirm"></u-picker>
    <u-picker itemHeight="88" :show="showConcurrentPicker" :columns="concurrentColumns" keyName="dictLabel" @cancel="showConcurrentPicker = false"
      @confirm="handleConcurrentConfirm"></u-picker>
    <u-picker itemHeight="88" :show="showMisfirePolicyPicker" :columns="misfirePolicyColumns" keyName="dictLabel" @cancel="showMisfirePolicyPicker = false"
      @confirm="handleMisfirePolicyConfirm"></u-picker>
  </view>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue'
import { getJob, addJob, updateJob } from '@/api/monitor/job'
import { getDicts } from "@/api/system/dict/data"
import { onLoad } from "@dcloudio/uni-app"

const { proxy } = getCurrentInstance()
const title = ref('新增定时任务')
const jobId = ref(undefined)
const showStatusPicker = ref(false)
const showConcurrentPicker = ref(false)
const showMisfirePolicyPicker = ref(false)
const statusName = ref('')
const concurrentName = ref('')
const misfirePolicyName = ref('')
const inputBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}
const statusColumns = ref([])
const concurrentColumns = ref([])
const misfirePolicyColumns = ref([])

const form = reactive({
  jobId: undefined,
  jobName: '',
  jobGroup: '',
  invokeTarget: '',
  cronExpression: '',
  misfirePolicy: '1',
  concurrent: '1',
  status: '0',
  remark: ''
})

const rules = {
  jobName: [
    { required: true, message: '任务名称不能为空', trigger: ['blur', 'change'] }
  ],
  jobGroup: [
    { required: true, message: '任务组名不能为空', trigger: ['blur', 'change'] }
  ],
  invokeTarget: [
    { required: true, message: '调用目标不能为空', trigger: ['blur', 'change'] }
  ],
  cronExpression: [
    { required: true, message: 'cron表达式不能为空', trigger: ['blur', 'change'] }
  ]
}

onLoad((options) => {
  // 获取字典数据
  getDicts('sys_job_status').then(res => {
    statusColumns.value = [res.data]
    updateStatusName()
  })
  getDicts('sys_job_concurrent').then(res => {
    concurrentColumns.value = [res.data]
    updateConcurrentName()
  })
  getDicts('sys_job_policy').then(res => {
    misfirePolicyColumns.value = [res.data]
    updateMisfirePolicyName()
  })

  if (options.id) {
    jobId.value = options.id
    title.value = '修改定时任务'
    getJob(jobId.value).then(response => {
      Object.assign(form, response.data)
      updateStatusName()
      updateConcurrentName()
      updateMisfirePolicyName()
    })
  }
})

// 更新状态名称显示
function updateStatusName() {
  if (statusColumns.value.length > 0 && statusColumns.value[0].length > 0) {
    const item = statusColumns.value[0].find(v => v.dictValue === form.status)
    statusName.value = item ? item.dictLabel : ''
  }
}

// 更新并发名称显示
function updateConcurrentName() {
  if (concurrentColumns.value.length > 0 && concurrentColumns.value[0].length > 0) {
    const item = concurrentColumns.value[0].find(v => v.dictValue === form.concurrent)
    concurrentName.value = item ? item.dictLabel : ''
  }
}

// 更新错失策略名称显示
function updateMisfirePolicyName() {
  if (misfirePolicyColumns.value.length > 0 && misfirePolicyColumns.value[0].length > 0) {
    const item = misfirePolicyColumns.value[0].find(v => v.dictValue === form.misfirePolicy)
    misfirePolicyName.value = item ? item.dictLabel : ''
  }
}

// 状态选择确认
function handleStatusConfirm(e) {
  form.status = e.value[0].dictValue
  statusName.value = e.value[0].dictLabel
  showStatusPicker.value = false
}

// 并发选择确认
function handleConcurrentConfirm(e) {
  form.concurrent = e.value[0].dictValue
  concurrentName.value = e.value[0].dictLabel
  showConcurrentPicker.value = false
}

// 错失策略选择确认
function handleMisfirePolicyConfirm(e) {
  form.misfirePolicy = e.value[0].dictValue
  misfirePolicyName.value = e.value[0].dictLabel
  showMisfirePolicyPicker.value = false
}

// 提交
function submit() {
  proxy.$refs['uForm'].validate().then(() => {
    const submitForm = { ...form }
    if (jobId.value) {
      updateJob(submitForm).then(() => {
        proxy.$refs['uToast'].show({
          message: '修改成功', complete() {
            uni.navigateBack()
          }
        })
      })
    } else {
      addJob(submitForm).then(() => {
        proxy.$refs['uToast'].show({
          message: '新增成功', complete() {
            uni.navigateBack()
          }
        })
      })
    }
  }).catch(() => {
    proxy.$refs['uToast'].show({
      type: 'error',
      message: '请填写完整信息'
    })
  })
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
}

.section {
  margin: 24rpx;
  padding: 0;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;

  .section-title {
    padding: 16rpx 24rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #ffffff;
    line-height: 1.2;
    font-size: 28rpx;
    font-weight: 600;
    display: flex;
    align-items: center;
    
    &::before {
      content: '';
      width: 6rpx;
      height: 28rpx;
      background: #ffffff;
      border-radius: 3rpx;
      margin-right: 12rpx;
    }
  }

  .form-view {
    padding: 24rpx;

    .input-with-arrow {
      position: relative;
      width: 100%;

      .arrow-icon {
        position: absolute;
        right: 20rpx;
        top: 50%;
        transform: translateY(-50%);
        color: #c0c4cc;
        font-size: 20rpx;
        pointer-events: none;
        z-index: 10;
      }
    }

    .form-btn {
      padding-top: 16rpx;
    }
  }
}
</style>

<style lang="scss">
.form-btn .u-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  border: none !important;
  border-radius: 24rpx !important;
  height: 80rpx !important;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4) !important;
}

.form-btn .u-button__text {
  font-size: 30rpx !important;
  font-weight: 500 !important;
  letter-spacing: 2rpx !important;
}
</style>