<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="PLC分组" prop="plcConfigId">
              <el-input-number v-model="queryParams.plcConfigId" :min="1" :controls="false" placeholder="请输入PLC分组" />
            </el-form-item>
            <el-form-item label="配置Key" prop="configKey">
              <el-input v-model="queryParams.configKey" placeholder="请输入配置Key" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="配置值" prop="configValue">
              <el-input v-model="queryParams.configValue" placeholder="请输入PLC地址或配置值" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="数据类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择数据类型" clearable filterable>
                <el-option v-for="dict in plc_data_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="启用状态" prop="isFalg">
              <el-select v-model="queryParams.isFalg" placeholder="请选择启用状态" clearable>
                <el-option v-for="dict in is_falg" :key="dict.value" :label="dict.label" :value="Number(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="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wcs:configinfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['wcs:configinfo:edit']">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Finished" :disabled="multiple" @click="handleBatchEdit" v-hasPermi="['wcs:configinfo:edit']">
              批量编辑
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['wcs:configinfo:remove']">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Top" @click="handleImport" v-hasPermi="['wcs:configinfo:import']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wcs:configinfo:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" :columns="columns" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="configinfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column v-if="columns[0].visible" type="index" label="序号" width="60" align="center" />
        <el-table-column v-if="columns[1].visible" label="PLC分组" align="center" prop="plcConfigId" width="90" />
        <el-table-column v-if="columns[2].visible" label="配置Key" align="center" prop="configKey" min-width="180" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[3].visible" label="配置值" align="center" prop="configValue" min-width="170" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[4].visible" label="数据类型" align="center" prop="type" width="110">
          <template #default="scope">
            <dict-tag :options="plc_data_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[5].visible" label="启用状态" align="center" prop="isFalg" width="100">
          <template #default="scope">
            <dict-tag :options="is_falg" :value="scope.row.isFalg" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" label="备注" align="center" prop="remark" min-width="180" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[7].visible" label="创建时间" align="center" prop="createTime" width="170">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="110" 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="['wcs:configinfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wcs:configinfo:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

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

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="640px" append-to-body>
      <el-form ref="configinfoFormRef" :model="form" :rules="rules" label-width="96px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="PLC分组" prop="plcConfigId">
              <el-input-number v-model="form.plcConfigId" :min="1" :controls="false" class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" prop="isFalg">
              <el-radio-group v-model="form.isFalg">
                <el-radio-button v-for="dict in is_falg" :key="dict.value" :value="Number(dict.value)">
                  {{ dict.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="配置Key" prop="configKey">
              <el-input v-model="form.configKey" placeholder="请输入现场业务含义，如3#线体忙碌状态" maxlength="255" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="配置值" prop="configValue">
              <el-input v-model="form.configValue" placeholder="请输入PLC地址或配置值，如DB100.DBX0.2" maxlength="200" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择或输入数据类型" filterable allow-create clearable class="w-full">
                <el-option v-for="dict in plc_data_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入实施备注或避坑说明" maxlength="300" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </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>

    <el-dialog title="批量编辑PLC配置值" v-model="batchDialog.visible" width="980px" append-to-body>
      <el-alert class="mb-3" type="warning" :closable="false" show-icon title="批量保存由后端事务一次提交，任一行失败时全部回滚。" />
      <el-table border :data="batchRows" max-height="460">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="PLC分组" prop="plcConfigId" width="100" align="center" />
        <el-table-column label="配置Key" prop="configKey" min-width="180" :show-overflow-tooltip="true" />
        <el-table-column label="配置值" min-width="220">
          <template #default="scope">
            <el-input v-model="scope.row.configValue" placeholder="请输入配置值" />
          </template>
        </el-table-column>
        <el-table-column label="数据类型" width="150">
          <template #default="scope">
            <el-select v-model="scope.row.type" filterable allow-create clearable>
              <el-option v-for="dict in plc_data_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="启用状态" width="140" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.isFalg">
              <el-option v-for="dict in is_falg" :key="dict.value" :label="dict.label" :value="Number(dict.value)" />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="batchDialog.loading" type="primary" @click="submitBatchEdit">批量保存</el-button>
          <el-button @click="batchDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="upload.open" :title="upload.title" width="420px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" class="ml-2 text-xs" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Configinfo" lang="ts">
import { to } from 'await-to-js';
import { addConfiginfo, delConfiginfo, getConfiginfo, listConfiginfo, updateConfiginfo, updateConfiginfoBatch } from '@/api/wcs/configinfo';
import { ConfiginfoBatchForm, ConfiginfoForm, ConfiginfoQuery, ConfiginfoVO } from '@/api/wcs/configinfo/types';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 与 BaseConfiginfoVo @ExcelDictFormat 对齐；PLC数据类型仍允许现场补充 string(N) 等长度化类型。
const { is_falg, plc_data_type } = toRefs<any>(proxy?.useDict('is_falg', 'plc_data_type'));

const configinfoList = ref<ConfiginfoVO[]>([]);
const selectedRows = ref<ConfiginfoVO[]>([]);
const batchRows = ref<ConfiginfoBatchForm[]>([]);
const buttonLoading = ref(false);
const loading = ref(false);
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 configinfoFormRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();

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

const batchDialog = reactive({
  visible: false,
  loading: false
});

const upload = reactive<ImportOption>({
  open: false,
  title: '',
  isUploading: false,
  updateSupport: 0,
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/wcs/configinfo/importData'
});

const columns = ref<FieldOption[]>([
  { key: 0, label: '序号', visible: true, children: [] },
  { key: 1, label: 'PLC分组', visible: true, children: [] },
  { key: 2, label: '配置Key', visible: true, children: [] },
  { key: 3, label: '配置值', visible: true, children: [] },
  { key: 4, label: '数据类型', visible: true, children: [] },
  { key: 5, label: '启用状态', visible: true, children: [] },
  { key: 6, label: '备注', visible: true, children: [] },
  { key: 7, label: '创建时间', visible: true, children: [] }
]);

const initFormData: ConfiginfoForm = {
  configId: undefined,
  configKey: undefined,
  configValue: undefined,
  isFalg: 0,
  type: undefined,
  remark: undefined,
  plcConfigId: 1
};

const data = reactive<PageData<ConfiginfoForm, ConfiginfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    configKey: undefined,
    configValue: undefined,
    isFalg: undefined,
    type: undefined,
    plcConfigId: undefined,
    params: {}
  },
  rules: {
    plcConfigId: [{ required: true, message: 'PLC配置分组不能为空', trigger: 'blur' }],
    configKey: [{ required: true, message: '配置Key不能为空', trigger: 'blur' }],
    isFalg: [{ required: true, message: '启用状态不能为空', trigger: 'change' }]
  }
});

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

