<template>
  <div class="app-container p-2">
    <el-row :gutter="20">
      <!-- 基础信息 -->
      <el-col :lg="30" :xs="24" style="">
        <el-form-item>
          <el-button type="primary" icon="ArrowLeft" @click="goBack">返回上一级</el-button>
        </el-form-item>
        <el-row :span="24" :gutter="10">
          <el-col :span="20" label="预案名称">
            <h2 key="planName" style="font-weight: bolder">{{ detailData.planName }}</h2>
          </el-col>
          <el-col :span="1.5">
            <el-button v-has-permi="['system:plan:add']" type="success" plain icon="Edit" @click="planUpdate()"> 编辑 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-has-permi="['system:plan:delete']" type="danger" plain icon="Delete" @click="planDelete()"> 删除预案 </el-button>
          </el-col>
        </el-row>
        <plan :id="dialog0.id" v-model="dialog0.visible" />
        <div class="line" style="background: #e7e7e7; width: auto; height: 0.6px; position: relative"></div>
        <h3>基础信息</h3>
        <div style="white-space: nowrap">
          <el-text :lg="15" class="mx-1">附件</el-text>
          <el-text :lg="15" class="mx-2" type="primary">
            <a v-if="detailData.file_list && detailData.file_list[0]" :href="detailData.file_list[0].file_url">{{
              detailData.file_list[0].file_name_desc
            }}</a>
          </el-text>
        </div>
        <el-card style="margin-top: 10px" shadow="hover">
          <el-descriptions title="">
            <el-descriptions-item key="planId" label="预案编号：">{{ detailData.planId }}</el-descriptions-item>
            <el-descriptions-item key="planType" label="预案类型：">{{ detailData.planType }}</el-descriptions-item>
            <el-descriptions-item key="publish_date" label="发布日期：">{{ detailData.publish_date }}</el-descriptions-item>
            <el-descriptions-item key="organUnit" label="编制单位：">{{ detailData.organUnit }}</el-descriptions-item>
            <el-descriptions-item key="document" label="发文字号：">{{ detailData.document }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
      <!-- 预案内容 -->
      <el-col :lg="30" :xs="24" style="">
        <h3>预案内容</h3>
        <el-card shadow="hover">
          <el-tabs v-model="activeName" type="border-card" class="demo-tabs" @tab-click="handleClick2">
            <el-tab-pane label="总则" name="first">
              <div>
                <el-row>
                  <el-col :span="4">
                    <el-anchor :container="containerRef" direction="vertical" type="default" :offset="30" @click="handleClick1">
                      <el-anchor-link href="#part1" title="编制目的" />
                      <el-anchor-link href="#part2" title="编制依据" />
                      <el-anchor-link href="#part3" title="适用范围" />
                      <el-anchor-link href="#part4" title="工作原则" />
                    </el-anchor>
                  </el-col>
                  <el-col :span="20">
                    <div ref="containerRef" style="height: 300px; overflow-y: auto">
                      <div id="part1" style="height: auto; margin-top: 20px; font-size: 14px">
                        <h3 style="font-weight: 600">1.1 编制目的</h3>
                        <span style="text-indent: 2em"
                          >这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容</span
                        >
                      </div>
                      <div id="part2" style="height: auto; margin-top: 15px; font-size: 14px">
                        <h3 style="font-weight: 600">1.2 编制依据</h3>
                        <span style="text-indent: 28px"
                          >这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容</span
                        >
                      </div>
                      <div id="part3" style="height: auto; margin-top: 15px; font-size: 14px">
                        <h3 style="font-weight: 600">1.3 适用范围</h3>
                        <span style="text-indent: 28px"
                          >这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容</span
                        >
                      </div>
                      <div id="part4" style="height: auto; margin-top: 15px; font-size: 14px">
                        <h3 style="font-weight: 600">1.4 工作原则</h3>
                        <span style="text-indent: 28px"
                          >这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容</span
                        >
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-tab-pane>
            <el-tab-pane label="组织体系" name="second">组织体系</el-tab-pane>
            <el-tab-pane label="运行机制" name="third">运行机制</el-tab-pane>
            <el-tab-pane label="应急保障" name="fourth">应急保障</el-tab-pane>
            <el-tab-pane label="监督管理" name="fifth">监督管理</el-tab-pane>
            <el-tab-pane label="附则" name="sixth">附则</el-tab-pane>
            <el-tab-pane label="附件" name="seventh">附件</el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
      <el-col :lg="30" :xs="24">
        <!-- 培训记录 -->
        <h3>培训记录</h3>
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10">
              <el-col :span="1.5">
                <el-button v-has-permi="['system:user:add']" type="primary" plain icon="Plus" @click="handleAdd()">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-has-permi="['system:user:add']" type="success" plain :disabled="single" icon="Edit" @click="handleUpdate()">
                  修改
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-has-permi="['system:user:delete']" type="danger" plain :disabled="multiple" icon="Delete" @click="handleDelete()">
                  删除
                </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @query-table="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table
            v-loading="loading3"
            :default-sort="{ prop: 'startTime,endTime', order: 'descending' }"
            :data="userList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column v-if="columns[0].visible" key="textId" label="记录编号" align="center" prop="textId" />
            <el-table-column v-if="columns[1].visible" key="theme" label="培训主题" align="center" prop="theme" :show-overflow-tooltip="true" />
            <el-table-column v-if="columns[2].visible" key="unitName" label="培训单位" align="center" prop="unitName" :show-overflow-tooltip="true" />
            <el-table-column v-if="columns[3].visible" key="Content" label="培训内容" align="center" prop="Content" :show-overflow-tooltip="true" />
            <el-table-column v-if="columns[4].visible" key="peopleNum" label="参与人数" align="center" prop="peopleNum" width="120" />
            <el-table-column v-if="columns[4].visible" key="trainingWay" label="培训方式" align="center" prop="trainingWay" width="120" />
            <el-table-column v-if="columns[5].visible" label="开始时间" sortable align="center" prop="startTime" width="160">
              <template #default="scope">
                <span>{{ scope.row.startTime }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="columns[6].visible" label="结束时间" sortable align="center" prop="endTime" width="160">
              <template #default="scope">
                <span>{{ scope.row.endTime }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="columns[7].visible" key="address" label="培训地点" align="center" prop="address" :show-overflow-tooltip="true" />
            <el-table-column fixed="right" label="操作" width="100">
              <template #default="scope">
                <el-tooltip v-if="scope.row.textId !== 1" content="修改" placement="top">
                  <el-button v-hasPermi="['system:role:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip v-if="scope.row.textId !== 1" content="删除" placement="top">
                  <el-button v-hasPermi="['system:role:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total3 > 0"
            v-model:page="queryParams3.page"
            v-model:limit="queryParams3.pageSize"
            :total="total3"
            @pagination="getList3"
          />
        </el-card>
      </el-col>
      <el-col :lg="30" :xs="24">
        <!-- 演练记录 -->
        <h3>演练记录</h3>
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10">
              <el-col :span="1.5">
                <el-button v-has-permi="['system:drill:add']" type="primary" plain icon="Plus" @click="drillAdd()">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-has-permi="['system:drill:add']" type="success" plain :disabled="single" icon="Edit" @click="drillUpdate()">
                  修改
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-has-permi="['system:drill:delete']" type="danger" plain :disabled="multiple" icon="Delete" @click="drillDelete()">
                  删除
                </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" :columns="columns0" :search="true" @query-table="getList"></right-toolbar>
            </el-row>
            <drill :id="dialog3.id" v-model="dialog3.visible" @getlist="getList2" />
          </template>
          <el-table v-loading="loading2" :data="drillList" @selection-change="handleSelectionChangeDrill">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column v-if="columns0[0].visible" key="drillId" label="演练编号" align="center" prop="drillId" />
            <el-table-column
              v-if="columns0[1].visible"
              key="drillName"
              label="演练名称"
              align="center"
              prop="drillName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              v-if="columns0[2].visible"
              key="drillUnit"
              label="演练单位"
              align="center"
              prop="drillUnit"
              :show-overflow-tooltip="true"
            />
            <el-table-column v-if="columns0[3].visible" key="year" label="年度" align="center" prop="year" :show-overflow-tooltip="true" />
            <el-table-column v-if="columns0[4].visible" label="演练时间" align="center" prop="drillTime" width="160">
              <template #default="scope">
                <span>{{ scope.row.year }}</span>
              </template>
            </el-table-column>
            <el-table-column
              v-if="columns0[5].visible"
              key="drillAddress"
              label="演练地点"
              align="center"
              prop="drillAddress"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              v-if="columns0[6].visible"
              key="drillProject"
              label="演练方案"
              align="center"
              prop="drillProject"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              v-if="columns0[7].visible"
              key="drillVideo"
              label="演练视频"
              align="center"
              prop="drillVideo"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              v-if="columns0[8].visible"
              key="drillPicture"
              label="演练图片"
              align="center"
              prop="drillPicture"
              :show-overflow-tooltip="true"
            />
            <el-table-column fixed="right" label="操作" width="100">
              <template #default="scope">
                <el-tooltip v-if="scope.row.drillId !== 1" content="修改" placement="top">
                  <el-button v-hasPermi="['system:drill:edit']" link type="primary" icon="Edit" @click="drillUpdate(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip v-if="scope.row.drillId !== 1" content="删除" placement="top">
                  <el-button v-hasPermi="['system:drill:remove']" link type="primary" icon="Delete" @click="drillDelete(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total2 > 0"
            v-model:page="drillForm.pageNum"
            v-model:limit="drillForm.pageSize"
            :total="total2"
            @pagination="getList2"
          />
        </el-card>
      </el-col>
      <el-col :lg="30" :xs="24">
        <!-- 响应记录 -->
        <h3>响应记录</h3>
        <el-card shadow="hover">
          <el-table v-loading="loading4" @selection-change="handleSelectionChangeResponse">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column v-if="columns1[0].visible" key="eventId" label="事件编号" align="center" prop="eventId" />
            <el-table-column
              v-if="columns1[1].visible"
              key="eventName"
              label="事件名称"
              align="center"
              prop="eventName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              v-if="columns1[2].visible"
              key="eventType"
              label="事件类型"
              align="center"
              prop="eventType"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              v-if="columns1[3].visible"
              key="responseUnit"
              label="响应单位"
              align="center"
              prop="responseUnit"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              v-if="columns1[4].visible"
              key="eventAddress"
              label="事件地点"
              align="center"
              prop="eventAddress"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              v-if="columns1[5].visible"
              key="responseLevel"
              label="响应级别"
              align="center"
              prop="responseLevel"
              :show-overflow-tooltip="true"
            />
            <el-table-column v-if="columns1[6].visible" label="响应开始时间" align="center" prop="responseStartTime" width="160">
              <template #default="scope">
                <span>{{ scope.row.responseStartTime }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="columns1[7].visible" label="响应开始时间" align="center" prop="responseEndTime" width="160">
              <template #default="scope">
                <span>{{ scope.row.responseEndTime }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :total="total"
            @pagination="getListResponse"
          />
        </el-card>
      </el-col>
    </el-row>
    <!-- 添加或修改培训记录配置对话框 -->
    <el-dialog ref="formDialogRef" v-model="dialog.visible" :title="dialog.title" width="600px" append-to-body @close="closeDialog">
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="20">
            <el-form-item label="培训主题" prop="theme">
              <el-input v-model="form.theme" placeholder="请输入培训主题" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="培训单位" prop="unitName">
              <el-input v-model="form.unitName" placeholder="请输入培训单位" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="培训方式" prop="trainingWay">
              <el-select v-model="form.trainingWay" placeholder="请选择培训方式" maxlength="11">
                <el-option label="线上培训" value="1" />
                <el-option label="线下培训" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="参与人数" prop="peopleNum">
              <el-input v-model="form.peopleNum" placeholder="请输入参与人数" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20" class="block">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="form.startTime" :shortcuts="shortcuts" placeholder="请选择开始时间" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20" class="block">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker v-model="form.endTime" :shortcuts="shortcuts" placeholder="请选择开始时间" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="培训地点" prop="address">
              <el-input v-model="form.address" placeholder="请输入培训地点" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="培训内容" prop="Content">
              <el-input v-model="form.Content" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </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 v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <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 ref="formDialogRef" v-model="dialog.visible" :title="dialog.title" width="600px" append-to-body @close="closeDialog">
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="20">
            <el-form-item label="培训主题" prop="theme">
              <el-input v-model="form.theme" placeholder="请输入培训主题" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="培训单位" prop="unitName">
              <el-input v-model="form.unitName" placeholder="请输入培训单位" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="培训方式" prop="trainingWay">
              <el-select v-model="form.trainingWay" placeholder="请选择培训方式" maxlength="11">
                <el-option label="线上培训" value="1" />
                <el-option label="线下培训" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="参与人数" prop="peopleNum">
              <el-input v-model="form.peopleNum" placeholder="请输入参与人数" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20" class="block">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="form.startTime" :shortcuts="shortcuts" placeholder="请选择开始时间" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20" class="block">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker v-model="form.endTime" :shortcuts="shortcuts" placeholder="请选择开始时间" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="培训地点" prop="address">
              <el-input v-model="form.address" placeholder="请输入培训地点" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="培训内容" prop="Content">
              <el-input v-model="form.Content" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </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="User" lang="ts">
import api from '@/api/system/user';
import { UserForm, UserQuery, UserVO, PlanVO, DrillVO, PlanForm } from '@/api/system/user/types';
import { DeptVO } from '@/api/system/dept/types';
import { RoleVO } from '@/api/system/role/types';
import { PostQuery, PostVO } from '@/api/system/post/types';
import { treeselect } from '@/api/system/dept';
import { globalHeaders } from '@/utils/request';
import { to } from 'await-to-js';
import { optionselect } from '@/api/system/post';
import type { TabsPaneContext } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { reactive } from 'vue';
import { getDrillList, getPlanDetail, getResponseDetail, getTrainingList } from "@/api/riskPrevention/planManage";
import drill from './drill.vue';
const router = useRouter();

const goBack = () => {
  router.go(-1);
};

const containerRef = ref<HTMLElement | null>(null);

const handleClick1 = (e: MouseEvent) => {
  e.preventDefault();
};

const activeName = ref('first');
const handleClick2 = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

/***培训记录编辑界面时间选择 */

const shortcuts = [
  {
    text: '今天',
    value: new Date()
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 1);
      return date;
    }
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 7);
      return date;
    }
  }
];
const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable, sys_user_sex } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'sys_user_sex'));
const userList = ref<UserVO[]>();
const loading4 = ref(false);
const loading3 = ref(false);
const total4 = ref(0);
const total3 = ref(0);
const planList = ref<PlanVO[]>();
const drillList = ref<DrillVO[]>();
const loading2 = ref(false);
const total2 = ref(0);
const responseList = ref<ResponseVO[]>();
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const Content = ref('');
const deptOptions = ref<DeptVO[]>([]);
const initPassword = ref<string>('');
const postOptions = ref<PostVO[]>([]);
const roleOptions = ref<RoleVO[]>([]);
/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/system/user/importData'
});
// 培训列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `培训编号`, visible: false, children: [] },
  { key: 1, label: `培训主题`, visible: true, children: [] },
  { key: 2, label: `培训单位`, visible: true, children: [] },
  { key: 3, label: `培训内容`, visible: true, children: [] },
  { key: 4, label: `参与人数`, visible: true, children: [] },
  { key: 5, label: `开始时间`, visible: true, children: [] },
  { key: 6, label: `结束时间`, visible: true, children: [] },
  { key: 7, label: `培训地点`, visible: true, children: [] }
]);

