<template>

  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable @change="handleQuery">
          <el-option v-for="dict in com_maintenance_record_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="roleId">
        <el-select v-model="queryParams.roleId" filterable placeholder="请选择角色" @change="handleQuery" clearable>
          <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
        </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" style="min-height:32px">
      <!-- <el-col :span="1.5" v-hasPermi="['maintenanceRecord:maintenanceRecord:add']" v-hasRole="['admin','root']">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">新增
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['maintenanceRecord:maintenanceRecord:edit']" v-hasRole="['admin','root']">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['maintenanceRecord:maintenanceRecord:remove']">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除
                </el-button>
            </el-col> -->
      <el-col :span="1.5" v-hasPermi="['maintenanceRecord:maintenanceRecord:export']">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-card shadow="never">
      <el-table ref="tableRef" v-loading="loading" :data="maintenanceRecordList" @selection-change="handleSelectionChange" :default-sort="defaultSort" @sort-change="handleSortChange">
        <!-- <el-table-column type="selection" width="55" align="center"
                v-hasPermi="['maintenanceRecord:maintenanceRecord:edit', 'maintenanceRecord:maintenanceRecord:remove']" /> -->
        <!-- <el-table-column label="维保记录id" align="center" prop="maintenanceRecordId" v-hasRole="['root']"/> -->
        <el-table-column label="序号" align="center" type="index" width="50" />
        <el-table-column label="部门" align="center" prop="deptName" />
        <!-- <el-table-column label="部门" align="center" prop="deptId">
                    <template #default="scope">
                        <TextTag :options="deptList" column="deptId" label="deptName" :value="scope.row.deptId" />
                    </template>
                </el-table-column> -->
        <el-table-column label="角色" align="center" prop="roleName"/>
        <!-- <el-table-column label="角色" align="center" prop="roleId">
          <template #default="scope">
            <TextTag :options="roleList" column="roleId" label="roleName" :value="scope.row.roleId" text />
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="创建者" align="center" prop="createBy" /> -->
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable="custom" :sort-orders="['descending', 'ascending']">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
        <el-table-column label="状态" align="center" prop="state">
          <template #default="scope">
            <dict-tag :options="com_maintenance_record_state" :value="scope.row.state" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right" v-hasPermi="['maintenanceRecord:maintenanceRecord:query', 'maintenanceRecord:maintenanceRecord:edit', 'maintenanceRecord:maintenanceRecord:remove']">
          <template #default="scope">
            <el-button type="primary" link icon="View" @click="handleView(scope.row)" v-hasPermi="['maintenanceRecord:maintenanceRecord:query']">详细
            </el-button>
            <!--  <el-button type="success" link icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['maintenanceRecord:maintenanceRecord:edit']">修改
                    </el-button>
                    <el-button type="danger" link icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['maintenanceRecord:maintenanceRecord:remove']">删除
                    </el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <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="maintenanceRecordRef" :model="form" :rules="rules" label-width="80px">
      </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>
    <MaintenanceRecordDetailDrawer ref="maintenanceRecordDetailDrawerRef" :maintenanceRecordId="maintenanceRecordId" @update="getList" />

  </div>

</template>

<script setup name="MaintenanceRecord">
import MaintenanceRecordDetailDrawer from "@/components/MaintenanceRecord/detail/drawer";
import {
  listMaintenanceRecord,
  getMaintenanceRecord,
  delMaintenanceRecord,
  addMaintenanceRecord,
  updateMaintenanceRecord,
  downloadMaintenanceRecord,
} from "@/api/maintenanceRecord/maintenanceRecord";
import { listRole } from "@/api/system/role";
import { listDept } from "@/api/system/dept";

const { proxy } = getCurrentInstance();
const { com_maintenance_record_state } = proxy.useDict(
  "com_maintenance_record_state"
);
const maintenanceRecordList = ref([]);
const roleList = ref([]);
const deptList = 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 maintenanceRecordId = ref(null);
const defaultSort = ref({ prop: "createTime", order: "descending" });

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
    roleId: null,
    state: null,
  },
  rules: {
    deptId: [
      {
        required: true,
        message: "部门不能为空",
        trigger: "change",
      },
    ],
    roleId: [
      {
        required: true,
        message: "角色不能为空",
        trigger: "change",
      },
    ],
  },
});
const { queryParams, form, rules } = toRefs(data);
const baseUrl = import.meta.env.VITE_APP_BASE_API;

/** 查询维保记录列表 */
function getList() {
  loading.value = true;
  queryParams.value.orderByColumn =
    queryParams.value.orderByColumn || defaultSort.value.prop;
  queryParams.value.isAsc = queryParams.value.isAsc || defaultSort.value.order;
  listMaintenanceRecord(queryParams.value).then((response) => {
    maintenanceRecordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function addList() {
  loading.value = true;
  listMaintenanceRecord(queryParams.value)
    .then((response) => {
      maintenanceRecordList.value.push(...response.rows);
      total.value = response.total;
      if (maintenanceRecordList.value.length >= total.value)
        finished.value = true;
      loading.value = false;
    })
    .catch((response) => {
      loading.value = false;
    });
}

// 下拉刷新
function handlePullDownRefresh() {
  queryParams.value.pageNum = 1;
  maintenanceRecordList.value = [];
  addList();
}

// 滚动到底部的事件
function handleReachBottom() {
  queryParams.value.pageNum++;
  addList();
}

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

// 表单重置
function reset() {
  form.value = {
    maintenanceRecordId: null,
    deptId: null,
    roleId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    state: null,
  };
  proxy.resetForm("maintenanceRecordRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.pageNum = 1;
  proxy.$refs["tableRef"].sort(defaultSort.value.prop, defaultSort.value.order);
  // handleQuery();
}

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

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加维保记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const maintenanceRecordId = row.maintenanceRecordId || ids.value;
  getMaintenanceRecord(maintenanceRecordId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改维保记录";
  });
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const maintenanceRecordIds = row.maintenanceRecordId || ids.value;
  proxy.$modal
    .confirm(
      '是否确认删除维保记录编号为"' + maintenanceRecordIds + '"的数据项？'
    )
    .then(function () {
      return delMaintenanceRecord(maintenanceRecordIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

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

/** 详细按钮操作 */
function handleView(row) {
  maintenanceRecordId.value = row.maintenanceRecordId;
  proxy.$refs["maintenanceRecordDetailDrawerRef"].show();
}

/** 排序触发事件 */
function handleSortChange(column, prop, order) {
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order;
  getList();
}

function initialData() {
  listDept({
    pageNum: 1,
    pageSize: 9999,
  }).then((response) => {
    deptList.value = response.data;
  });
  listRole(
    proxy.addDateRange(
      {
        pageNum: 1,
        pageSize: 9999,
      },
      undefined
    )
  ).then((response) => {
    roleList.value = response.rows;
  });
  getList();
}

onActivated(() => {
  //// console.log("onActivated")
  initialData();
});
onMounted(() => {
  //// console.log("onMounted")
  initialData();
});
</script>