<template>
  <div class="bigBox" :style="{ height: bigHeight }">

    <div class="right">
      <!-- 头部 -->
      <div class="titleBox">
        <div class="title">编辑试卷信息</div>
        <div class="btnBox">

          <el-button type="primary" @click="CloseEvent">
            <el-icon>
              <Back />
            </el-icon>
            <span>返回</span>
          </el-button>
        </div>
      </div>
      <div class="title-box" ref="searchBox">
        <div>试卷名称：{{ FromData.name }}
        </div>
      </div>
      <div class="tabBox">
        <div class="box_left">

          <ul class="type_box">
            <li v-for="(item, index) in typelist" :key="item" @click="changClick(index, item)"
              :class="listQuery.qclass == item.qclass ? 'active' : ''">
              <span>{{ item.title }}({{ item.count }})</span>
            </li>
          </ul>
        </div>
        <div class="box_count">
          <div class="count_top">
            <span class="tit">待选择</span>
            <button style="height:25px;" v-for="item in qtypelisy" :key="item" @click="changtext(item)"
              :class="listQuery.qtype == item.qtype ? 'activebtn' : ''">{{ item.title }}({{ item.count }})
            </button>

            <el-button @click="addgl">添加选择项</el-button>
          </div>
          <div class="count_top">
            <span>筛选条件：{{ searchObj ? searchObj.toString() : '' }}</span>
            <div style="display: flex;align-items: center;">
              <span>难易程度：</span>
              <div style="width: 250px;">
                <MOSTY.DictRidioAndSelect :dictData="D_BZ_KTKNYCD" v-model="FromData.nycd" selectType="radio"
                  :disabled="false" @onChange='getlable' />
              </div>
            </div>

          </div>
          <div style="display:flex; padding: 0 5px;">
            <div class="title_box" style="margin-right:5px;">试卷类型：
              <el-select class="pxdx_boxs" style="border:none;background:none;width:166px;" v-model="FromData.type"
                clearable disabled multiple collapse-tags>
                <el-option v-for="item in props.zdlist.D_TB_YWLX" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </div>
            <div class="title_box">出题类型：
              <el-select class="pxdx_boxs" style="border:none;background:none;width:140px;" v-model="ruleForm.ctfs"
                clearable disabled>
                <el-option v-for="item in props.zdlist.D_BZ_PXSSCTFS" :key="item" :label="item.label"
                  :value="item.value" />
              </el-select>
            </div>
            <!-- 修改字段 -->
            <div class="title_box" style='margin-left:20px;'>是否随机：
              <el-select class="pxdx_boxs" style="border:none;background:none;width:60px;" v-model="ruleForm.sfsj"
                clearable disabled>
                <el-option v-for="item in props.zdlist.D_BZ_SF" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </div>

          <div class="table_bo">
            <el-table ref="multipleTableRef" :data="wgltableData" v-loading="tableloading"
              element-loading-text="数据加载中..." height="51vh" style="width: 100%;"
              @selection-change="handleSelectionChange" border>
              <el-table-column type="selection" width="55" />
              <el-table-column label="题目" property="questionname">
              </el-table-column>
            </el-table>
            <div class="fenyes">
              <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="listQuery.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.pageSize"
                layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
              <el-button @click="toggleSelection()">清空</el-button>
            </div>

          </div>
        </div>
        <div class="box_count">
          <div class="count_top">
            <span class="tit">已选择</span>

            <el-button @click="delxzx">删除选择项</el-button>
          </div>
          <div class="count_tops">
            <span>已选题:{{ ygltableData.length }}</span>
            <span v-for="item in yxtype" :key="item">{{ item.title }}:{{ item.count }}</span>
          </div>
          <div class="count_top">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="79px" :="true"
              :disabled="!saveBtnShow" style="display: flex;justify-content:space-between;" :inline="true">
              <el-form-item label="判断题：" prop="pdtl">
                <el-input v-model.number="ruleForm.pdtl" type='number' style="width: 77px">
                </el-input>题
              </el-form-item>
              <el-form-item label="单选题：" prop="danxtl">
                <el-input v-model.number="ruleForm.danxtl" type='number' style="width: 77px">
                </el-input>题
              </el-form-item>
              <el-form-item label="多选题：" prop="duoxtl">
                <el-input v-model.number="ruleForm.duoxtl" type='number' style="width: 77px">
                </el-input>题
              </el-form-item>

              <!-- <el-button style="height:25px;" @click="savefrom(ruleFormRef)" :loading="loading">保存</el-button> -->
            </el-form>
          </div>
          <div class="table_bo">
            <el-table ref="multipleTableRef2" :data="ygltableData" v-loading="tableloading2"
              element-loading-text="数据加载中..." style="width: 100%" height="53vh"
              @selection-change="handleSelectionChange2" border>
              <el-table-column type="selection" width="55" />
              <el-table-column label="题目" property="questionname">
              </el-table-column>
              <el-table-column label="题目类型" width="120">
                <template #default="{ row }">
                  <dict-tag :options="props.zdlist.D_TB_KTTX" :value="row.qtype" :tag="false" />
                </template>
              </el-table-column>
              <el-table-column label="业务类型" width="120">
                <template #default="{ row }">
                  <div class="flex just-center">
                    <dict-tag v-for="item in row.qclassArr" :options="props.zdlist.D_BZ_KTKYWLX" :value="item" :tag="true" />
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <div class="fenyes">
              <el-pagination class="pagination" @size-change="handleSizeChanges" @current-change="handleCurrentChanges"
                :current-page="listQuerys.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="listQuerys.pageSize"
                layout="total, prev, pager, next, sizes, jumper" :total="totals"></el-pagination>
              <el-button @click="toggleSelection2()">清空</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { onMounted, ref, defineEmits, reactive, defineProps, watch, getCurrentInstance } from "vue";
