<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-position="top">
      <el-form-item label="机型" prop="fanType" label-position="top">
        <el-select
          v-model="queryParams.fanType"
          placeholder="请选择机型"
          clearable
          filterable
          @change="handleQuery"
        >
          <el-option
            v-for="item in fanTypeOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="维保类型" prop="inspectionTypeId" label-position="top">
        <el-select
          v-model="queryParams.inspectionTypeId"
          placeholder="请选择维保类型"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="dict in gxt_inspection_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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:scorefaninspection:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gxt:scorefaninspection:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gxt:scorefaninspection:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="Upload" @click="handleImport" v-hasPermi="['gxt:scorefaninspection:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="Download"
          @click="handleExport"
          v-hasPermi="['gxt:scorefaninspection:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fanInspectionScoreList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="机型" align="center" prop="fanType" />
      <el-table-column label="维保类型" align="center" prop="inspectionTypeId">
        <template #default="scope">
          <dict-tag :options="gxt_inspection_type" :value="scope.row.inspectionTypeId" />
        </template>
      </el-table-column>
      <el-table-column label="分值" align="center" prop="score" />
      <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
            size="small"
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['gxt:scorefaninspection:edit']"
          >修改</el-button>
          <el-button
            size="small"
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gxt:scorefaninspection: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="80px">
        <el-form-item label="机型" prop="fanType">
          <el-select
            v-model="form.fanType"
            placeholder="请选择机型"
            clearable
            filterable
          >
            <el-option
              v-for="item in fanTypeOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维保类型" prop="inspectionTypeId">
          <el-select
            v-model="form.inspectionTypeId"
            placeholder="请选择维保类型"
            clearable
          >
            <el-option
              v-for="dict in gxt_inspection_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分值" prop="score">
          <el-input-number v-model="form.score" :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="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + (upload.updateSupport ? 'true' : 'false')" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-change="handleFileChange" :on-remove="handleFileRemove" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @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>
    
    <!-- 字段选择对话框 -->
    <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="small" style="width:5px;" @click="upDown('up')" /><br/>
        <el-button type="primary" icon="download" size="small" 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="FanInspectionScore">
import { getToken } from "@/utils/auth"
import { listFanInspectionScore, getFanInspectionScore, delFanInspectionScore, addFanInspectionScore, updateFanInspectionScore, listFanTypes, getExportFields } from "@/api/gxt/fanInspectionScore";
import { getCurrentInstance, reactive, ref, toRefs, onMounted, watch } from "vue";

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

const fanInspectionScoreList = 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 fanTypeOptions = ref([]);

/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的数据
  updateSupport: true,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/gxt/fanInspectionScore/importData"
})

// 导出字段选择相关
const showExportFieldsDialog = ref(false);
const exportFieldsSelected = ref([]);
const exportFieldsData = ref([]);

const data = reactive({
  form: {
    id: null,
    fanType: null,
    inspectionTypeId: null,
    score: null,
    status: "0",
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fanType: null,
    inspectionTypeId: null,
    score: null,
    status: null
  },
  rules: {
    fanType: [
      { required: true, message: "机型不能为空", trigger: "change" }
    ],
    inspectionTypeId: [
      { required: true, message: "维保类型不能为空", trigger: "change" }
    ],
    score: [
      { required: true, message: "分值不能为空", trigger: "blur" }
    ]
  }
});

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

/** 查询机型列表 */
function getFanTypeList() {
  listFanTypes().then(response => {
    fanTypeOptions.value = response.data;
  });
}

/** 查询机型维保分值列表 */
function getList() {
  loading.value = true;
  listFanInspectionScore(queryParams.value).then(response => {
    fanInspectionScoreList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    fanType: null,
    inspectionTypeId: null,
    score: null,
    status: 0,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("formRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  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
  getFanInspectionScore(id).then(response => {
    // 确保inspectionTypeId是字符串类型，以便与字典选项匹配
    form.value = {
      ...response.data,
      inspectionTypeId: response.data.inspectionTypeId ? String(response.data.inspectionTypeId) : null
    };
    open.value = true;
    title.value = "修改机型维保分值配置";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      // 提交前确保inspectionTypeId是数字类型
      const submitData = {
        ...form.value,
        inspectionTypeId: form.value.inspectionTypeId ? Number(form.value.inspectionTypeId) : null
      };
      
      if (submitData.id != null) {
        updateFanInspectionScore(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFanInspectionScore(submitData).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 delFanInspectionScore(deleteIds)
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "风机定检分值导入"
  upload.open = true
  upload.selectedFile = null
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("gxt/fanInspectionScore/importTemplate", {
  }, `fanInspection_score_template_${new Date().getTime()}.xlsx`)
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件选择处理 */
const handleFileChange = (file, fileList) => {
  upload.selectedFile = file
}

/** 文件删除处理 */
const handleFileRemove = (file, fileList) => {
  upload.selectedFile = null
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
  getList()
}

/** 提交上传文件 */
function submitFileForm() {
  const file = upload.selectedFile
  if (!file || file.length === 0 || !file.name.toLowerCase().endsWith('.xls') && !file.name.toLowerCase().endsWith('.xlsx')) {
    proxy.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
    return
  }
  proxy.$refs["uploadRef"].submit()
}

/** 导出按钮操作 */
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/fanInspectionScore/export', exportParams, `fanInspectionScore_${new Date().getTime()}.xlsx`)
  
  showExportFieldsDialog.value = false;
}

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


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)
      }
    })
  }
}

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