<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" >
<!--            <el-form-item label="任务主键" prop="taskId">-->
<!--              <el-input v-model="queryParams.taskId" placeholder="请输入任务主键" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
            <el-form-item label="任务编码" prop="taskCode">
              <el-input v-model="queryParams.taskCode" placeholder="请输入任务编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="任务类型" prop="wmsCheckTaskType">
              <el-select v-model="queryParams.wmsCheckTaskType" placeholder="请选择任务类型" clearable >
                <el-option v-for="dict in wms_check_task_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
<!--            <el-form-item label="物料类型" prop="materialTypeId">-->
<!--              <el-input v-model="queryParams.materialTypeId" placeholder="请输入物料类型" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="抽检率" prop="checkRate">-->
<!--              <el-input v-model="queryParams.checkRate" placeholder="请输入抽检率" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="定时任务" prop="cron">-->
<!--              <el-input v-model="queryParams.cron" placeholder="请输入定时任务" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="仓库主键" prop="warehouseId">-->
<!--              <el-input v-model="queryParams.warehouseId" placeholder="请输入仓库主键" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
            <el-form-item label="频率选项" prop="wmsCheckTaskFrequency">
              <el-select v-model="queryParams.wmsCheckTaskFrequency" placeholder="请选择定时任务频率选项" clearable >
                <el-option v-for="dict in wms_check_task_frequency" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:wmsCheckTask:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['wms:wmsCheckTask:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['wms:wmsCheckTask:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:wmsCheckTask:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="wmsCheckTaskList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="任务主键" align="center" prop="taskId" v-if="columns[0].visible"/> -->
        <el-table-column label="任务编码" align="center" prop="taskCode" v-if="columns[0].visible"/>
        <el-table-column label="任务名称" align="center" prop="taskName" v-if="columns[1].visible"/>
        <el-table-column label="任务类型" align="center" prop="wmsCheckTaskType" v-if="columns[2].visible">
          <template #default="scope">
            <dict-tag :options="wms_check_task_type" :value="scope.row.wmsCheckTaskType"/>
          </template>
        </el-table-column>
        <el-table-column label="定时任务" align="center" prop="cron" v-if="columns[3].visible"/>
        <el-table-column label="频率选项" align="center" prop="wmsCheckTaskFrequency" v-if="columns[5].visible">
          <template #default="scope">
            <dict-tag :options="wms_check_task_frequency" :value="scope.row.wmsCheckTaskFrequency"/>
          </template>
        </el-table-column>
        <el-table-column label="仓库名称" align="center" prop="warehouseName" v-if="columns[4].visible"/>
        <el-table-column label="物料类型" align="center" prop="matrialTypeName" v-if="columns[6].visible"/>
        <el-table-column label="抽检率" align="center" prop="checkRate" v-if="columns[7].visible"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wms:wmsCheckTask:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wms:wmsCheckTask:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改仓储盘点任务对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="wmsCheckTaskFormRef" :model="form" :rules="rules" label-width="120px">
<!--        <el-form-item label="任务主键" prop="taskId">-->
<!--          <el-input v-model="form.taskId" placeholder="请输入任务主键" />-->
<!--        </el-form-item>-->
        <el-form-item label="任务编码" prop="taskCode">
          <el-input v-model="form.taskCode" placeholder="请输入任务编码" />
        </el-form-item>
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务类型" prop="wmsCheckTaskType">
          <el-select v-model="form.wmsCheckTaskType" placeholder="请选择任务类型" :disabled="!!form.taskId">
            <el-option
                v-for="dict in wms_check_task_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="频率选项" prop="wmsCheckTaskFrequency">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card :class="{'selected': form.wmsCheckTaskFrequency === '0'}" @click="form.wmsCheckTaskFrequency = '0'">
                月度计划
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card :class="{'selected': form.wmsCheckTaskFrequency === '1'}" @click="form.wmsCheckTaskFrequency = '1'">
                年度计划
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card :class="{'selected': form.wmsCheckTaskFrequency === '2'}" @click="form.wmsCheckTaskFrequency = '2'">
                自定义计划
              </el-card>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item v-if="form.wmsCheckTaskFrequency === '0'" label="执行日期">
          <el-select v-model="form.executeDay" title="推荐使用'L'以适应月份变异，如闰年">
            <el-option v-for="day in 27" :key="day" :value="day.toString()">{{day}}日</el-option>
            <el-option value="L">最后一天</el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.wmsCheckTaskFrequency === '0'" label="间隔月数">
          <el-input-number v-model="form.intervalMonths" :min="0" :step="1" />
        </el-form-item>

        <el-form-item v-if="form.wmsCheckTaskFrequency === '1'" label="执行月份">
          <el-select v-model="form.executeMonth">
            <el-option v-for="m in 12" :key="m" :value="m">{{m}}月</el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.wmsCheckTaskFrequency === '1'" label="执行日期">
          <el-select v-model="form.executeDay">
            <el-option v-for="day in getMaxDay(form.executeMonth)" :key="day" :value="day.toString()">{{day}}日</el-option>
            <el-option value="L" v-if="showLastDay(form.executeMonth)">最后一天</el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.wmsCheckTaskFrequency === '2'" label="定时计划" prop="cron">
          <el-input
            v-model="form.cron"
            readonly
            placeholder="只能点击右侧生成器">
            <template #append>
              <el-button type="primary" @click="handleShowCron">
                点击生成计划表达式
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-dialog title="Cron表达式生成器" v-model="dialogCron.visible" append-to-body destroy-on-close class="scrollbar">
          <Crontab @hide="dialogCron.visible = false" @fill="crontabFill" :expression="expression"></Crontab>
        </el-dialog>
        <el-form-item label="抽检物料类型" prop="materialTypeId" v-if="form.wmsCheckTaskType == 0">
          <el-select v-model="form.materialTypeId" placeholder="请选择抽检物料类型">
            <el-option
              v-for="item in materialTypeList"
              :key="item.matrialTypeId"
              :label="item.matrialTypeName"
              :value="item.matrialTypeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="抽检率（%）" prop="checkRate" v-if="form.wmsCheckTaskType == 0">
          <el-input-number v-model="form.checkRate" :precision="2" :step="0.01" :min="0" :max="100" placeholder="请输入抽检率" />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
<!--          <el-input v-model="form.warehouseId" placeholder="请输入仓库主键" />-->
          <el-select v-model="form.warehouseId" placeholder="请选择仓库">
            <el-option
              v-for="item in warehouseList"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预览Cron">
          <code>{{ previewCron }}</code>
        </el-form-item>
<!--        <el-form-item label="下次执行时间">-->
<!--          <CrontabResult :ex="previewCron" />-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="WmsCheckTask" lang="ts">
import { listWmsCheckTask, getWmsCheckTask, delWmsCheckTask, addWmsCheckTask, updateWmsCheckTask } from '@/api/wms/wmsCheckTask';
import { WmsCheckTaskVO, WmsCheckTaskQuery, WmsCheckTaskForm } from '@/api/wms/wmsCheckTask/types';
import { getBaseWarehouseList } from '@/api/wms/baseWarehouse';

import Crontab from '@/components/Crontab/index.vue';
import CrontabResult from '@/components/Crontab/result.vue';
import { getBaseMaterialTypeList } from '@/api/wms/baseMaterialType';


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wms_check_task_type, wms_check_task_frequency } = toRefs<any>(proxy?.useDict('wms_check_task_type', 'wms_check_task_frequency'));

