<template>
  <div class="pageRight">
    <div class="bigBox">
      <div style="overflow: auto;" class="left">
        <h2>考题库类型</h2>
        <section class="list" v-for="(item, index) in leftSelectList" :key="index" @click="handleSelect(item)"
          :class="{ active: selectItem == item.qclass }">{{ item.zdmc }}({{ item.count }})</section>
      </div>
      <div class="right">
        <div class="titleBox">
          <div class="title">考题库列表</div>
          <div class="toggle" :class="{ active: isOpen }" @click="handleTotal">
            <span>统计</span>
            <el-icon>
              <DArrowLeft />
            </el-icon>
          </div>
        </div>
        <div v-show="isOpen" ref="getHeight">
          <MOSTY.Assort title="考题库统计" style="padding: 0;" />
          <section class="flex">
            <section class="left-tj">
              <Sjtj :info="countlist" :isShowTip="false" :isShowBottom="false" :width="236" mb="6px" />
            </section>
          </section>
        </div>
        <el-divider style="margin: 0;" />
        <section class="query-flex">
          <section class="query-section">
            <section class="flex">
              <MOSTY.DictRidioAndSelect :dictData="D_TB_KTTX" style="width: 250px;" v-model="searchobj.qtype"
                placeholder="请选择考题类型" selectType="select" />
            </section>
          </section>
          <section class="query-btn">
            <el-button type="primary" @click="addUserHander">
              <el-icon>
                <Search />
              </el-icon>
              <span>查询</span>
            </el-button>
            <el-button @click="handleRest">
              <el-icon>
                <Refresh />
              </el-icon><span>重置</span></el-button>
          </section>
        </section>
        <el-divider style="margin: 0;" />
        <section class="button">
          <!-- <el-popconfirm v-if="isAqbm" confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定批量上报?"
            @confirm="handleBatchPush()">
            <template #reference>
              <el-button type="primary" :loading="batchReportLoading">
                <el-icon>
                  <Upload />
                </el-icon>
                <span>批量上报</span>
              </el-button>
            </template>
