<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="组成编码" prop="partCode">
        <el-input
          v-model="queryParams.partCode"
          placeholder="请输入组成编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="组成名称" prop="partName">
        <el-input
          v-model="queryParams.partName"
          placeholder="请输入组成名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['system:autocode:part:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:autocode:part:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:autocode:part:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Close"
          size="small"
          @click="handleClose"
        >关闭</el-button>
      </el-col>
      <el-col :span="1.5">
        <span style="color: red; font-size: 18px;display: inline-block;text-align: right;">示例： {{ showExample }}</span>
      </el-col>
      <right-toolbar :show-search="showSearch" @update:showSearch="val => showSearch = val" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="partList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="组成编码" align="center" prop="partCode" />
      <el-table-column label="组成名称" align="center" prop="partName"/>
      <el-table-column label="分段序号" align="center" prop="partIndex" />
      <el-table-column label="分段类型" align="center" prop="partType" >
        <template #default="scope">
          <dict-tag :options="sys_autocode_parttype" :value="scope.row.partType"/>
        </template>
      </el-table-column>
      <el-table-column label="分段长度" align="center" prop="partLength" />
      <el-table-column label="固定字符" align="center" prop="fixCharacter"/>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:autocode:part:edit']"
          >修改</el-button>
          <el-button
            size="small"
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:autocode:part:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="分段编码" prop="partCode">
              <el-input v-model="form.partCode" placeholder="请输入分段编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分段名称" prop="partName">
              <el-input v-model="form.partName" placeholder="请输入分段名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分段序号" prop="partIndex">
              <el-input-number v-model="form.partIndex" placeholder="请输入分段序号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分段长度" prop="partLength">
              <el-input-number v-model="form.partLength" placeholder="请输入分段长度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="业务类型" prop="bizType">
              <el-select v-model="form.bizType" @change="getDictItems" placeholder="请选择">
                <el-option
                  v-for="item in sys_biz_code"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务项" prop="bizItem">
              <el-select v-model="form.bizItem" placeholder="请选择" clearable>
                <el-option
                  v-for="item in bizItems"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分段类型" prop="partType">
              <el-select v-model="form.partType" placeholder="请选择" clearable>
                <el-option
                  v-for="item in sys_autocode_parttype"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日期时间格式" prop="dateFormat" v-if="form.partType=='NOWDATE'">
              <el-input v-model="form.dateFormat" placeholder="请输入日期时间格式" />
            </el-form-item>

            <el-form-item label="输入字符" prop="inputCharacter" v-if="form.partType=='INPUTCHAR'">
              <el-input v-model="form.inputCharacter" placeholder="请填写输入字符" />
            </el-form-item>

            <el-form-item label="固定字符" prop="fixCharacter" v-if="form.partType=='FIXCHAR'">
              <el-input v-model="form.fixCharacter" placeholder="请填写固定字符" />
            </el-form-item>

            <el-form-item label="起始流水号" prop="seriaStartNo" v-if="form.partType=='SERIALNO'">
              <el-input-number v-model="form.seriaStartNo" placeholder="请填写起始流水号" />
            </el-form-item>

            <el-form-item label="值类型" prop="bizValue" v-if="form.partType=='DEFINE'">
              <el-select v-model="form.bizValue" placeholder="请选择" clearable>
                <el-option
                  v-for="item in biz_autocode_value"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="流水号步长" prop="seriaStep" v-if="form.partType=='SERIALNO'">
              <el-input-number v-model="form.seriaStep" placeholder="请填写流水号步长" />
            </el-form-item>
          </el-col>
          <el-col :span= "12">
            <el-form-item label="是否循环" prop="cycleFlag" v-if="form.partType=='SERIALNO'">
              <el-radio-group v-model="form.cycleFlag">
                    <el-radio label="Y">是</el-radio>
                    <el-radio label="N">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span= "12">
            <el-form-item label="循环方式" prop="cycleMethod" v-if="form.partType =='SERIALNO' && form.cycleFlag =='Y'">
              <el-select v-model="form.cycleMethod" placeholder="请选择" clearable>
                <el-option
                  v-for="item in sys_autocode_cyclemethod"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="autoPart">
import { getCurrentInstance, ref, onMounted, nextTick, toRefs } from 'vue'
import { useRoute } from 'vue-router'
import { listPart, getPart, delPart, addPart, updatePart } from "@/api/system/autocode/part";
import { showRule } from "@/api/system/autocode/rule";
import { getDicts } from "@/api/system/dict/data";