import { ElTable } from 'element-plus';
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, deleteApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();
const { D_BZ_KTKNYCD } =
  proxy.$dict("D_BZ_KTKNYCD");
const rules = reactive({
  danxtl: [{ required: true, message: "请输入单选数量", trigger: "blur" }],
  duoxtl: [{ required: true, message: "请输入多选数量", trigger: "blur" }],
  pdtl: [{ required: true, message: "请输入判断数量", trigger: "blur" }],
})
const props = defineProps({
  Row: Object,
  zdlist: Object
});
const searchObj = ref(['', '判断题'])
const ruleFormRef = ref(null)
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  qtype: '0',
  nycd: ''
})
const bigHeight = ref()
const listQuerys = ref({
  pageCurrent: 1,
  pageSize: 20,
})
const loading = ref(false)
const totals = ref(0)
const total = ref(0)
const saveBtnShow = ref(false)
const ruleForm = ref({})
const inds = ref()
const emits = defineEmits(["close"]);
const FromData = ref({})
const qtypelisy = ref([
  { title: '判断题', qtype: '0', count: 0 },
  { title: '单选题', qtype: '1', count: 0 },
  { title: '多选题', qtype: '2', count: 0 }

])
const typelist = ref([])
const yxtype = ref([
  { title: '判断题', qtype: '0', count: 0 },
  { title: '单选题', qtype: '1', count: 0 },
  { title: '多选题', qtype: '2', count: 0 }

])
const tableloading = ref(false)
const tableloading2 = ref(false)
const wgltableData = ref([])
const ygltableData = ref([])
const multipleTableRef = ref()
const multipleTableRef2 = ref()
const multipleSelection = ref([])
const multipleSelection2 = ref([])

