<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">

      <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="checkedLevel">
        <el-select v-model="queryParams.checkedLevel" placeholder="请选择被检查级别" clearable style="width: 200px;">
          <el-option v-for="dict in check_checked_level" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable style="width: 200px;">
          <el-option v-for="dict in check_task_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="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</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" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="开始时间" align="center" prop="checkStartTime" />
      <el-table-column label="结束时间" align="center" prop="checkEndTime" />
      <el-table-column label="任务状态" align="center" prop="statusDesc">
        <!-- <template #default="scope">
          <div class="color-div">
            <div class="round" :style="{ backgroundColor: scope.row.statusDesc === '已结束' ? '#6BC77F' : '#5EA4FF' }">
            </div>
            <div>{{ scope.row.statusDesc }}</div>
          </div>
  
        </template> -->
      </el-table-column>
      <el-table-column label="发布人" align="center" prop="createBy" />
      <el-table-column label="发布日期" align="center" prop="createTime">
        <template #default="scope">
          {{ moment(scope.row.createTime).format('YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <el-table-column label="被检查级别" align="center" prop="checkedLevelDesc">
        <!-- <template #default="scope">
          <dict-tag :options="check_checked_level" :value="scope.row.checkedLevel" />
        </template> -->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)"
            v-hasPermi="['check:checkRecord:query']">详情</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['check:checkRecord: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="1000px" append-to-body>
      <el-form ref="checkRecordRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12" v-if="title !== '巡检任务新建'">
            <el-form-item label="任务编号" prop="taskCode">
              <el-input v-model="form.taskCode" placeholder="请输入任务编号" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入任务名称" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务时间" prop="timeRange">
              <div style="display: flex; align-items: center;">
                <el-date-picker v-model="form.timeRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                  end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 80%" :disabled="formDisabled" />
                <span v-if="form.timeRange && form.timeRange.length === 2" style="margin-left: 10px">
                  共 {{ calculateDayDiff(form.timeRange[0], form.timeRange[1]) }} 天
                </span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检查级别" prop="checkLevel">
              <el-select v-model="form.checkLevel" placeholder="请选择检查级别" style="width: 100%"
                @change="handleCheckLevelChange" :disabled="formDisabled">
                <el-option v-for="dict in check_level" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="被检查级别" prop="checkedLevel">
              <el-select v-model="form.checkedLevel" placeholder="请选择被检查级别" :disabled="true" style="width: 100%">
                <el-option v-for="dict in check_checked_level" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="任务类型" prop="checkCategory">
              <el-select v-model="form.checkCategory" placeholder="请选择任务类型" style="width: 100%"
                :disabled="formDisabled">
                <el-option v-for="dict in check_task_category" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行频率" prop="ruleType" :required="true">
              <div style="display: flex;width: 100%;">
                <el-select v-model="form.ruleType" placeholder="请选择执行频率" style="width: 100%" :disabled="formDisabled">
                  <el-option v-for="dict in check_rule_type" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
                <el-input-number v-model="form.ruleTypeNum" :default-value="1" :min="1" style="margin-left: 10px"
                  :disabled="formDisabled" />
                <span style="margin-left: 10px">次</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否科内自查" prop="isSelfCheck">
              <el-radio-group v-model="form.isSelfCheck" :disabled="formDisabled">
                <el-radio :value="1">是</el-radio>
                <el-radio :value="0">否</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="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入任务简介" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="检查项目" prop="checkProjectItemList">
              <div v-for="(item, index) in checkItemsList" :key="index" style="margin-bottom: 20px;">
                <el-tree :ref="`tree_${index}`" :data="[item]" :props="{ children: 'list', label: 'name' }"
                  show-checkbox node-key="code" :default-expand-all="true" :expand-on-click-node="false"
                  :default-checked-keys="checkedCodes" :disabled="formDisabled">
                  <template #default="{ node, data }">
                    <span>{{ node.label }}</span>
                  </template>
                </el-tree>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!formDisabled" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CheckTask">
import { listCheckTask, getCheckTask, delCheckTask, addCheckTask, getCheckProjectItemList } from "@/api/check/checkTask"
import { computed } from "vue"
import moment from 'moment'
const { proxy } = getCurrentInstance()
const { check_checked_level, check_task_status, check_level, check_rule_type, check_task_category } = proxy.useDict('check_checked_level', 'check_task_status', 'check_level', 'check_rule_type', 'check_task_category')


/** 计算日期差 */
const calculateDayDiff = (startDate, endDate) => {
  const start = new Date(startDate)
  const end = new Date(endDate)
  const diffTime = Math.abs(end - start)
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

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 formDisabled = computed(() => {
  return title.value === '巡检任务详情'
})

const data = reactive({
  form: {
    isSelfCheck: 0,
    timeRange: [],
    ruleTypeNum: 1,
    checkProjectItemList: []
  },
  checkItemsList: [],
  checkedCodes: [],//回显选中的节点
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    checkResult: null,
    problemDescription: null,
    attachmentUrl: null,
    checkedLevel: null,
    documentCode: null,
    taskName: null,
    rectificationSuggestions: null,
    comprehensiveEvaluation: null,
    rectificationDeadline: null,
    correctionStatus: null,
    checkResultDesc: null,
    correctionStatusDesc: null,
    attachmentId: null,
    score: null,
    attachmentName: null
  },
  rules: {
    taskCode: [
      { required: false, message: "请输入任务编号", trigger: "blur" }
    ],
    taskName: [
      { required: true, message: "请输入任务名称", trigger: "blur" }
    ],
    timeRange: [
      { required: true, message: "请选择任务时间范围", trigger: "change" }
    ],
    checkLevel: [
      { required: true, message: "请选择检查级别", trigger: "change" }
    ],
    checkedLevel: [
      { required: true, message: "请选择被检查级别", trigger: "change" }
    ],
    ruleType: [
      { required: true, message: "请选择执行频率", trigger: "change" }
    ],
    ruleTypeNum: [
      { required: true, message: "请输入频率值", trigger: "change" },
    ],
    checkCategory: [
      { required: true, message: "请选择任务类型", trigger: "change" }
    ],
    description: [
      { required: true, message: "请输入任务简介", trigger: "blur" }
    ],
  }
})

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

const handleCheckLevelChange = (val) => {
  if ('STATION_LEVEL' == val) {
    form.value.checkedLevel = 'DEPARTMENT_LEVEL'
  }
  if ('DEPARTMENT_LEVEL' == val) {
    form.value.checkedLevel = 'TEAM_LEVEL'
  }
  if ('TEAM_LEVEL' == val) {
    form.value.checkedLevel = 'PERSONNEL_LEVEL'
  }
  getCheckItem(val)
}

function getCheckItem(level) {
  getCheckProjectItemList(level).then(response => {
    let res = response.data
    let disabledList = res.map(item => ({
      ...item,
      disabled: true,
      list: item.list?.map(child => ({
        ...child,
        disabled: true,
        list: child.list?.map(grandChild => ({
          ...grandChild,
          disabled: true,
        }))
      }))
    }))
    checkItemsList.value = formDisabled.value ? disabledList : res;
    checkedCodes.value = res.flatMap(item => item.list?.flatMap(child => child.list?.map(grandChild => grandChild.code)) || [])

  })

}


/** 查询检查记录列表 */
function getList() {
  loading.value = true
  listCheckTask(queryParams.value).then(response => {
    checkRecordList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

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

// 表单重置
function reset() {
  form.value = {
    isSelfCheck: 0,
    timeRange: [],
    ruleTypeNum: 1,
    checkProjectItemList: []
  }
  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 = "巡检任务新建"
  getCheckItem()
}

/** 查看详情 */
function handleDetail(row) {
  reset()
  const _id = row.id || ids.value
  getCheckTask(_id).then(response => {
    let res = response.data;

    form.value = {
      ...res,
      timeRange: [res.checkStartTime, res.checkEndTime]
    }
    const list = response.data.checkProjectItemList || [];



    // 根据checkProjectItemList回显el-tree选中状态
    checkedCodes.value = list.map(item => item.projectCode);


    open.value = true
    title.value = "巡检任务详情"
    getCheckItem(res.checkLevel)
  })
}



/** 提交按钮 */
function submitForm() {
  proxy.$refs["checkRecordRef"].validate(valid => {
    if (valid) {
      const selectedItems = []
      const treeElements = document.querySelectorAll('.el-tree')
      treeElements.forEach((tree, index) => {
        const treeInstance = proxy.$refs[`tree_${index}`][0]

        const checkedNodes = treeInstance.getCheckedNodes(true)

        checkedNodes.forEach(node => {
          const path = []

          // 从checkItemsList中查找当前节点及其父节点
          const findNodeAndParents = (items, targetCode) => {
            for (const item of items) {
              if (item.code === targetCode) {
                path.unshift({
                  code: item.code,
                  name: item.name
                })
                return true
              }
              if (item.list && item.list.length > 0) {
                if (findNodeAndParents(item.list, targetCode)) {
                  path.unshift({
                    code: item.code,
                    name: item.name
                  })
                  return true
                }
              }
            }
            return false
          }

          findNodeAndParents(checkItemsList.value, node.code)

          selectedItems.push({
            projectCode: node.code,
            projectName: node.name,
            categoryCodeOne: path[0]?.code || '',
            categoryNameOne: path[0]?.name || '',
            categoryCodeTwo: path[1]?.code || '',
            categoryNameTwo: path[1]?.name || '',
          })
        })
      })

      let res = {
        ...form.value,
        checkStartTime: form.value.timeRange[0],
        checkEndTime: form.value.timeRange[1],
        checkLevelDesc: check_level.value.find(item => item.value == form.value.checkLevel)?.label,
        checkedLevelDesc: check_level.value.find(item => item.value == form.value.checkedLevel)?.label,
        checkCategoryDesc: check_task_category.value.find(item => item.value == form.value.checkCategory)?.label,
        ruleTypeDesc: check_rule_type.value.find(item => item.value == form.value.ruleType)?.label,
        checkProjectItemList: selectedItems
      }
      console.log(res, "res")
      debugger
      addCheckTask(res).then(response => {
        proxy.$modal.msgSuccess("新增成功")
        open.value = false
        getList()
      })
    }
  })
}

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


getList()
</script>

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

.round {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 5px;
}

.color-div {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.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>