const wmsCheckTaskList = ref<WmsCheckTaskVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const wmsCheckTaskFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐信息
const columns = ref<FieldOption[]>([
        // { key: 0, label: `任务主键`, visible: true },
        // { key: 1, label: `租户号`, visible: true },
        { key: 0, label: `任务编码`, visible: true },
        { key: 1, label: `任务名称`, visible: true },
        { key: 2, label: `任务类型`, visible: true },

        { key: 3, label: `定时任务`, visible: true },
        { key: 4, label: `仓库`, visible: true },
        // { key: 7, label: `创建人`, visible: true },
        // { key: 8, label: `创建部门`, visible: true },
        // { key: 9, label: `创建时间`, visible: true },
        // { key: 10, label: `修改人`, visible: true },
        // { key: 11, label: `修改时间`, visible: true },
        { key: 5, label: `频率选项`, visible: true },
        { key: 6, label: `物料类型`, visible: true },
        { key: 7, label: `抽检率`, visible: false },
]);

const initFormData: WmsCheckTaskForm = {
  taskId: undefined,
  taskCode: undefined,
  taskName: undefined,
  wmsCheckTaskType: undefined,
  materialTypeId: undefined,
  checkRate: undefined,
  cron: undefined,
  warehouseId: undefined,
  wmsCheckTaskFrequency: undefined,
  matrialTypeName: undefined,
  warehouseName: undefined,
}
const data = reactive<PageData<WmsCheckTaskForm, WmsCheckTaskQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskId: undefined,
    taskCode: undefined,
    taskName: undefined,
    wmsCheckTaskType: undefined,
    materialTypeId: undefined,
    checkRate: undefined,
    cron: undefined,
    warehouseId: undefined,
    wmsCheckTaskFrequency: undefined,
    matrialTypeName: undefined,
    warehouseName: undefined,
    params: {
    }
  },
  rules: {
    taskCode: [
      { required: true, message: "任务编码不能为空", trigger: "blur" }
    ],
    taskName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    wmsCheckTaskType: [
      { required: true, message: "任务类型不能为空", trigger: "change" }
    ],
    wmsCheckTaskFrequency: [
      { required: true, message: "频率选项不能为空", trigger: "change" }
    ],
    executeDay: [{ required: true, message: '执行日期不能为空', trigger: 'change' }],
    intervalMonths: [
      { required: true, message: '间隔月数不能为空', trigger: 'blur' },
      { type: 'integer', min: 0, message: '间隔月数必须为非负整数 (0表示每月)', trigger: 'blur' }
    ],
    executeMonth: [{ required: true, message: '执行月份不能为空', trigger: 'change' }],
    cron: [{ required: true, message: '定时任务不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询仓储盘点任务列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listWmsCheckTask(queryParams.value);
    wmsCheckTaskList.value = res.rows;
    total.value = res.total;
  } catch (e: any) {
    proxy?.$modal.msgError('获取列表失败: ' + e.message);
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  console.log('cancel called');
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  wmsCheckTaskFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: WmsCheckTaskVO[]) => {
  ids.value = selection.map(item => item.taskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加仓储盘点任务";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: WmsCheckTaskVO) => {
  reset();
  const _taskId = row?.taskId || ids.value[0]
  try {
    const res = await getWmsCheckTask(_taskId);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改仓储盘点任务";

    // Add parse function
    const parseCron = (cron: string) => {
      // Simple parsing logic, assume cron format '0 0 0 day month ? *' or similar
      const parts = cron.split(' ');
      if (parts.length < 6) return { frequency: '2', cron }; // fallback to custom

      const day = parts[3];
      const month = parts[4];
      const year = parts[6];

      if (month.startsWith('*/')) {
        // Monthly
        const interval = parseInt(month.slice(2));
        return { frequency: '0', executeDay: day, intervalMonths: interval, cron };
      } else if (year === '*' && month !== '*' && month !== '*/' ) {
        // Yearly
        return { frequency: '1', executeDay: day, executeMonth: parseInt(month), cron };
      } else {
        return { frequency: '2', cron };
      }
    };

    // In handleUpdate after res
    const parsed = parseCron(res.data.cron);
    form.value.wmsCheckTaskFrequency = parsed.frequency;
    if (parsed.frequency === '0') {
      form.value.executeDay = parsed.executeDay;
      form.value.intervalMonths = parsed.intervalMonths;
    } else if (parsed.frequency === '1') {
      form.value.executeDay = parsed.executeDay;
      form.value.executeMonth = parsed.executeMonth;
    }
    form.value.cron = parsed.cron;
  } catch (e: any) {
    proxy?.$modal.msgError('获取详情失败: ' + e.message);
  }
}

/** 提交按钮 */
const submitForm = () => {
  wmsCheckTaskFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (form.value.taskId) {
          console.log(form.value);
          await updateWmsCheckTask(form.value);
        } else {
          console.log(form.value);
          await addWmsCheckTask(form.value);
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        await getList();
      } catch (e: any) {
        proxy?.$modal.msgError('操作失败: ' + e.message);
      } finally {
        buttonLoading.value = false;
      }
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: WmsCheckTaskVO) => {
  const _taskIds = row?.taskId || ids.value;
  await proxy?.$modal.confirm('是否确认删除仓储盘点任务编号为"' + _taskIds + '"的数据项？').finally(() => loading.value = false);
  try {
    await delWmsCheckTask(_taskIds);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  } catch (e: any) {
    proxy?.$modal.msgError('删除失败: ' + e.message);
  }
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('wms/wmsCheckTask/export', {
    ...queryParams.value
  }, `wmsCheckTask_${new Date().getTime()}.xlsx`)
}



const previewDescription = ref('');
const previewCron = ref('');

watch(() => form.value, (newForm) => {
  // Generate cron and description based on frequency
  let cron = '';
  let desc = '';
  if (newForm.wmsCheckTaskFrequency === '0') {
    cron = `0 0 0 ${newForm.executeDay || '?'} */${newForm.intervalMonths || 1} ?`;
    desc = `每${newForm.intervalMonths || 1}个月的${newForm.executeDay === 'L' ? '最后一天' : newForm.executeDay + '日'} 00:00 执行`;
  } else if (newForm.wmsCheckTaskFrequency === '1') {
    cron = `0 0 0 ${newForm.executeDay || '?'} ${newForm.executeMonth || '?'} ? *`;
    desc = `每年${newForm.executeMonth}月的${newForm.executeDay === 'L' ? '最后一天' : newForm.executeDay + '日'} 00:00 执行`;
  } else if (newForm.wmsCheckTaskFrequency === '2') {
    cron = newForm.cron || '';
    desc = '自定义计划: ' + cron;
  }
  previewCron.value = cron;
  previewDescription.value = desc;
  // For non-custom, set form.cron
  if (newForm.wmsCheckTaskFrequency !== '2') {
    newForm.cron = cron;
  }
  cron = cron + ' *'; // 添加 year *

}, { deep: true });

//获取仓库列表
let warehouseList = ref([]);
const getWarehouseList = async () => {
  const res = await getBaseWarehouseList(null);
  warehouseList.value = res.data;
}

//获取物料类型列表
let materialTypeList = ref([]);
const getMaterialTypeList = async () => {
  const res = await getBaseMaterialTypeList(null);
  materialTypeList.value = res.data;
}

const dialogCron = reactive({ visible: false });
const expression = ref('');

const handleShowCron = () => {
  expression.value = form.value.cron || '';
  dialogCron.visible = true;
};

const crontabFill = (value: string) => {
  form.value.cron = value;
  dialogCron.visible = false;
};

const monthMaxDays = [0,31,27,31,30,31,30,31,31,30,31,30,31]; // Feb 27

const getMaxDay = (month: number) => {
  if (!month) return 27; // default 27
  return monthMaxDays[month] || 27; // default 27
};

const showLastDay = (month: number) => {
  return getMaxDay(month) < 30; // Hide if max >=30
};

watch(() => form.value.executeMonth, (newMonth) => {
  if (form.value.wmsCheckTaskFrequency === '1' && form.value.executeDay && form.value.executeDay !== 'L') {
    const dayNum = parseInt(form.value.executeDay);
    if (dayNum > getMaxDay(newMonth)) {
      form.value.executeDay = null;
    }
  }
});

watch(() => form.value.wmsCheckTaskType, (newType) => {
  if (newType !== '0') {
    form.value.checkRate = undefined;
  }
});

onMounted(() => {
  getList();
  getWarehouseList();
  getMaterialTypeList();
});
</script>

<style scoped>
.selected {
  border-color: #409EFF;
  background-color: #E6F7FF;
}
</style>
