<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单编号" prop="orderNo">
        <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入工单编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单状态" prop="orderStatus" style="width: 260px">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择工单状态" clearable >
          <el-option
              v-for="dict in repair_status"
              :key="dict.value"
              :label="dict.label"
              :value="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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['repairOrder:repairOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['repairOrder:repairOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['repairOrder:repairOrder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['repairOrder:repairOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>-->

    <el-table v-loading="loading" :data="repairOrderList" @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="orderNo" />
      <el-table-column label="工单内容" align="center" prop="orderContent" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="派单时间" align="center" prop="assignTime" width="180" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.assignTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="责任人" align="center" prop="finishBy" />
      <el-table-column label="工单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <dict-tag :options="repair_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="finishTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="附件" align="center" prop="annex" />
      <!--      <el-table-column label="完成人id" align="center" prop="userId" />-->
      <el-table-column label="工单备注" align="center" prop="orderRemark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
        <template #default="scope">
<!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['repairOrder:repairOrder:edit']">详情</el-button>-->
          <el-button link type="primary" icon="View" @click="showDetail(scope.row)" v-hasPermi="['repairOrder:repairOrder:edit']">详情</el-button>
          <el-button
              v-if="scope.row.orderStatus === '1'"
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['repairOrder:repairOrder:edit']"
          >处理</el-button>
<!--          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['repairOrder:repairOrder: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-drawer
        v-model="detailVisible"
        title="工单详情"
        direction="rtl"
        size="40%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="工单编号">{{ detailData.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="工单内容">{{ detailData.orderContent }}</el-descriptions-item>
        <el-descriptions-item label="项目名称">{{ detailData.projectName }}</el-descriptions-item>
        <el-descriptions-item label="派单时间">{{ parseTime(detailData.assignTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ parseTime(detailData.finishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="责任人">{{ detailData.finishBy }}</el-descriptions-item>
        <el-descriptions-item label="工单状态">
          <dict-tag :options="repair_status" :value="detailData.orderStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="工单备注">{{ detailData.orderRemark }}</el-descriptions-item>
        <el-descriptions-item label="附件">{{ detailData.annex }}</el-descriptions-item>

      </el-descriptions>
      <el-button type="primary" @click="downloadFile(detailData.annex)">下载附件</el-button>
    </el-drawer>

    <!-- 添加或修改维修工单对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="repairOrderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入工单编号" disabled/>
        </el-form-item>
        <el-form-item label="工单内容" prop="orderContent">
          <el-input v-model="form.orderContent" type="textarea" placeholder="请输入内容" disabled/>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" disabled/>
        </el-form-item>
        <el-form-item label="派单时间" prop="assignTime" >
          <el-date-picker clearable
                          v-model="form.assignTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择派单时间" disabled>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完成时间" prop="finishTime" :rules="rules.finishTime">
          <el-date-picker clearable
                          v-model="form.finishTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="责任人" prop="finishBy" >
          <el-select
              v-model="form.userId"
              placeholder="请选择责任人"
              clearable
              filterable
              disabled
          >
            <el-option
                v-for="user in userOptions"
                :key="user.userId"
                :label="user.userName || user.userName"
                :value="user.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="附件" prop="annex">
          <file-upload v-model="form.annex" :on-remove="handleRemoveFile"/>
        </el-form-item>
        <!--
        <el-form-item label="完成人id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入完成人id" />
        </el-form-item>-->
<!--        <el-form-item label="工单状态" prop="orderStatus">
          <el-radio-group v-model="form.orderStatus">
            <el-radio
                v-for="dict in repair_status"
                :key="dict.value"
                :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>-->
        <el-form-item label="工单备注" prop="orderRemark">
          <el-input v-model="form.orderRemark" 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>
  </div>
</template>

<script setup name="RepairOrder">
import { listRepairOrder, getRepairOrder, delRepairOrder, addRepairOrder, updateRepairOrder,deleteFile } from "@/api/repairOrder/repairOrder";
import { listUser } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const { repair_status } = proxy.useDict('repair_status');

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

const detailVisible = ref(false);
const detailData = ref({});

const data = reactive({
  form: {},
  queryParams: {
    isMe: true,
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    orderContent: null,
    projectName: null,
    orderStatus: null,
    state:Date.now(),
  },
  rules: {
    finishTime: [
      { required: true, message: "完成时间不能为空", trigger: "blur" }
    ]
  }
});

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

function showDetail(row) {
  detailData.value = {...row};
  detailVisible.value = true;
}

function downloadFile(url) {
  window.open(import.meta.env.VITE_APP_BASE_API+url);
}

/** 查询维修工单列表 */
function getList() {
  loading.value = true;
  listRepairOrder(queryParams.value).then(response => {
    repairOrderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function handleRemoveFile(file) {
  // 这里可以添加调用后端API删除文件的逻辑
  proxy.$modal.confirm('确认删除该附件吗？').then(() => {
    deleteFile(file.url).then(() => {
      form.value.annex = null;
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {
      proxy.$modal.msgError("删除失败");
    });
  }).catch(() => {});
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNo: null,
    orderContent: null,
    projectName: null,
    assignTime: null,
    finishTime: null,
    finishBy: null,
    annex: null,
    userId: null,
    orderStatus: null,
    orderRemark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("repairOrderRef");
}

/** 搜索按钮操作 */
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 getUserList() {
  listUser().then(response => {
    userOptions.value = response.rows || [];
  });
}

// 在组件挂载时获取用户列表
onMounted(() => {
  getUserList();
});
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getRepairOrder(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "维修工单派单";
  });

}

/** 提交按钮 */
function submitForm() {
  if (form.value.userId) {
    const user = userOptions.value.find(u => u.userId === form.value.userId);
    if (user) {
      form.value.finishBy = user.nickName || user.userName;
      form.value.userId = user.userId || user.userId;
    }
  }
  proxy.$refs["repairOrderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRepairOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRepairOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  const deletePromises = [];
  proxy.$modal.confirm('是否确认删除选中的数据项？').then(function() {
    // 如果是批量删除，检查每个选中项是否有附件
    if (Array.isArray(ids.value) && ids.value.length > 0) {
      repairOrderList.value.forEach(item => {
        if (ids.value.includes(item.id) && item.annex) {
          deletePromises.push(deleteFile(item.annex));
        }
      });
    }
    // 如果是单个删除，检查是否有附件
    else if (row.annex) {
      deletePromises.push(deleteFile(row.annex));
    }
    // 先删除所有附件
    return Promise.all(deletePromises)
        .then(() => {
          // 附件删除成功后删除数据
          return delRepairOrder(_ids);
        });
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
    proxy.$modal.msgError("删除失败");
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('repairOrder/repairOrder/export', {
    ...queryParams.value
  }, `repairOrder_${new Date().getTime()}.xlsx`)
}

getList();
</script>