</el-popconfirm> -->
          <el-button type="primary" @click="importKtk" :loading="importLoading">
            <el-icon>
              <Upload />
            </el-icon>
            <span>批量导入</span>
          </el-button>
          <!-- 文件上传小东西 -->
          <input type="file" style="display: none;" @change="changeFile" ref="fileBtn">
          <el-button style="margin-left: 10px;" type="primary" @click="templateDownload">
            <el-icon>
              <Download />
            </el-icon>
            <span>模板下载</span>
          </el-button>
          <el-button type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            <span>新增</span>
          </el-button>
          <el-button type="primary" @click="CloseEvents" v-if='props.RowId'>
            <span>返回</span>
          </el-button>
        </section>
        <section :style="{ 'height': totalHeights }">
          <!-- <div class="eltab9"> -->
          <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :tableloading="tableloading" :isSort="true"
            style="width: 100%;" :isSelect="false" @selectionChange="handleSelectionChange" :selectable="selectable">
            <template #qtype="{ row }">
              <dict-tag :options="D_TB_KTTX" :value="row.qtype" :tag="false" />
            </template>
            <template #qclass="{ row }">
              <dict-tag :options="D_BZ_KTKYWLX" :value="row.qclass" :tag="true" style='display:flex;flex-wrap:wrap;' />
            </template>
            <template #status="{ row }">
              <el-tag v-if="D_BZ_PXZYK_OBJ[row.status]" :type="colorTypeObj[row.status]">{{ D_BZ_PXZYK_OBJ[row.status]
              }}</el-tag>
            </template>
            <template #actions="{ row }">
              <div class="flex just-center just-wrap">
                <!-- <el-popconfirm confirm-button-text="是" v-if="isShowReportBtn(row)" cancel-button-text="否"
                  icon-color="red" title="确定要上报?" @confirm="reportPush(row.id)">
                  <template #reference>
                    <span class="operedit" size="small">
                      <el-icon>
                        <Upload />
                      </el-icon>
                      上报</span>
                  </template>
    </el-popconfirm> -->
                <span v-if="isShowEditBtn(row)" class="operedit" @click="handlexz(row)"><el-icon>
                    <EditPen />
                  </el-icon>修改</span>
                <span class="operesee" @click="handlexq(row)"><el-icon>
                    <EditPen />
                  </el-icon>详情</span>
                <el-popconfirm v-if="isShowDelBtn(row)" confirm-button-text="是" cancel-button-text="否" icon-color="red"
                  title="确定要删除?" @confirm="handledelete(row)">
                  <template #reference>
                    <span class="operdel" size="small"><el-icon>
                        <Delete />
                      </el-icon>删除</span>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </MOSTY.Table>
        </section>
        <div class="fenye">
          <MOSTY.Pages :pageConfiger="searchobj" @changeSize="handleSizeChange" @changeNo="handleCurrentChange" />
        </div>

      </div>
    </div>
    <!-- 新增 -->
    <el-dialog v-model="dialogVisible" :title="title" width="980px" :before-close="CloseEvent">
      <div v-if="dialogVisible">
        <div class="from_box">
          <div class="from_left">
            <div style="height: 175px;overflow-y: hidden;">
              <MOSTY.Upload :width="'100%'" :limit="1" :nopicer="false" :isImg="true" :ShowfileList="false"
                v-model="dialogForm.files" :gsgfList="['jpg', 'png']" :disabled='!showbtn'>
              </MOSTY.Upload>
            </div>

          </div>
          <el-form ref="frombt" :model="dialogForm" :rules="rules" :disabled='!showbtn' label-width="129px">
            <el-form-item label="题型：" prop="qtype">
              <el-select class="pxdx_box" v-model="dialogForm.qtype" clearable style="width: 215px"
                @change="QtypeChange">
                <el-option v-for="item in D_TB_KTTX" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="出题人：">
              <el-input v-model="dialogForm.authorname" disabled style="width: 215px"></el-input>
            </el-form-item>
            <el-form-item label="出题人所在单位：">
              <el-input v-model="dialogForm.authordept" disabled style="width: 215px"></el-input>
            </el-form-item>
            <el-form-item label="难易程度：" prop="nycd">
              <div style="width: 215px">
                <MOSTY.DictRidioAndSelect :dictData="D_BZ_KTKNYCD" v-model="dialogForm.nycd" selectType="radio" />
              </div>
            </el-form-item>

            <!-- 上报备用
            <el-form-item label="仅本级查看：" v-if="isShowBenJBtn(dialogForm, showbtn)" prop="pubpriv">
              <div style="width: 215px">
                <MOSTY.DictRidioAndSelect :dictData="[{ label: '是', value: '01' }, { label: '否', value: '02' }]"
                  v-model="dialogForm.pubpriv" selectType="radio" />
              </div>
            </el-form-item> -->


            <el-form-item label="业务类型：" prop="qclass">
              <div style="width: 603px">
                <MOSTY.DictRidioAndSelect :dictData="D_BZ_KTKYWLX" v-model="dialogForm.qclass" :multiple="true"
                  selectType="select" />
              </div>
            </el-form-item>
            <el-form-item label="适用岗位：" prop="sygw">
              <div style="width: 603px">
                <MOSTY.DictRidioAndSelect :dictData="KHLX" v-model="dialogForm.sygw" :multiple="true"
                  selectType="select" />
              </div>
            </el-form-item>

            <el-form-item label="题目：" prop="questionname">
              <el-input style="width: 603px" class="subject-textarea-box" v-model="dialogForm.questionname" row="10"
                maxlength="200" autosize type="textarea" show-word-limit placeholder="不能超过200个字" />
            </el-form-item>
            <div v-if="dialogForm.qtype == '0'">
              <el-form-item label="正确答案：" prop="answer" style="width: 489px">
                <el-radio-group v-model="dialogForm.answer">
                  <el-radio label="T">A、正确</el-radio>
                  <el-radio label="F">B、错误</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            <div v-else>
              <el-form-item label="A：">
                <el-input v-model="dialogForm.a" style="width: 603px" maxlength="200" placeholder="不能超过50个字" autosize
                  show-word-limit type="textarea" />
              </el-form-item>
              <el-form-item label="B：">
                <el-input v-model="dialogForm.b" style="width: 603px" maxlength="200" placeholder="不能超过50个字" autosize
                  show-word-limit type="textarea" />
              </el-form-item><el-form-item label="C：">
                <el-input v-model="dialogForm.c" style="width: 603px" maxlength="200" placeholder="不能超过50个字" autosize
                  show-word-limit type="textarea" />
              </el-form-item><el-form-item label="D：">
                <el-input v-model="dialogForm.d" style="width: 603px" maxlength="200" placeholder="不能超过50个字" autosize
                  show-word-limit type="textarea" />
              </el-form-item>
              <el-form-item label="正确答案：" prop="answer">
                <el-select v-if="dialogForm.qtype == '2'" class="pxdx_box" v-model="dialogForm.answer" clearable
                  style="width: 215px" multiple>
                  <el-option v-for="item in D_BZ_ABCD" :key="item" :label="item.label" :value="item.value" />
                </el-select>
                <el-select v-if="dialogForm.qtype == '1'" class="pxdx_box" v-model="dialogForm.answer" clearable
                  style="width: 215px">
                  <el-option v-for="item in D_BZ_ABCD" :key="item" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </div>
            <el-form-item label="答案解析：">
              <el-input style="width: 603px" v-model="dialogForm.answerparse" type="textarea" row="10" />
            </el-form-item>
            <!-- <el-form-item v-if="filterqx('isSgs') == 1 || filterqx('isgs') == 1" label="是否公开：" prop="pubpriv"
              style="width: 489px">
              <el-radio-group v-model="dialogForm.pubpriv">
                <el-radio label="2">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item> -->
          </el-form>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="showbtn" type="primary" @click="searchfrom(frombt)" :loading="loading">
            保存
          </el-button>
          <el-button @click="CloseEvent">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <ktkImportTC v-if="isShowKtkImportTC" :resData="importResData" @close="isShowKtkImportTC = false" />
    <ktkAuditTc v-if="isShowKtkAuditTc" :dictObj="{ D_BZ_KTKYWLX }" :resData="auditResData" @close="ktkAuditTcClose" />
  </div>