// 演练列显隐信息
const columns0 = ref<FieldOption[]>([
  { key: 0, label: `演练编号`, visible: false, children: [] },
  { key: 1, label: `演练名称`, visible: true, children: [] },
  { key: 2, label: `演练单位`, visible: true, children: [] },
  { key: 3, label: `年度`, visible: true, children: [] },
  { key: 4, label: `演练时间`, visible: true, children: [] },
  { key: 5, label: `演练地点`, visible: true, children: [] },
  { key: 6, label: `演练方案`, visible: true, children: [] },
  { key: 7, label: `演练视频`, visible: true, children: [] },
  { key: 8, label: `演练图片`, visible: true, children: [] }
]);
// 响应列显隐信息
const columns1 = ref<FieldOption[]>([
  { key: 0, label: `事件编号`, visible: false, children: [] },
  { key: 1, label: `事件名称`, visible: true, children: [] },
  { key: 2, label: `事件类型`, visible: true, children: [] },
  { key: 3, label: `响应单位`, visible: true, children: [] },
  { key: 4, label: `事件地点`, visible: true, children: [] },
  { key: 5, label: `响应级别`, visible: true, children: [] },
  { key: 6, label: `响应开始时间`, visible: true, children: [] },
  { key: 7, label: `响应结束时间`, visible: true, children: [] }
]);
const deptTreeRef = ref<ElTreeInstance>();
const queryFormRef = ref<ElFormInstance>();
const userFormRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();
const formDialogRef = ref<ElDialogInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialog0 = reactive<DialogOption>({
  visible: false,
  id: ''
});
const dialog3 = reactive<DialogOption>({
  visible: false,
  id: ''
});

