<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-position="top">
      <!-- <el-form-item label="检修类型代码" prop="maintenanceType" label-position="top">
        <el-input
          v-model="queryParams.maintenanceType"
          placeholder="请输入检修类型代码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="检修类型" prop="projectName" label-position="top">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入检修类型"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="status" label-position="top">
        <el-select v-model="queryParams.status" placeholder="启用状态" clearable>
          <el-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label-position="top">
        <div class="item-search">&nbsp;</div>
        <div class="item-search">
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        </div>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['gxt:scoreproject:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gxt:scoreproject:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gxt:scoreproject:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="Download"
          @click="handleExport"
          v-hasPermi="['gxt:scoreproject:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scoreprojectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <!-- <el-table-column label="检修类型代码" align="center" prop="maintenanceType" /> -->
      <el-table-column label="检修类型" align="center" prop="projectName" />
      <el-table-column label="分值" align="center" prop="scorePerCompletion" />
      <el-table-column label="启用状态" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['gxt:scoreproject:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['gxt:scoreproject:remove']">删除</el-button>
        </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-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="检修类型代码" prop="maintenanceType">
          <el-select v-model="form.maintenanceType" placeholder="请选择检修类型代码" @change="handleMaintenanceTypeChange">
            <el-option
              v-for="dict in gxt_maintenance_type"
              :key="dict.value"
              :label="dict.value"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="检修类型" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入检修类型" readonly />
        </el-form-item>
        <el-form-item label="分值" prop="scorePerCompletion">
          <el-input-number v-model="form.scorePerCompletion" :precision="2" :step="0.1" controls-position="right" />
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="Number(dict.value)"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </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>
    
    <!-- 字段选择对话框 -->
    <el-dialog title="选择导出字段" v-model="showExportFieldsDialog" width="600px" append-to-body>
      <div style="position: absolute;bottom: 65px;right: 38%;">
        <el-button type="primary" icon="upload" size="mini" style="width:5px;" @click="upDown('up')" /><br/>
        <el-button type="primary" icon="download" size="mini" style="margin-top:3px;width:5px;" @click="upDown('down')" />
      </div>
      <el-transfer 
        v-model="exportFieldsSelected" 
        :data="exportFieldsData" 
        :titles="['可选字段', '导出字段']"
        target-order = "push"
        show-checkbox
        filterable
        filter-placeholder="请输入字段名称"
        @right-check-change="rightCheckHandler">
      </el-transfer>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showExportFieldsDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmExport">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Scoreproject">
import { ref, reactive, toRefs, getCurrentInstance } from "vue"
import { listScoreproject, getScoreproject, delScoreproject, addScoreproject, updateScoreproject, exportScoreproject, getExportFields } from "@/api/gxt/scoreproject";

const { proxy } = getCurrentInstance();
const { gxt_maintenance_type,sys_normal_disable } = proxy.useDict("gxt_maintenance_type","sys_normal_disable");

const scoreprojectList = ref([]);
const open = ref(false);
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 showExportFieldsDialog = ref(false);
const exportFieldsSelected = ref([]);
const exportFieldsData = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    maintenanceType: null,
    projectName: null,
    status: null
  },
  rules: {
    maintenanceType: [
      { required: true, message: "检修类型代码不能为空", trigger: "change" }
    ],
    projectName: [
      { required: true, message: "检修类型不能为空", trigger: "blur" }
    ],
    scorePerCompletion: [
      { required: true, message: "分值不能为空", trigger: "blur" }
    ]
  }
});

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

/** 查询检修类型分值列表 */
function getList() {
  loading.value = true;
  listScoreproject(queryParams.value).then(response => {
    scoreprojectList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    maintenanceType: null,
    projectName: null,
    scorePerCompletion: null,
    status: 0,
    remark: null
  };
  proxy.resetForm("formRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

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

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加检修类型分值配置";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getScoreproject(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改检修类型分值配置";
  });
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const deleteIds = row.id || ids.value
  proxy.$modal.confirm('是否确认删除检修类型分值配置编号为"' + deleteIds + '"的数据项？').then(function() {
    return delScoreproject(deleteIds)
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  // 获取导出字段数据并处理默认选中
  getExportFieldsData().then(() => {
    // 显示字段选择对话框
    showExportFieldsDialog.value = true;
    
    // 定义默认选中的字段（基于字段标签）
    const defaultSelectedLabels = [
      '检修类型',
      '分值',
      '启用状态'
    ];
    
    // 在导出字段中查找对应的key
    const selectedKeys = [];
    exportFieldsData.value.forEach(field => {
      if (defaultSelectedLabels.includes(field.label)) {
        selectedKeys.push(field.key);
      }
    });
    
    // 设置默认选中的字段
    exportFieldsSelected.value = selectedKeys;
  });
}

/** 确认导出 */
function confirmExport() {
  if (exportFieldsSelected.value.length === 0) {
    proxy.$modal.msgWarning("请至少选择一个导出字段");
    return;
  }
  
  // 将导出字段拼接成字符串
  const exportFieldsStr = exportFieldsSelected.value.join(',');
  
  const exportParams = {
    ...queryParams.value,
    exportFields: exportFieldsStr
  };

  proxy.download("gxt/scoreproject/export", exportParams, `scoreproject_${new Date().getTime()}.xlsx`);
  
  showExportFieldsDialog.value = false;
}

/** 获取导出字段数据 */
function getExportFieldsData() {
  return getExportFields().then(response => {
    exportFieldsData.value = response.data;
    return response.data;
  });
}

/** 处理检修类型代码变更 */
function handleMaintenanceTypeChange(value) {
  // 根据选择的检修类型代码设置对应的检修类型
  const selectedItem = gxt_maintenance_type.value.find(item => item.value === value);
  if (selectedItem) {
    form.value.projectName = selectedItem.label;
  } else {
    form.value.projectName = '';
  }
}


const rightChecks = ref([])
function rightCheckHandler(val) {
  rightChecks.value = exportFieldsSelected.value
    .filter(item => val.includes(item))
  console.log(rightChecks.value, "rightCheckHandler")
}

function upDown(direction) {
   // 找出最小和最大索引
  const indices = rightChecks.value
    .map(i => exportFieldsSelected.value.indexOf(i))
    .filter(i => i !== -1)
  const minIndex = Math.min(...indices)
  const maxIndex = Math.max(...indices)
  // 边界检查
  if (direction === 'up' && minIndex === 0) {
    console.log('已到顶部')
    return
  }
  if (direction === 'down' && maxIndex === exportFieldsSelected.value.length - 1) {
    console.log('已到底部')
    return
  }
  if (direction === 'up') {
    rightChecks.value.map(i => {
      const index = exportFieldsSelected.value.findIndex(t => t == i)
      exportFieldsSelected.value.splice(index, 1);
      exportFieldsSelected.value.splice(index - 1, 0, i);
    })
  } else {
    rightChecks.value.slice().reverse().forEach(i => {
      const index = exportFieldsSelected.value.findIndex(t => t == i)
      if (index < exportFieldsSelected.value.length - 1) {
        exportFieldsSelected.value.splice(index, 1)
        exportFieldsSelected.value.splice(index + 1, 0, i)
      }
    })
  }
}

getList();
</script>