<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-position="top">
      <el-form-item label="场站" prop="station" label-position="top">
        <el-select
            v-model="queryParams.station"
            placeholder="请选择场站"
            clearable
            @change="handleQueryStationChange"
        >
          <el-option
              v-for="item in stationOptions"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="机型" prop="model" label-position="top">
        <el-select
            v-model="queryParams.model"
            placeholder="请选择机型"
            clearable
            :disabled="!queryParams.station"
        >
          <el-option
              v-for="item in modelOptions"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="故障代码" prop="faultCode" label-position="top">
        <el-input
            v-model="queryParams.faultCode"
            placeholder="请输入故障代码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="isActive" label-position="top">
        <el-select
            v-model="queryParams.isActive"
            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"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['gxt:faultCodes:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gxt:faultCodes:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gxt:faultCodes:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['gxt:faultCodes:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['gxt:faultCodes:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="faultCodesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="场站" align="center" prop="station" />
      <el-table-column label="机型" align="center" prop="model" />
      <el-table-column label="故障代码" align="center" prop="faultCode" />
      <el-table-column label="故障条文" align="center" prop="faultBarcode" />
      <el-table-column label="故障描述" align="center" prop="faultDescription" />
      <el-table-column label="启用状态" align="center" prop="isActive">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.isActive"/>
        </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:faultCodes:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['gxt:faultCodes: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="700px" append-to-body>
      <el-form ref="faultCodesRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="场站" prop="station">
              <el-select
                  v-model="form.station"
                  placeholder="请选择场站"
                  clearable
                  @change="handleStationChange"
              >
                <el-option
                    v-for="item in stationOptions"
                    :key="item.deptId"
                    :label="item.deptName"
                    :value="item.deptName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机型" prop="model">
              <el-select
                  v-model="form.model"
                  placeholder="请选择机型"
                  clearable
                  :disabled="!form.station"
              >
                <el-option
                    v-for="item in modelOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="故障代码" prop="faultCode">
              <el-input v-model="form.faultCode" placeholder="请输入故障代码" maxlength="10" show-word-limit v-chinese-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障条文" prop="faultBarcode">
              <el-input v-model="form.faultBarcode" placeholder="请输入故障条文" maxlength="20" show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="启用状态" prop="isActive">
              <el-radio-group v-model="form.isActive">
                <el-radio
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :value="parseInt(dict.value)"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="故障描述" prop="faultDescription">
              <el-input v-model="form.faultDescription" type="textarea" placeholder="请输入内容" :rows="4" maxlength="200" show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="4" maxlength="200" show-word-limit/>
            </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>

    <!-- 故障代码导入对话框 -->
    <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" :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="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="FaultCodes">
import { listFaultCodes, getFaultCodes, delFaultCodes, addFaultCodes, updateFaultCodes, listStations, listModelsByStationId, getExportFields, } from "@/api/gxt/faultCodes"
import { getToken } from "@/utils/auth"

const { proxy } = getCurrentInstance()

// 定义字典
const { sys_normal_disable } = proxy.useDict("sys_normal_disable" )

const faultCodesList = 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 stationOptions = ref([])
const modelOptions = ref([])

// 导出字段相关变量
const showExportFieldsDialog = ref(false)
const exportFieldsData = ref([])
const exportFieldsSelected = ref([])

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

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    faultCode: null,
    faultDescription: null,
    isActive: null,
    faultBarcode: null,
    station: null,
    model: null,
    stationId: null,
  },
  rules: {
    station: [
      { required: true, message: "场站不能为空", trigger: "change" }
    ],
    model: [
      { required: true, message: "机型不能为空", trigger: "blur" }
    ],
    /*faultCode: [
      { required: true, message: "故障代码不能为空", trigger: "blur" }
    ],*/
    faultBarcode: [
      { required: true, message: "故障条文不能为空", trigger: "blur" }
    ],
    /*faultDescription: [
      { required: true, message: "故障描述不能为空", trigger: "blur" }
    ],*/
  }
})

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

/** 查询故障代码管理列表 */
function getList() {
  loading.value = true
  listFaultCodes(queryParams.value).then(response => {
    faultCodesList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 查询场站列表 */
function getStationList() {
  listStations().then(response => {
    stationOptions.value = response.data
  })
}

/** 根据场站ID查询机型列表 */
function getModelListByStationId(stationId) {
  if (!stationId) {
    modelOptions.value = []
    return
  }
  listModelsByStationId(stationId).then(response => {
    modelOptions.value = response.data
  })
}

/** 场站选择变化时，加载对应的机型 */
function handleStationChange(stationName) {
  if (stationName) {
    // 查找选中场站的ID
    const selectedStation = stationOptions.value.find(item => item.deptName === stationName)
    if (selectedStation) {
      getModelListByStationId(selectedStation.deptId)
      // 设置场站ID
      form.value.stationId = selectedStation.deptId
    }
    form.value.model = null
  } else {
    // 如果清空了场站选择，也清空机型选择和场站ID
    modelOptions.value = []
    form.value.model = null
    form.value.stationId = null
  }
}

/** 查询表单中场站选择变化时，加载对应的机型 */
function handleQueryStationChange(stationName) {
  if (stationName) {
    // 查找选中场站的ID
    const selectedStation = stationOptions.value.find(item => item.deptName === stationName)
    if (selectedStation) {
      getModelListByStationId(selectedStation.deptId)
      // 设置查询参数中的场站ID
      queryParams.value.stationId = selectedStation.deptId
    }
    queryParams.value.model = null
  } else {
    // 如果清空了场站选择，也清空机型选择和场站ID
    modelOptions.value = []
    queryParams.value.model = null
    queryParams.value.stationId = null
  }
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    faultCode: null,
    faultBarcode: null,
    faultDescription: null,
    isActive: 0,
    station: null,
    model: null,
    stationId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  }
  proxy.resetForm("faultCodesRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  // 根据场站名称获取场站ID
  if (queryParams.value.station) {
    const selectedStation = stationOptions.value.find(item => item.deptName === queryParams.value.station)
    if (selectedStation) {
      queryParams.value.stationId = selectedStation.deptId
    }
  }
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.stationId = null
  queryParams.value.model = null
  modelOptions.value = []
  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
  getFaultCodes(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改故障代码"
    // 加载机型列表（如果场站已选择）
    if (form.value.station) {
      const selectedStation = stationOptions.value.find(item => item.deptName === form.value.station)
      if (selectedStation) {
        getModelListByStationId(selectedStation.deptId)
      }
    }
  })
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除故障代码编号为"' + _ids + '"的数据项？').then(function() {
    return delFaultCodes(_ids)
  }).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/faultCodes/export', exportParams, `faultCodes_${new Date().getTime()}.xlsx`);
  
  showExportFieldsDialog.value = false;
}

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

/** 导入按钮操作 */
function handleImport() {
  upload.title = "故障代码导入"
  upload.open = true
  upload.selectedFile = null
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("gxt/faultCodes/importTemplate", {
  }, `faultCodes_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()
}

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

getStationList()
getList()
</script>