const initFormData: UserForm = {
  textId: undefined,
  theme: '',
  unitName: undefined,
  peopleNum: undefined
};

const initData: PageData<UserForm, UserQuery> = {
  form2: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    theme: '',
    unitName: ''
  },
  rules: {
    theme: [
      { required: true, message: '培训主题不能为空', trigger: 'blur' },
      {
        min: 1,
        max: 20,
        message: '培训主题长度必须介于 1 和 20 之间',
        trigger: 'blur'
      }
    ],
    unitName: [
      { required: true, message: '培训单位不能为空', trigger: 'blur' },
      {
        min: 1,
        max: 20,
        message: '培训主题长度必须介于 1 和 20 之间',
        trigger: 'blur'
      }
    ],
    peopleNum: [
      { required: true, message: '参与人数不能为空', trigger: 'blur' },
      {
        min: 1,
        message: '参与人数长度必须大于1',
        trigger: 'blur'
      }
    ],
    trainingWay: [{ required: true, message: '培训方式不能为空', trigger: 'blur' }],
    address: [
      { required: true, message: '培训地点不能为空', trigger: 'blur' },
      {
        min: 1,
        max: 20,
        message: '培训主题长度必须介于 1 和 20 之间',
        trigger: 'blur'
      }
    ],
    Content: [
      { required: true, message: '培训内容不能为空', trigger: 'blur' },
      {
        min: 1,
        message: '参与人数长度必须大于1',
        trigger: 'blur'
      }
    ],
    startTime: [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
    endTime: [{ required: true, message: '结束时间不能为空', trigger: 'change' }]
  }
};
const data = reactive<PageData<UserForm, UserQuery>>(initData);