</template>

<script setup>
// 引入

import { ref, onMounted, reactive, getCurrentInstance, defineProps, watch, nextTick, computed } from "vue";
import { ArrowDown, Download, Upload } from "@element-plus/icons-vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi, deleteApi, uploadfilApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import { getItem } from "@/utils/storage";
import Sjtj from '@/views/dataReportWork/aqjypx/components/sjtj.vue'
import { isString, downloadTemplate } from '@/utils/tools.js';
import ktkImportTC from "./ktkCom/ktkImportTC.vue";
import { filterqx } from "@/utils/auth.js";
import { useRoute, useRouter } from "vue-router";
import { isShowReportButton, getUserLevel } from './reportcom/reportTools.js';
import ktkAuditTc from "./ktkCom/ktkAuditTc.vue";

const { proxy } = getCurrentInstance();
const { D_TB_KTTX, D_BZ_KTKYWLX, D_BZ_ABCD, KHLX, D_BZ_KTKNYCD, D_BZ_PXZYK } = proxy.$dict(
  "D_TB_KTTX",
  "D_BZ_KTKYWLX",
  "D_BZ_ABCD", "KHLX", "D_BZ_KTKNYCD", "D_BZ_PXZYK"
);

const route = useRoute();
const router = useRouter();

const totalHeights = ref(null)
const tableloading = ref(false)
const getHeight = ref(null)
const isOpen = ref(false);
const USERID = getItem("USERID").toString();
/** 是否安全部门 */
const isAqbm = filterqx('isaqbm') == '1'
/** 所属部门id */
const ssdwid = getItem("deptId").ssdwid;
const selectItem = ref('all')
const fileBtn = ref()
const leftSelectList = ref([
])
/** 批量导入 */
const importLoading = ref(false)
/** 批量上报loading */
const batchReportLoading = ref(false)
/** 导入回传的数据, */
const importResData = ref([])
const auditResData = ref([])
/** 上传回传错误弹框 */
const isShowKtkImportTC = ref(false)
/** 审核弹框 */
const isShowKtkAuditTc = ref(false)
const tableColumn = ref([
  {
    title: "题目",
    prop: "questionname",
  },
  {
    title: "出题人",
    prop: "authorname",
  },
  {
    title: "题型",
    prop: "qtype",
    slot: true
  },
  {
    title: "业务类型",
    prop: "qclass",
    slot: true
  },
  // {
  //   title: "上报状态",
  //   prop: "status",
  //   slot: true
  // },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const countlist = ref(
  [
    { title: '判断题', num: 0, dm: '0', icon: 'ccss/icon_03.png' },
    { title: '单选题', num: 0, dm: '1', icon: 'ccss/icon_01.png' },
    { title: '多选题', num: 0, dm: '2', icon: 'ccss/icon_02.png' },
  ]
)
const getscsbsscount = (qclass) => {
  if (!isOpen.value) return // 没展开就不获取数据
  getApi({ qclass }, '/mosty-jcgl/examlib/getStatCount').then(res => {
    if (res) {
      res.forEach((item) => {
        let _item = countlist.value.find(v => v.dm == item.qtype)
        if (_item) {
          _item.num = item.count || 0
        }
      })
    }
  })
}
const isShowBenJBtn = (form) => {
  // 新增 仅省,市有本级选项
  if (!form.id) return filterqx('isSgs') == 1 || filterqx('isgs') == 1;
  if (filterqx('isxgs') == 1) return false; // 县公司没有本级权
  return form.historylevel == form.level // level 没变过才显示
}
const getLeftList = () => {
  getApi({}, '/mosty-jcgl/examlib/getQclassStatCount ').then(res => {
    leftSelectList.value = res.reverse()
    let _item = leftSelectList.value.find(v => v.zdmc == '全部')
    _item.qclass = 'all'
  })
}

const isShowEditBtn = (row) => {
  return row.authorid == USERID
  // 后面先不要
  const status = row.status
  // 01 审核中，03  省审核中 不显示编辑按钮
  if (['01', '03'].includes(status)) return false
  const isNotReported = row.historylevel == row.level // 是未否上报过
  return row.authorid == USERID && isNotReported
}

/** 是否未上报过 */
const isShowDelBtn = (row) => {
  return row.authorid == USERID
  // 后面备用
  /** @type {String} 审核状态 00 未上报，01 审核中，02  市公司审核完成，03  省审核中  04省公司审核完成 */
  const status = row.status
  const level = row?.level // 级别 10 省 20 市 30 县

  // 01 审核中，03  省审核中 不显示删除按钮
  if (['01', '03'].includes(status)) return false
  const isNotReported = row.historylevel == row.level // 是未否上报过
  const ssdwdm = getItem('deptId')?.ssdwdm
  return row.authorid == USERID || (filterqx('isaqbm') == '1' && row.authordeptid == ssdwdm)
}
const handleSelect = (val) => {
  selectItem.value = val.qclass != 'all' ? val.qclass : 'all'
  searchobj.value.qclass = val.qclass != 'all' ? val.qclass : ''
  getTableData()
  getscsbsscount(searchobj.value.qclass)
}
const handleTotal = () => {
  isOpen.value = !isOpen.value
  getscsbsscount(searchobj.value.qclass)
  nextTick(() => {
    if (isOpen.value) {
      totalHeights.value = `calc(100vh - ${364 + getHeight.value.offsetHeight}px)`
      return
    }
    totalHeights.value = `calc(100vh - 364px)`
  })
}
/** 题型切换 清空答案 */
const QtypeChange = () => {
  dialogForm.value.answer = ''
}
// 课件库传过来的参数
const props = defineProps({
  RowId: {
    type: String,
    default: null
  }
});
const fileEdit = ref(true);
const total = ref(0);
const searchobj = ref({
  pageCurrent: 1,
  pageSize: 20,
  total: 0,
  qtype: '',
  qclass: '',
});
const loading = ref(false); //新增保存按钮截流
const frombt = ref();
const title = ref("");
const emits = defineEmits(["close"]);
const dialogVisible = ref(false);
const dialogForm = ref({
  answer: '',
  /** 题型 0判断 1:单选 2:多选 */
  qtype: "0",
  authorname: getItem("USERNAME"),
  authordept: getItem("deptId").sssgsmc ? getItem("deptId").sssgsmc : getItem("deptId").ssdwmc,
  pubpriv: '01', // 默认本级
  // nycd: '1', // : 测试
  // qclass: ['13'], //  测试
  // sygw: '01',
});
//图片

const showbtn = ref(false);
/** 选中的数组 */
const selected = ref([])
// 数据
const tableData = ref([]); //表格数据
/** 是否安全部门 */
const isaqbm = ref(filterqx('isaqbm') == '1')
/** 是否是省公司 */
const isSgs = ref(filterqx('isSgs') == '1')
/** 是否是市公司 */
const isgs = computed(filterqx('isgs') == '1')
//规则校验
const rules = reactive({
  qtype: [{ required: true, message: "题型不能为空", trigger: "blur" }],
  qclass: [{ required: true, message: "业务类型不能为空", trigger: "blur" }],
  questionname: [{ trigger: "blur", required: true, message: "题目不能为空" }],
  nycd: [{ trigger: "blur", required: true, message: "难易程度不能为空" }],
  sygw: [{ trigger: "blur", required: true, message: "适用岗位不能为空" }],
  answer: [{ trigger: "blur", required: true, message: "正确答案不能为空" }]
});
/** 审核对照对象 00 未上报，01 审核中，02  市公司审核完成，03  省审核中  04省公司审核完成 */
const colorTypeObj = {
  '00': '',
  '01': 'danger',
  '02': 'success',
  '03': 'danger',
  '04': 'success',
}
const D_BZ_PXZYK_OBJ = computed(() => {
  let arr = Array.isArray(D_BZ_PXZYK.value) ? D_BZ_PXZYK.value : []
  return arr.reduce((obj, item) => {
    obj[item.value] = item.label
    return obj
  }, {})
})
//查询
function addUserHander() {
  getTableData();
  getLeftList()
}
//重置
const handleRest = () => {
  searchobj.value.pageCurrent = 1;
  searchobj.value.qtype = '';
  selectItem.value = 'all'
  searchobj.value.qclass = ''
  getTableData();
  getLeftList()

}
onMounted(() => {
  getscsbsscount()
  getLeftList()
  nextTick(() => {
    totalHeights.value = `calc(100vh - ${364 + getHeight.value.offsetHeight}px)`
  })
  if (props.RowId) {
    searchobj.value.spmanid = props.RowId
    dialogForm.value.spmanid = props.RowId
  }
  getTableData();
  // 去审核
  if (route.query.id) goToAudit(route.query)
});
//获取查询考题列表
function getTableData() {
  getApi(searchobj.value, "/mosty-jcgl/examlib/getPageList").then((res) => {
    searchobj.value.total = res.total;
    if (res.records) {
      tableData.value = res.records;
      tableData.value.forEach(item => {
        item.qclass = item.qclass.split(',')
      })

    }
  });
}
// 获取文件
const changeFile = () => {
  nextTick(() => {
    let file = fileBtn.value.files[0]
    if (!file) { return; }
    let data = new FormData()
    data.append('file', file);
    importLoading.value = true
    uploadfilApi(data, `/mosty-jcgl/examlib/batchUpload`).then((res) => {
      const arr = Array.isArray(res) ? res : []
      if (arr.length) {
        importResData.value = arr
        isShowKtkImportTC.value = true
      } else {
        if (!arr.length) ElMessage.success("批量上传成功");
      }
      getTableData()
      getLeftList()
      getscsbsscount(searchobj.value.qclass)
    }).finally(() => {
      fileBtn.value.value = ''
      importLoading.value = false
    })
  })
}
function importKtk() {
  nextTick(() => {
    fileBtn.value.click()
  })
}
function templateDownload() {
  downloadTemplate('09', '考题上传模板')
}
//新增
function handleAdd() {
  dialogForm.value = {};
  title.value = "考题新增";
  if (props.RowId) {
    dialogForm.value.spmanid = props.RowId
  }
  dialogForm.value.qtype = "0";
  dialogForm.value.pubpriv = "01"; // 默认本级
  dialogForm.value.nycd = "2"; // 默认难度一般
  dialogForm.value.authorname = getItem("USERNAME");
  dialogForm.value.authordept = getItem("deptId").sssgsmc ? getItem("deptId").sssgsmc : getItem("deptId").ssdwmc;
  showbtn.value = true;
  dialogVisible.value = true; // 展示
  dialogForm.value.files = null

}
const CloseEvent = () => {
  if (showbtn.value) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        frombt.value.clearValidate();
        dialogForm.value = {}
        dialogVisible.value = false
        showbtn.value = false;
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    frombt.value.clearValidate();
    dialogForm.value = {}
    dialogVisible.value = false
    showbtn.value = false;
  }

};
/** 是否显示上报按钮 */
const isShowReportBtn = (row) => {
  return isShowReportButton(row)
}
const selectable = (row) => {
  return isShowReportBtn(row)
}
const handleSelectionChange = (val) => {
  selected.value = val;
};
/** 上报推送 */
const reportPush = (ids, call) => {
  getApi({ ids: ids }, `/mosty-jcgl/examlib/reporting`).then(() => {
    ElMessage.success("上报成功");
    getTableData()
  }).finally(() => {
    if (typeof call === 'function') call()
  })
}