const { proxy } = getCurrentInstance();
const { sys_autocode_cyclemethod, sys_autocode_parttype, sys_biz_code, biz_autocode_value } = proxy.useDict('sys_autocode_cyclemethod','sys_autocode_parttype','sys_biz_code', 'biz_autocode_value');

const route = useRoute();

// 定义响应式数据
const partList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const open = ref(false);
const showExample = ref('');
const recentRuleId = ref(undefined);
const bizItems = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    ruleId: undefined,
    partCode: undefined,
    partName: undefined
  },
  rules: {
    partCode: [
      { required: true, message: "组成编码不能为空", trigger: "change" }
    ],
    partName: [
      { required: true, message: "组成名称不能为空", trigger: "blur" }
    ],
    partIndex: [
      { required: true, message: "组成序号不能为空", trigger: "blur" }
    ]
  }
});

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

// 查询表格数据
function getList() {
  loading.value = true;
  listPart(queryParams.value).then(response => {
    partList.value = response.rows;
    showExampleFunc();
    total.value = response.total;
    loading.value = false;
  });
}

// 显示示例
function showExampleFunc() {
  showRule(recentRuleId.value).then(response => {
    showExample.value = response.msg;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    partCode: undefined,
    partName: undefined,
    partIndex: 0,
    partLength: 0,
    remark: undefined,
    bizType: undefined,
    bizItem: undefined,
    partType: undefined,
    bizValue: undefined,
    cycleMethod: undefined
  };
  proxy.resetForm("formRef");
}

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

// 返回按钮操作
function handleClose() {
  const obj = { path: "/system/autocodeRule" };
  proxy.$tab.closeOpenPage(obj);
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.ruleId = recentRuleId.value;
  handleQuery();
}

// 新增按钮操作
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加规则组成";
  form.value.ruleId = recentRuleId.value;
  
  // 添加调试代码，确保表单字段正确初始化
  nextTick(() => {
    console.log('Form values after reset:', form.value);
    if (proxy.$refs.formRef) {
      proxy.$refs.formRef.clearValidate();
    }
    // 强制更新组件
    setTimeout(() => {
      if (proxy.$refs.formRef) {
        proxy.$refs.formRef.$forceUpdate();
      }
    }, 100);
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.partId)
  single.value = selection.length!=1
  multiple.value = !selection.length
}

// 修改按钮操作
function handleUpdate(row) {
  reset();
  const partId = row.partId || ids.value
  getPart(partId).then(response => {
    form.value = response.data;
    // 确保所有字段都有默认值
    if (form.value.bizType === undefined || form.value.bizType === "") form.value.bizType = null;
    if (form.value.bizItem === undefined || form.value.bizItem === "") form.value.bizItem = null;
    if (form.value.partType === undefined || form.value.partType === "") form.value.partType = null;
    if (form.value.bizValue === undefined || form.value.bizValue === "") form.value.bizValue = null;
    if (form.value.cycleMethod === undefined || form.value.cycleMethod === "") form.value.cycleMethod = null;
    getDictItems();
    open.value = true;
    title.value = "修改规则组成";
    
    // 添加调试代码
    nextTick(() => {
      console.log('Form values after update:', form.value);
      if (proxy.$refs.formRef) {
        proxy.$refs.formRef.clearValidate();
      }
      // 强制更新组件
      setTimeout(() => {
        if (proxy.$refs.formRef) {
          proxy.$refs.formRef.$forceUpdate();
        }
      }, 100);
    });
  });
}

// 提交按钮
function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      if (form.value.partId != undefined) {
        updatePart(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPart(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 删除按钮操作
function handleDelete(row) {
  const partIds = row.partId || ids.value;
  proxy.$modal.confirm('是否确认删除该数据项？').then(function() {
    return delPart(partIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

// 获取字典项
function getDictItems() {
  //获取业务类型
  bizItems.value = [];
  if (!form.value.bizType) {
    form.value.bizItem = null; // 改为 null
    return;
  }
  getDicts(form.value.bizType + '_autocode').then(response => {
    bizItems.value = response.data;
  });
}

// 组件挂载时执行
onMounted(() => {
  //从上级页面获取的规则ID
  const ruleId = route.params && route.params.ruleId;
  recentRuleId.value = ruleId;
  queryParams.value.ruleId = ruleId;
  getList();
  
  // 手动触发一次更新，确保 placeholder 显示
  nextTick(() => {
    if (proxy.$refs.formRef) {
      proxy.$refs.formRef.clearValidate();
    }
    // 强制更新组件
    setTimeout(() => {
      if (proxy.$refs.formRef) {
        proxy.$refs.formRef.$forceUpdate();
      }
    }, 100);
  });
});
</script>