onMounted(() => {
  if (props.Row.ctfs == '3') {
    saveBtnShow.value = true
  } else {
    saveBtnShow.value = false
  }
  FromData.value.name = props.Row.name;
  FromData.value.type = props.Row.type ? props.Row.type.split(',') : [];
  listQuery.value.qclass = props.Row.type;
  listQuery.value.id = props.Row.id;
  listQuerys.value.id = props.Row.id;

  getwglList();
  getyglList()
  getTotal()
  getLeftList()
})
const setSearch = ()=>{
  if (listQuery.value.qclass && Array.isArray(typelist.value)) {
    typelist.value.forEach(item => {
      if (listQuery.value.qclass == item.qclass) {
        searchObj.value[0] = item.title
      }
    })
  }
}
const getLeftList = () => {
  getApi({}, '/mosty-jcgl/examlib/getQclassStatCount ').then(res => {
    res = Array.isArray(res) ? res : []
    typelist.value = res

    typelist.value = typelist.value.map(item => {
      item.title = item.zdmc
      item.qclass = item.qclass
      item.count = item.count || 0
      return item
    })
    setSearch()
  })
}
//试卷考题统计
function getTotal() {
  getApi({ id: listQuery.value.id, qclass: listQuery.value.qclass }, '/mosty-jcgl/exampaper/getExamPaperCount').then(res => {
    if (res) {
      //待选择
      qtypelisy.value.forEach((item1) => {
        let found = false;
        res.qTypeList.forEach((item2) => {
          if (item1.qtype === item2.qtype) {
            item1.count = item2.count;
            found = true;
          }
        });
        if (!found) {
          item1.count = 0;
        }
      });
      //试卷类型
      // typelist.value[0].count=res.qClassList.xf
      // typelist.value[1].count=res.qClassList.jt
      // typelist.value[2].count=res.qClassList.sc
      // typelist.value[3].count=res.qClassList.sb
      // typelist.value[4].count=res.qClassList.dq
      // typelist.value[5].count=res.qClassList.sp
      // typelist.value[6].count=res.qClassList.za
      // typelist.value[7].count=res.qClassList.tzzy
      // typelist.value[8].count=res.qClassList.tzsb
      // typelist.value[9].count=res.qClassList.zyjk
      // typelist.value[10].count=res.qClassList.hjbh
      // typelist.value[11].count=res.qClassList.yjgl
      // typelist.value[12].count=res.qClassList.qt

      //以选择
      yxtype.value.forEach((item1) => {
        let found2 = false;
        res.list.forEach((item2) => {
          if (item1.qtype === item2.qtype) {
            item1.count = item2.count;
            found2 = true;
          }
        });
        if (!found2) {
          item1.count = 0;
        }
      });
      ruleForm.value = props.Row
      ruleForm.value.pdtl = props.Row.pdtl ? props.Row.pdtl : yxtype.value[0].count;
      ruleForm.value.danxtl = props.Row.danxtl ? props.Row.danxtl : yxtype.value[1].count;
      ruleForm.value.duoxtl = props.Row.duoxtl ? props.Row.duoxtl : yxtype.value[2].count;
      ruleForm.value.sfsj = props.Row.pzlx == '0' ? '1' : '2';

    }
  })
}


//查询试卷未关联的试题
function getwglList() {
  tableloading.value = true
  getApi(listQuery.value, '/mosty-jcgl/exampaper/getExamlibByPaperIdNotExists').then(res => {
    if (res.records) {
      wgltableData.value = res.records;
      total.value = res.total
      tableloading.value = false
    }

  })
}
//	查询试卷已关联的试题
function getyglList() {
  tableloading2.value = true
  getApi(listQuerys.value, '/mosty-jcgl/exampaper/getExamlibByPaperId').then(res => {
    if (res.records) {
      // qclass
      ygltableData.value = [...res.records[0].multipleList, ...res.records[0].singleList, ...res.records[0].trueOrFalseList];
      ygltableData.value = ygltableData.value.map(item=>{
        return {
          ...item,
          qclassArr: item.qclass ? item.qclass.split(',') : []
        }
      })
      totals.value = res.total
      tableloading2.value = false
    }
  })
}
function changClick(val, row) {
  searchObj.value[0] = row.title
  listQuery.value.qclass = row.qclass;
  listQuery.value.pageCurrent = 1
  getTotal()
  getwglList()
}
//选择
function changtext(val) {
  searchObj.value[2] = val.title
  listQuery.value.qtype = val.qtype;
  listQuery.value.pageCurrent = 1
  getwglList()
}
function getlable(val) {
  if (val == '1') {
    searchObj.value[2] = '较难'
  } else if (val == '2') {
    searchObj.value[2] = '一般'
  } else {
    searchObj.value[2] = '简单'
  }
  listQuery.value.nycd = val
  getTotal()
  getwglList()
}
//清空选中项
function toggleSelection() {
  multipleTableRef.value.clearSelection()
}
function toggleSelection2() {
  multipleTableRef2.value.clearSelection()
}
//获取选中项
const handleSelectionChange = (val) => {
  multipleSelection.value = val.map((item) => {
    return item.id
  })
}
const handleSelectionChange2 = (val) => {
  multipleSelection2.value = val.map((item) => {
    return item.id
  })
}
//添加选择项
function addgl() {
  postApi({ id: listQuery.value.id, libList: multipleSelection.value }, '/mosty-jcgl/exampaper/addExamlib').then(res => {
    ElMessage.success("添加成功");
    getwglList();
    getyglList()
    getTotal()
  })
}
//删除选择项
function delxzx() {
  deleteApi({ id: listQuery.value.id, libList: multipleSelection2.value }, '/mosty-jcgl/exampaper/delExamlib').then(res => {
    ElMessage.success("删除成功");
    getwglList();
    getyglList()
    getTotal()
  })
}
const CloseEvent = () => {
  emits("close");
};
const savefrom = async (formEl) => {
  loading.value = true
  if (!formEl) return;
  if (ruleForm.value.danxtl > yxtype.value[1].count || ruleForm.value.duoxtl > yxtype.value[2].count || ruleForm.value.pdtl > yxtype.value[0].count) {
    ElMessage.warning("设置题数不能大于现有题数");
    loading.value = false;
  } else {
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        postApi(ruleForm.value, '/mosty-jcgl/exampaper/edit').then((res) => {
          ElMessage.success('保存成功');
          loading.value = false;
          emits("close");
        })
      }
    })
  }

}
//分页
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getwglList();
};
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  getwglList();
};
//已关联
const handleSizeChanges = (currentSize) => {
  listQuerys.value.pageSize = currentSize;
  getyglList()
};
const handleCurrentChanges = (currentPage) => {
  listQuerys.value.pageCurrent = currentPage;
  getyglList()
};
</script>