/** 批量上报 */
const handleBatchPush = () => {
  if (!selected.value.length) {
    ElMessage.warning('请先选择数据')
    return
  }
  const ids = selected.value.map(item => item.id).join(',')
  batchReportLoading.value = true
  reportPush(ids, () => {
    batchReportLoading.value = false
  })
}

/**
 * 审核
 * @param isPass 是否不通过 true 通过 false 不通过
 */
const doAudit = (isPass) => {
  loading.value = true
  let params = {
    id: dialogForm.value.id,
    status: !isPass ? '05' : dialogForm.value.status
  }
  postApi(params, `/mosty-jcgl/examlib/examineExaminationInfo`).then(() => {
    ElMessage.success(!isPass ? "审核不通过" : "审核通过");
    getTableData()
    CloseEvent()
  }).finally(() => {
    loading.value = false
  })
}
//修改
function handlexz(row) {
  getktkxq(row.id);
  title.value = "考题信息修改";
  showbtn.value = true;
  dialogVisible.value = true;
}
//详情
function handlexq(row) {
  getktkxq(row.id);
  title.value = "考题信息详情";
  showbtn.value = false;
  dialogVisible.value = true;
}
/** 获取需要的判断题答案(AB 转TF)
 * @param {String} answer 答案
 */
function getNeedPdAnswer(answer) {
  if (answer === 'A') return "T"
  if (answer === 'B') return "F"
  return answer
}
//获取考题库详情
function getktkxq(id) {
  getApi({ id }, "/mosty-jcgl/examlib/getById").then((res) => {
    dialogForm.value = res;
    dialogForm.value.sygw = res.sygw ? res.sygw.split(',') : null;
    dialogForm.value.qclass = res.qclass ? res.qclass.split(',') : null;
    if (!dialogForm.value.id) dialogForm.value.pubpriv = '02' // 之前没有的状态默认为公开
    // 判断题
    if (dialogForm.value.qtype == "0") {
      dialogForm.value.answer = getNeedPdAnswer(dialogForm.value.answer)
    } else if (dialogForm.value.qtype == "2") {
      if (typeof dialogForm.value.answer === 'string' && dialogForm.value.answer.length) {
        dialogForm.value.answer = dialogForm.value.answer.split('')
      } else {
        if (!Array.isArray(dialogForm.value.answer)) {
          dialogForm.value.answer = []
        }
      }
    }
  });
}
//保存
const searchfrom = async (formEl) => {
  if (!formEl) {
    ElMessage.warning("请输入必填项");
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      if (dialogForm.value.qtype == "2") {
        // dialogForm.value.answer = dialogForm.value.answer.toString("");
        dialogForm.value.answer = dialogForm.value.answer.join('');
      }
      dialogForm.value.files = dialogForm.value.files
        ? dialogForm.value.files.toString()
        : null;
      dialogForm.value.sygw = dialogForm.value.sygw ? dialogForm.value.sygw.toString() : '';
      dialogForm.value.qclass = dialogForm.value.qclass ? dialogForm.value.qclass.toString() : '';
      if (dialogForm.value.id) {
        postApi(dialogForm.value, "/mosty-jcgl/examlib/edit").then((res) => {
          ElMessage.success("修改成功");
          getTableData();
          getLeftList()
        }).finally(() => {
          dialogVisible.value = false;
          dialogForm.value.answer = dialogForm.value.answer && isString(dialogForm.value.answer) ? dialogForm.value.answer.split("") : dialogForm.value.answer;
          dialogForm.value.sygw = dialogForm.value.sygw && isString(dialogForm.value.sygw) ? dialogForm.value.sygw.split(',') : dialogForm.value.sygw;
          dialogForm.value.qclass = dialogForm.value.qclass && isString(dialogForm.value.qclass) ? dialogForm.value.qclass.split(',') : dialogForm.value.qclass;
        });
      } else {
        postApi(dialogForm.value, "/mosty-jcgl/examlib/add").then((res) => {
          ElMessage.success("新增成功");
          dialogVisible.value = false;
          getTableData();
          getLeftList();
          getscsbsscount(searchobj.value.qclass)
        }).finally(() => {
          dialogVisible.value = false;
          dialogForm.value.answer = dialogForm.value.answer && isString(dialogForm.value.answer) ? dialogForm.value.answer.split("") : dialogForm.value.answer;
          dialogForm.value.sygw = dialogForm.value.sygw && isString(dialogForm.value.sygw) ? dialogForm.value.sygw.split(',') : dialogForm.value.sygw;
          dialogForm.value.qclass = dialogForm.value.qclass && isString(dialogForm.value.qclass) ? dialogForm.value.qclass.split(',') : dialogForm.value.qclass;
        });
      }
      loading.value = false;
    }
  });

};
//删除数据
const handledelete = (row) => {
  deleteApi(
    { id: row.id, spmanid: row.spmanid },
    `/mosty-jcgl/examlib/del`
  ).then((res) => {
    ElMessage.success("删除成功");
    getTableData();
    getLeftList();
    getscsbsscount(searchobj.value.qclass)
  });
};