const { queryParams, form2, rules } = toRefs<PageData<UserForm, UserQuery>>(data);
const drillForm = reactive({
  page: 1,
  pageSize: 10,
  planNum: ''
});
const queryParams3 = reactive({
  page: 1,
  pageSize: 10,
  planNum: ''
});
const responseParams = reactive({
  page: 1,
  pageSize: 10,
  planNum: ''
});

const form = reactive<DrillVO>({
  drillId: '',
  drillName: '',
  drillUnit: '',
  year: '',
  drillTime: '',
  drillAddress: '',
  drillProject: '',
  drillVideo: '',
  drillPicture: ''
});

/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选培训内容树 */
watchEffect(
  () => {
    deptTreeRef.value?.filter(Content.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 查询培训内容下拉树结构 */
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};

/** 查询培训列表 */
const getList = async () => {
  loading.value = true;
  const res = await api.listUser(proxy?.addDateRange(queryParams.value, dateRange.value));
  loading.value = false;
  userList.value = res.rows;
  total.value = res.total;
};
/** 查询演练列表 */
const getList2 = async () => {
  loading2.value = true;
  const res = await getDrillList(drillForm);
  loading2.value = false;
  res.data.forEach((item) => {
    item.drillPicture = item.drillPicture[0].file_name_desc;
    item.drillVideo = item.drillVideo[0].file_name_desc;
  });
  drillList.value = res.data;
  total2.value = res.total;
};
/** 查询培训列表 */
const getList3 = async () => {
  loading3.value = true;
  const res = await getTrainingList(queryParams3);
  loading3.value = false;
  // res.data.forEach(item => {
  //   item.drillPicture = item.drillPicture[0].file_name_desc
  //   item.drillVideo = item.drillVideo[0].file_name_desc
  // })
  userList.value = res.data;
  total3.value = res.total;
};
/** 查询响应列表 */
/**const getListResponse = async () => {
  loading4.value = true;
  const res = await api.listResponse(proxy?.addDateRange(queryParams.value, dateRange.value));
  loading4.value = false;
  responseList.value = res.rows;
  total.value = res.total;
};*/
const getListResponse = async () => {
  loading4.value = true;
  const res = await getResponseDetail(responseParams);
  loading4.value = false;
  // res.data.forEach(item => {
  //   item.drillPicture = item.drillPicture[0].file_name_desc
  //   item.drillVideo = item.drillVideo[0].file_name_desc
  // })
  responseList.value = res.data;
  total4.value = res.total;
};
/** 删除按钮操作 */
const handleDelete = async (row?: UserVO) => {
  const textIds = row?.textId || ids.value;
  const [err] = await to(proxy?.$modal.confirm('是否确认删除记录编号为"' + textIds + '"的数据项？') as any);
  if (!err) {
    await api.delUser(textIds);
    await getList();
    proxy?.$modal.msgSuccess('删除成功');
  }
};

/** 选择条数  */
const handleSelectionChange = (selection: UserVO[]) => {
  ids.value = selection.map((item) => item.textId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
const handleSelectionChangeDrill = (selection: DrillVO[]) => {
  ids.value = selection.map((item) => item.drillId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
const handleSelectionChangeResponse = (selection: ResponseVO[]) => {
  ids.value = selection.map((item) => item.eventId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '用户导入';
  upload.open = true;
};
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/user/export',
    {
      ...queryParams.value
    },
    `user_${new Date().getTime()}.xlsx`
  );
};
/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

/** 初始化培训内容数据 */
const initTreeData = async () => {
  // 判断培训内容的数据是否存在，存在不获取，不存在则获取
  if (deptOptions.value === undefined) {
    const { data } = await treeselect();
    deptOptions.value = data;
  }
};

/** 重置操作表单 */
const reset = () => {
  form.value = { ...initFormData };
  userFormRef.value?.resetFields();
};
/** 取消按钮 */
const cancel = () => {
  dialog.visible = false;
  reset();
};

/** 修改按钮操作 */
const handleUpdate = async (row?: UserForm) => {
  reset();
  //const textId = row?.textId || ids.value[0];
  //const { data } = await api.getUser(textId);
  dialog.visible = true;
  dialog.title = '修改培训记录';
  await initTreeData();
  Object.assign(form.value, data.user);
};

/** 提交培训按钮 */
const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.textId ? await api.updateUser(form.value) : await api.addUser(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/**
 * 关闭培训弹窗
 */
const closeDialog = () => {
  dialog.visible = false;
  resetForm();
};

/**
 * 重置表单
 */
const resetForm = () => {
  userFormRef.value?.resetFields();
  userFormRef.value?.clearValidate();
  form.value.textId = undefined;
};
/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  //const { data } = await api.getUser();
  dialog.visible = true;
  dialog.title = '新增培训记录';
};
let detailData = ref({
  file_list: []
});
onMounted(() => {
  const planId = route.query.planId;
  drillForm.planNum = planId;
  queryParams3.planNum = planId;
  getPlanDetail(planId).then((res) => {
    detailData.value = res.data;
  });
  getTreeSelect(); // 初始化培训内容数据
  getList(); // 初始化列表数据
  getList2(); // 初始化列表数据
  getList3(); // 初始化列表数据
  proxy?.getConfigKey('sys.user.initPassword').then((response) => {
    initPassword.value = response.data;
  });
});

async function handleDeptChange(value: number | string) {
  const response = await optionselect(value);
  postOptions.value = response.data;
}

/** 新增预案按钮操作
const planAdd = () => {
  dialog0.visible = true;
  dialog0.id = '';
};*/
/** 修改预案按钮操作 */
const planUpdate = (row) => {
  dialog1.visible = true;
  dialog0.id = row.planId;
};
/** 删除预案按钮操作 */
const planDelete = async (row?: PlanVO) => {
  const planIds = row?.planId || ids.value;
  const [err] = await to(proxy?.$modal.confirm('是否确认删除记录编号为"' + planIds + '"的数据项？') as any);
  if (!err) {
    await api.delPlan(planIds);
    await getListResponse();
    proxy?.$modal.msgSuccess('删除成功');
  }
};

/** 新增演练按钮操作 */
const drillAdd = () => {
  dialog3.visible = true;
  dialog3.id = '';
};
/** 修改演练按钮操作 */
const drillUpdate = (row) => {
  dialog3.visible = true;
  dialog3.id = row.drillId;
};
/** 删除演练按钮操作 */
const drillDelete = async (row?: DrillVO) => {
  const drillIds = row?.drillId || ids.value;
  const [err] = await to(proxy?.$modal.confirm('是否确认删除记录编号为"' + drillIds + '"的数据项？') as any);
  if (!err) {
    await api.delPlan(drillIds);
    await getList();
    proxy?.$modal.msgSuccess('删除成功');
  }
};
</script>

<style lang="scss" scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
