<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <!-- <el-form-item label="检查单号" prop="documentCode">
        <el-input
          v-model="queryParams.documentCode"
          placeholder="请输入检查单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->

      <!-- <el-form-item label="任务标题" prop="documentName">
        <el-input v-model="queryParams.documentName" placeholder="请输入任务标题" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="检查人" prop="checkerName">
        <el-input v-model="queryParams.checkerName" placeholder="请输入检查人" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="检查时间" prop="checkTime">
        <el-date-picker clearable v-model="queryParams.checkTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择检查时间">
        </el-date-picker>
      </el-form-item> -->

      <el-form-item label="任务标题" prop="taskName">
        <el-input v-model="queryParams.taskName" placeholder="请输入任务标题" clearable style="width: 200px;" />
      </el-form-item>

      <el-form-item label="检查人" prop="checkerName">
        <el-input v-model="queryParams.checkerName" placeholder="请输入检查人" clearable style="width: 200px;" />
      </el-form-item>

      <el-form-item label="检查时间" prop="checkTime">
        <!-- <el-date-picker v-model="queryParams.checkTime" type="daterange" value-format="YYYY-MM-DD" placeholder="请选择检查时间"
          style="width: 200px;" clearable /> -->
        <el-date-picker clearable v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="检查结果" prop="checkResult">
         <el-select v-model="queryParams.checkResult" placeholder="请选择检查结果" clearable style="width: 120px">
          <el-option
            v-for="dict in check_result"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->


      <!-- <el-form-item label="严重程度" prop="severity">
        <el-select v-model="queryParams.severity" placeholder="请选择严重程度" clearable style="width: 120px">
          <el-option
            v-for="dict in check_severity"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="整改状态" prop="correctionStatus">
        <el-select v-model="queryParams.correctionStatus" placeholder="请选择整改状态" clearable style="width: 120px">
          <el-option
            v-for="dict in check_problem_corrections_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="['check:checkRecord:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['check:checkRecord:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['check:checkRecord:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['check:checkRecord:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务编号" align="center" prop="taskCode" width="180" />
      <el-table-column label="任务标题" align="center" prop="taskName" />
      <el-table-column label="检查人" align="center" prop="checkerName" width="100" />
      <el-table-column label="检查时间" align="center" prop="checkTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.checkTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="被检查级别" align="center" prop="checkedLevel" width="100">
        <template #default="scope">
          <dict-tag :options="check_checked_level" :value="scope.row.checkedLevel" />
        </template>
      </el-table-column>
      <el-table-column label="被检查人/班组/主管" align="center" prop="checkedLevel">
        <template #default="scope">
          <div v-if="scope.row.checkedLevel === 'DEPARTMENT_LEVEL'">{{ scope.row.checkedDepartmentName }}</div>
          <div v-if="scope.row.checkedLevel === 'TEAM_LEVEL'">{{ scope.row.checkedTeamName }}</div>
          <div v-if="scope.row.checkedLevel === 'PERSONNEL_LEVEL'">{{ scope.row.checkedPersonnelName }}</div>
          <div v-if="scope.row.checkedLevel === 'BRIGADE_LEVEL'">{{ scope.row.checkedBrigadeName }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['check:checkRecord:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['check:checkRecord:remove']">删除</el-button> -->
          <el-button link type="info" icon="View" @click="handleDetail(scope.row)"
            v-hasPermi="['check:checkRecord:query']">详情</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="1100px" append-to-body>
      <Details v-model:form="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="CheckRecord">
import { listCheckRecord, getCheckRecord, delCheckRecord, addCheckRecord, updateCheckRecord } from "@/api/check/checkRecord"
import Details from './components/Details.vue'
const { proxy } = getCurrentInstance()
const { check_severity, check_checked_level, check_problem_corrections_status, check_result, check_record_type } = proxy.useDict('check_severity', 'check_checked_level', 'check_problem_corrections_status', 'check_result', 'check_record_type')

const checkRecordList = 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 positiveList = ref([])
const negativeList = ref([])
const dateRange = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    checkResult: null,
    problemDescription: null,
    attachmentUrl: null,
    checkedLevel: null,
    checkTime: null,
    documentCode: null,
    documentName: null,
    rectificationSuggestions: null,
    scoreTotal: null,
    comprehensiveEvaluation: null,
    rectificationDeadline: null,
    checkerId: null,
    checkerName: null,
    type: null,
    severity: null,
    isNeedCorrection: null,
    correctionStatus: null,
    checkResultDesc: null,
    checkedLevelDesc: null,
    typeDesc: null,
    severityDesc: null,
    correctionStatusDesc: null,
    attachmentId: null,
    score: null,
    attachmentName: null
  }
})

const { queryParams, form } = toRefs(data)

/** 查询检查记录列表 */
function getList() {
  loading.value = true
  let params = {
    ...queryParams.value,
    startDate: dateRange.value[0],
    endDate: dateRange.value[1]
  }

  listCheckRecord(params).then(response => {
    checkRecordList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

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

// 表单重置
function reset() {
  form.value = {
    tenantId: null,
    revision: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    checkResult: null,
    problemDescription: null,
    attachmentUrl: null,
    remark: null,
    checkedLevel: null,
    checkTime: null,
    id: null,
    documentCode: null,
    documentName: null,
    rectificationSuggestions: null,
    scoreTotal: null,
    comprehensiveEvaluation: null,
    rectificationDeadline: null,
    checkerId: null,
    checkerName: null,
    type: null,
    severity: null,
    isNeedCorrection: null,
    correctionStatus: null,
    checkResultDesc: null,
    checkedLevelDesc: null,
    typeDesc: null,
    severityDesc: null,
    correctionStatusDesc: null,
    attachmentId: null,
    score: null,
    attachmentName: null
  }
  proxy.resetForm("checkRecordRef")
}

/** 搜索按钮操作 */
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 handleDetail(row) {
  reset()
  const _id = row.id || ids.value
  getCheckRecord(_id).then(response => {
    form.value = response.data
    const list = response.data.checkProjectItemList || []
    // todo
    positiveList.value = list.filter(i => i.evaluationType === '1')
    negativeList.value = list.filter(i => i.evaluationType === '0')
    open.value = true
    title.value = "巡检单详情"
  })
}

/** 修改 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getCheckRecord(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改"
  })
}


const viewText = (...rest) => {
  if (Array.isArray(rest) && rest.length) {
    return rest.reduce((cur, acc) => {
      if (acc) {
        cur += cur ? `/${acc}` : acc
      }
      return cur
    }, '')
  }
  return '-'
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除数据项？').then(function () {
    return delCheckRecord(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

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

getList()
</script>

<style>
.record-card {
  margin-bottom: 12px;
  padding: 8px 12px;
  /* border-left: 4px solid #52c41a;    */
  /* background: #f6ffed; */
  border-radius: 4px;
}

.record-line {
  display: flex;
  margin-bottom: 4px;
  font-size: 14px;
  line-height: 1.5;
}

.label {
  color: #666;
  margin-right: 6px;
  flex-shrink: 0;
  width: 70px;
}

.value {
  color: #333;
  flex: 1;
}
</style>