//页码发生变化
const handleCurrentChange = (val) => {
  searchobj.value.pageCurrent = val;
  getTableData();
};
//查询条数发生变化
const handleSizeChange = (val) => {
  searchobj.value.pageSize = val;
  getTableData();
};
/** 打开审核详情 */
function goToAudit(query) {
  // getktkxq(query.id);
  auditResData.value = {
    id: query.id,
    rwid: query.rwid
  }
  isShowKtkAuditTc.value = true;
}
const ktkAuditTcClose = () => {
  isShowKtkAuditTc.value = false
  if (route.query.id) router.replace({ path: '/safety/pxzyk/ktk' })//地址还原
  getTableData();
  getLeftList();
  getscsbsscount(searchobj.value.qclass)
}
const CloseEvents = () => {
  emits("close");
};
</script>

<style lang="scss" scoped>
.pageRight {

  background: transparent;
  padding-left: 0;
  padding-right: 0;
}

.btnBox {
  display: flex;
  // width: 300px;
  justify-content: space-between;

  .el-input {
    width: 400px;
    margin-right: 10px;
  }
}

.chartsBox {
  height: 603px;
  display: flex;
  justify-content: space-between;

  div {
    width: 50%;
  }
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.from_box {
  display: flex;
  justify-content: space-between;

  .from_left {
    width: 25%;
  }

  .subject-textarea-box ::v-deep .el-textarea__inner {
    padding-right: 56px;
  }
}

.el-form {
  width: 100%;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding-right: 20px;
}


.toggle {
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #0f3916;

  .el-icon {
    transform: rotate(90deg);
    transition: all 0.25s ease;
  }

  &.active {
    .el-icon {
      transform: rotate(-90deg);
    }
  }
}

.query-flex {
  display: flex;
  justify-content: space-between;

  .query-section {

    width: 68%;
  }

  .query-btn {
    width: 360px;
    display: flex;
    justify-content: end;

    .toggle {
      height: 32px;
      cursor: pointer;
      display: flex;
      align-items: center;
      color: #0f3916;

      .el-icon {
        transform: rotate(90deg);
        transition: all 0.25s ease;
      }

      &.active {
        .el-icon {
          transform: rotate(-90deg);
        }
      }
    }
  }
}

.button {
  display: flex;
  align-items: center;
  justify-content: end;
  margin-bottom: 12px;
}

.flex {
  display: flex;
  align-items: center;

  .left-tj {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: start;
  }
}

.bigBox {
  display: flex;

  .title {
    font-size: 18px;
    color: #0f3916;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .el-icon {
      cursor: pointer;
    }
  }

  .left {
    width: 250px;
    background-color: #fff;
    padding: 10px;
    box-sizing: border-box;
    text-align: center;
    color: #333;

    >h2 {
      font-size: 16px;
      margin: 0;
    }

    .list {
      width: 100%;
      height: 30px;
      border-radius: 6px;
      border: 1px solid #e0e0e0;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      margin-top: 10px;

      &:hover {
        background-color: #f5f5f5;
        color: #333;
      }
    }

    .active {
      background: var(--el-color-primary);
      color: #fff;
    }
  }

  .right {
    padding: 0 10px;
    margin-left: 14px;
    background: #fff;
    width: calc(100% - 250px);

    .headBox {
      display: flex;
      align-items: center;
    }

    .btnBox {
      .el-select {
        width: 150px;
      }

      .header-right {
        display: flex;
        align-items: center;
      }

      .btnBox {
        display: flex;
        width: 547px;
        justify-content: space-between;
        align-items: center;

        .el-icon {
          cursor: pointer;
        }
      }
    }
  }
}
</style>
