<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-position="top">
      <el-form-item label="连续安全运行时长" prop="safeDuration" label-position="top">
        <el-input-number
          v-model="queryParams.safeDuration"
          placeholder="请输入时长"
          clearable
          @keyup.enter="handleQuery"
          controls-position="right" :precision="0" :step="1" :min="0" :max="9999"
        />
      </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:safeoperationreward:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gxt:safeoperationreward:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gxt:safeoperationreward:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="Download"
          @click="handleExport"
          v-hasPermi="['gxt:safeoperationreward:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="safeOperationRewardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="连续安全运行时长" align="center">
        <template #default="scope">{{ '≥' + scope.row.safeDuration + '天'}}</template>
      </el-table-column>
      <el-table-column label="维保工单奖励分值" prop="plannedMaintenanceScore"  align="center"/>
      <el-table-column label="维修工单奖励分值" prop="unplannedMaintenanceScore" align="center"/>
      <el-table-column label="长时间停运扣分值" prop="downtimeScore" align="center"/>
      <el-table-column label="启用状态" prop="status" align="center">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" class-name="small-padding fixed-width" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['gxt:safeoperationreward:edit']"><i class="fa fa-edit"></i>编辑</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['gxt:safeoperationreward:remove']"><i class="fa fa-trash"></i>删除</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="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="200px">
        <el-form-item label="连续安全运行时长(≥)" prop="safeDuration">
          <el-input-number v-model="form.safeDuration" placeholder="请输入连续安全运行时长（天）" controls-position="right" :precision="0" :step="1" :min="0" :max="9999" style="width: 80%"/>（天）
        </el-form-item>
        <el-form-item label="维保工单奖励分值" prop="plannedMaintenanceScore">
          <el-input-number v-model="form.plannedMaintenanceScore" controls-position="right" :precision="2" :step="0.1" :min="0" :max="999" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="维修工单奖励分值" prop="unplannedMaintenanceScore">
          <el-input-number v-model="form.unplannedMaintenanceScore" controls-position="right" :precision="2" :step="0.1" :min="0" :max="999" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="长时间停运扣分值" prop="downtimeScore">
          <el-input-number v-model="form.downtimeScore" controls-position="right" :precision="2" :step="0.1" :max="0" :min="-999" style="width: 100%"/>
        </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="请输入内容" maxlength="200" show-word-limit/>
        </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="SafeOperationReward">
import { ref, reactive, toRefs, getCurrentInstance } from "vue"
import { listSafeOperationReward, getSafeOperationReward, delSafeOperationReward, addSafeOperationReward, updateSafeOperationReward, exportSafeOperationReward, getExportFields } from "@/api/gxt/safeOperationReward"

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

const safeOperationRewardList = 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,
    safeDuration: undefined,
    plannedMaintenanceScore: undefined,
    unplannedMaintenanceScore: undefined,
    downtimeScore: undefined,
    status: undefined
  },
  rules: {
    safeDuration: [{ required: true, message: "连续安全运行时长不能为空", trigger: "blur" }],
    plannedMaintenanceScore: [{ required: true, message: "维保工单奖励分值不能为空", trigger: "blur" }],
    unplannedMaintenanceScore: [{ required: true, message: "维修工单奖励分值不能为空", trigger: "blur" }],
    downtimeScore: [{ required: true, message: "长时间停运扣分值不能为空", trigger: "blur" }]
  }
})

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

/** 查询奖惩分值列表 */
function getList() {
  loading.value = true
  listSafeOperationReward(queryParams.value).then(response => {
    safeOperationRewardList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

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

/** 表单重置 */
function reset() {
  form.value = {
    safeDuration: undefined,
    plannedMaintenanceScore: undefined,
    unplannedMaintenanceScore: undefined,
    downtimeScore: undefined,
    status: 0,
    remark: undefined
  }
  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
  getSafeOperationReward(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 != undefined) {
        updateSafeOperationReward(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSafeOperationReward(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 delSafeOperationReward(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/safeoperationreward/export", exportParams, `safeoperationreward_${new Date().getTime()}.xlsx`)
  
  showExportFieldsDialog.value = false
}

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

/** 解析时间 */
function parseTime(time) {
  if (!time) return ''
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

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>