/** 查询PLC配置列表；实施现场通常按PLC分组排查，所以筛选条件保持轻量。 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listConfiginfo(queryParams.value);
    configinfoList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

const reset = () => {
  form.value = { ...initFormData };
  configinfoFormRef.value?.resetFields();
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: ConfiginfoVO[]) => {
  selectedRows.value = selection;
  ids.value = selection.map((item) => item.configId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增PLC配置';
};

const handleUpdate = async (row?: ConfiginfoVO) => {
  reset();
  const configId = row?.configId || ids.value[0];
  const res = await getConfiginfo(configId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改PLC配置';
};

const submitForm = () => {
  configinfoFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    }
    buttonLoading.value = true;
    try {
      if (form.value.configId) {
        await updateConfiginfo(form.value);
      } else {
        await addConfiginfo(form.value);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

const handleBatchEdit = () => {
  // 批量编辑只复制业务字段，避免把表格响应式对象直接提交后出现脏引用。
  batchRows.value = selectedRows.value.map((item) => ({
    configId: item.configId,
    configKey: item.configKey,
    configValue: item.configValue,
    isFalg: item.isFalg,
    type: item.type,
    remark: item.remark,
    plcConfigId: item.plcConfigId
  }));
  batchDialog.visible = true;
};

const submitBatchEdit = async () => {
  const invalidIndex = batchRows.value.findIndex(
    (item) => !item.configId || !item.configKey || item.isFalg === undefined || item.plcConfigId === undefined
  );
  if (invalidIndex >= 0) {
    proxy?.$modal.msgError(`第${invalidIndex + 1}行PLC配置关键字段不完整`);
    return;
  }
  batchDialog.loading = true;
  try {
    await updateConfiginfoBatch(batchRows.value);
    proxy?.$modal.msgSuccess('批量保存成功');
    batchDialog.visible = false;
    await getList();
  } finally {
    batchDialog.loading = false;
  }
};

const handleDelete = async (row?: ConfiginfoVO) => {
  const configIds = row?.configId || ids.value;
  const [err] = await to(proxy?.$modal.confirm('是否确认删除PLC配置编号为"' + configIds + '"的数据项？') as any);
  if (!err) {
    await delConfiginfo(configIds);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
  }
};

const handleImport = () => {
  upload.title = 'PLC配置导入';
  upload.open = true;
};

const importTemplate = () => {
  proxy?.download('wcs/configinfo/importTemplate', {}, `configinfo_template_${new Date().getTime()}.xlsx`);
};

const handleExport = () => {
  proxy?.download('wcs/configinfo/export', { ...queryParams.value }, `configinfo_${new Date().getTime()}.xlsx`);
};

const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  const importMessage = response.data || response.msg || '导入完成';
  ElMessageBox.alert("<div style='overflow:auto;overflow-x:hidden;max-height:70vh;padding:10px 20px 0;'>" + importMessage + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

const submitFileForm = () => {
  uploadRef.value?.submit();
};

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