<style lang="scss" scoped>
.titleBox {
  height: 41px;

  .title {
    height: 47px;
    line-height: 47px;
  }

  .btnBox {
    margin-top: 4px;
  }
}

.ld_box {
  display: flex;
  margin-right: 30px;

}

.el-form {
  width: 100%;
  align-items: center;
}

.el-form-item {
  display: flex;
  margin-right: 10px;
  margin-bottom: 0px !important;
}

.addbtn {
  margin-bottom: 10px;
}

.bigBox {
  display: block !important;
  padding: 0 14px;
  box-sizing: border-box;
  color: #000;
}

::v-deep .el-upload-list {
  width: 50%;
}


.title-box {
  height: 50px;


  >div {
    width: 100%;
    height: 50px;
    line-height: 50px;
    margin: auto;
    color: #000;
    text-align: center;
    font-size: 18px;
    background-color: #eae7e7;
  }
}

.tabBox {
  display: flex;
  height: 80vh;

  .box_left {
    height: calc(100vh - 237px);
    width: 286px;
    padding: 10px;
    background: #f3f3f3;
    overflow: auto;
    .title_box {
      font-size: 15px;
      font-weight: 600;
      text-align: center;
    }

    .type_box {
      li {
        padding: 8px 0;
        text-align: center;
        border-radius: 2px;
        font-size: 15px;
        background-color: white;
        box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);
        cursor: pointer;
        color: #002060;
        margin: 10px;


      }

      .active {
        background-color: #A8D8DB;
        color: #fff;
        text-shadow: 1px 1px 3px #333;
      }
    }
  }

  .box_count {
    padding: 10px;
    width: 45%;
    border-right: 1px solid #ddd;
    background: #f7f7f7;

    .count_top {
      width: 100%;
      display: flex;
      justify-content: space-between;
      padding: 5px;
      border-bottom: #beb9b9;

      .tit {
        font-size: 16px;
        font-weight: 600;
      }


    }

    .count_tops {
      width: 100%;
      display: flex;
      justify-content: space-between;
      padding: 0px 5px;
      border-bottom: #beb9b9;

      .tit {
        font-size: 16px;
        font-weight: 600;
      }


    }

    .table_bo {
      height: 60vh;

      .el-table--fit {
        position: unset;
      }

      .fenye {
        top: 90%;
      }
    }
  }

}

.activebtn {
  background-color: green;
  color: #fff;
  border: none;
}

::v-deep .el-input__inner {
  background: none;
  color: #0b0b0b;
}

::v-deep .el-select .el-input.is-focus .el-input__inner {
  background: none;
  border: none;
}
</style>
