<template>
  <div class="bigBox" :style="{ height: bigHeight }">
    <MOSTY.FromPage :title="props.editObj.title" @closeDialog="CloseEvent">
      <template #content>
        <MOSTY.Assort :title="'试卷详情'" />
        <div class='fromboxs'>
          <el-form ref="ruleFormRef" class="mosty-from-wrap" label-width="130px" :model="data.newdata" inline="true"
            :rules="rules">
            <el-form-item label="试卷类型:">
              <el-select v-model="data.fromObj.type" style="width: 280px" clearable disabled placeholder="请选择试卷类型：" multiple collapse-tags>
                <el-option v-for="item in D_BZ_KTKYWLX" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="试卷名称:">
              <el-input v-model="data.fromObj.name" clearable disabled style="width: 280px" />
            </el-form-item>
            <el-form-item label="所属部门:">
              <el-input v-model="data.fromObj.deptname" clearable disabled style="width: 280px" />
            </el-form-item>
            <el-form-item label="判断题数量:" prop="pdCount">
              <el-input v-model="data.newdata.pdCount" clearable disabled style="width: 280px" />
            </el-form-item>
            <el-form-item label="单选题数量:" prop="danXCount">
              <el-input v-model="data.newdata.danXCount" clearable disabled style="width: 280px" />
            </el-form-item>
            <el-form-item label="多选题数量:" prop="duoXCount">
              <el-input v-model="data.newdata.duoXCount" clearable disabled style="width: 280px" />
            </el-form-item>
            <el-form-item :label="'判断题（' + pdCount + '题）:'" prop="trueOrFalseQuestions">
              <el-input v-model="data.newdata.trueOrFalseQuestions" @change="chanegePd" type="number" clearable
                style="width: 280px">
                <template #append>分</template></el-input>
            </el-form-item>

            <el-form-item :label="'单选题（' + danXCount + '题）:'" prop="singleChoice">
              <el-input v-model="data.newdata.singleChoice" @change="chanegeDanX" type="number" clearable
                style="width: 280px">
                <template #append>分</template>
              </el-input>
            </el-form-item>

            <el-form-item :label="'多选题（' + duoXCount + '题）:'" prop="multipleChoice">
              <el-input v-model="data.newdata.multipleChoice" @change="chanegeDuoX" type="number" clearable
                style="width: 280px">
                <template #append>分</template></el-input>
            </el-form-item>
            <el-form-item label="考试总分:" prop="examScore">
              <el-input-number controls-position="right" v-model="data.newdata.examScore" disabled
                style="width: 280px" />
            </el-form-item>
            <el-form-item label="开始时间:" prop="startTime">
              <el-date-picker v-model="data.newdata.startTime" style="width: 280px" type="datetime"
                format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm" />
            </el-form-item>
            <el-form-item label="结束时间:" prop="endTime">
              <el-date-picker v-model="data.newdata.endTime" style="width: 280px" type="datetime"
                format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm" />
            </el-form-item>
            <el-form-item label="考试时长:" prop='examTime'>
              <el-input v-model="data.newdata.examTime" type="number" clearable style="width: 280px">
                <template #append>分钟</template></el-input>
            </el-form-item>
            <el-form-item label="可考试次数：" prop="kcjcs">
              <el-input v-model="data.newdata.kcjcs" type="number" clearable style="width: 280px">
                <template #append>次</template></el-input>
            </el-form-item>
            <el-form-item label="考题是否随机：" prop="sflx">
              <el-select v-model="data.newdata.sflx" clearable style="width: 280px">
                <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否查看错题：" prop="sfckct">
              <el-select v-model="data.newdata.sfckct" clearable style="width: 280px">
                <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="合格分数：" prop="hgfs">
              <el-input v-model="data.newdata.hgfs" type="number" clearable style="width: 280px">
                <template #append>分</template></el-input>
            </el-form-item>
            <!-- 这里暂时都不要 -->
            <!-- <el-form-item label="是否发证:" prop="isCertificate">
                    <el-select v-model="data.newdata.isCertificate" style="width: 280px" clearable
                      placeholder="请选择是否发证：">
                      <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>
                  <el-form-item v-if="data.newdata.isCertificate == '1'" label="证书模板：">
                    <el-input v-model="data.newdata.mbName" clearable style="width: 1090px" disabled></el-input>
                    <el-button style="margin-left: 20px" @click="ChooesDdld('02')">选择</el-button>
                  </el-form-item>
                  <el-form-item v-if="data.newdata.isCertificate == '1'" label="证书模板图片：">
                    <el-image :src="data.newdata.mbImg" fit="scale-down"
                      :preview-src-list="[data.newdata.mbImg]"></el-image>
                  </el-form-item> -->
          </el-form>
        </div>
        <MOSTY.Assort :title="'人员选择'" />
        <div>
          <el-button class="addbtn" type="primary" @click="ChooesDdld('01')">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
        </div>
        <div class="tabbox">
          <el-table :data="userList" border stripe style="width: 100%" :height="tableHeight" :key="keyCount"
            @current-change="handlecheckChange">
            <el-table-column sortable prop="userName" align="center" label="姓名"></el-table-column>
            <el-table-column sortable prop="deptName" align="center" label="部门"></el-table-column>
            <el-table-column sortable align="center" label="操作">
              <template #default="scope">
                <span class="operate" style="color: yellowgreen" @click="delInfo(scope.row)">删除</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template #footer>
        <el-button style="margin-left: 10px" v-loading='loadingshow' type="primary" @click="handleSave(ruleFormRef)">
          <el-icon>
            <Search />
          </el-icon>
          <span>保存</span>
        </el-button>
        <el-button type="primary" @click="CloseEvent">
          <el-icon>
            <Back />
          </el-icon>
          <span>返回</span>
        </el-button>
      </template>
    </MOSTY.FromPage>

    <!-- 选择用户 -->
    <ChooseUser v-model="chooseUserVisible" :Single="false" :data="memberList" :leaderid="leaderid"
      @choosedUsers="getSonValue"></ChooseUser>
    <!-- 选择证书模板 -->
    <!-- <ZslbList v-model="showMb" @changeClose="closeMbData" @listdata="getSonValue" :data="mbData" /> -->
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, reactive, getCurrentInstance } from "vue";
// import ZslbList from "@/views/safety/pxjygl/pxjhcoms/zslbList.vue";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import * as rule from "@/utils/rules.js";
const { proxy } = getCurrentInstance();
const { D_BZ_KTKYWLX, D_BZ_SF } = proxy.$dict("D_BZ_KTKYWLX", "D_BZ_SF");
const ruleFormRef = ref(null);
// 验证
const rules = {
  // type: [{ trigger: "blur", required: true, message: "请选择试卷类型：" }],
  // name: [{ trigger: "blur", required: true, message: "请输入试卷名称" }],
  // deptname: [{ trigger: "blur", required: true, message: "所属部门不能为空" }],
  ctfs: [{ trigger: "blur", required: true, message: "请选择出题方式" }],
  startTime: [{ trigger: "blur", required: true, message: "请选择开始时间" }],
  endTime: [{ trigger: "blur", required: true, message: "请选择结束时间" }],
  isCertificate: [{ trigger: "blur", required: true, message: "请选择是否发证" }],
  sfckct: [{ trigger: "blur", required: true, message: "请选择是否查看错题" }],
  sflx: [{ trigger: "blur", required: true, message: "请选择是考题是否随机" }],
  ...rule.intRule({ validator: true, require: false }, "pdCount"),
  ...rule.intRule({ validator: true, require: false }, "danxCount"),
  ...rule.intRule({ validator: true, require: false }, "duoxCount"),
  ...rule.intRule({ validator: true, require: true }, "kcjcs"),
  ...rule.intRule({ validator: true, require: true }, "examTime"),
  ...rule.percentageRule({ validator: true, require: true }, "singleChoice"),
  ...rule.percentageRule({ validator: true, require: true }, "trueOrFalseQuestions"),
  ...rule.percentageRule({ validator: true, require: true }, "multipleChoice"),
  ...rule.percentageRule({ validator: true, require: true }, "examScore"),
};
const props = defineProps({
  editObj: {
    type: Object,
    default: () => { }
  },
  title: String,
});
const loadingshow = ref(false)
const activeNames = ref(1);
const emits = defineEmits(["close"]);
const chooseUserVisible = ref(false); //选择领导弹窗
const memberList = ref([]); //成员选择的id回显
const leaderid = ref("");
const zzlx = ref(null);
const duoXCount = ref(0);
const danXCount = ref(0);
const pdCount = ref(0);
const data = reactive({
  fromObj: {},
  newdata: {}
});
const pdAll = ref(0);
const danXAll = ref(0);
const duoXAll = ref(0);
const userList = ref([]);
const showMb = ref(false)
// 模板数据
const mbData = ref(null)
//初始化
onMounted(() => {
  activeNames.value = ["1", "2", "3", "4"];
  // 获取试卷详情信息
  getKsData(props.editObj.id);
  // 获取考题数量
  getTotal(props.editObj.id, props.editObj.qclass);
  // 获取考试详情
  if (props.editObj.paperId) {
    getPaper(props.editObj.paperId)
  } else {
    // 设置默认值
    data.newdata.kcjcs = 3
    data.newdata.sflx = '1'
    data.newdata.sflx = '1'
    data.newdata.sfckct = '1'
    data.newdata.hgfs = '80'
    data.newdata.isCertificate = '2'
  }
});
// 获取模板数据
const closeMbData = (val) => {
  showMb.value = val
}
// 获取考试详情
const getPaper = (paperId) => {
  getApi({}, `/mosty-jcgl/paper/getInfo?id=${paperId}`).then((res) => {
    if (res) {
      data.newdata = res
      duoXAll.value = duoXCount.value * data.newdata.multipleChoice || 0;
      danXAll.value = danXCount.value * data.newdata.singleChoice || 0;
      pdAll.value = pdCount.value * data.newdata.trueOrFalseQuestions || 0;
      // 设置默认值
      data.newdata.danXCount = danXCount.value || 0
      data.newdata.pdCount = pdCount.value || 0
      data.newdata.duoXCount = duoXCount.value || 0
      // 查询证书模板
      // if (res.bbid) {
      //   getApi({}, "/mosty-jcgl/template/getTemplateInfo?id=" + res.bbid).then(async (resp) => {
      //     if (resp) {
      //       data.newdata.mbName = resp.name
      //       let url = await new Promise(async ok => {
      //         await getApi({}, `/mosty-base/minio/file/download/${resp.file}`).then((res) => {
      //           if (res && res.url) {
      //             ok(res.url)
      //           } else {
      //             ok('')
      //           }
      //         })
      //       })
      //       data.newdata.mbImg = url
      //     }
      //   })
      // }
      // 查询已选择的用户信息列表
      postApi({ id: paperId }, "/mosty-jcgl/paper/getExamTypeDetail").then(
        (res) => {
          let data = res.records
          data.forEach(item => {
            memberList.value.push(item.userId)
            userList.value.push({
              id: item.userId,
              userName: item.userName,
              deptName: item.deptName
            })
          })
        }
      );
    }
  });
}
// 修改多选配分
const chanegeDuoX = () => {
  if (Number(data.newdata.multipleChoice) < 0) {
    data.newdata.multipleChoice = 0
  }
  duoXAll.value = duoXCount.value * data.newdata.multipleChoice || 0;
  data.newdata.examScore = duoXAll.value + danXAll.value + pdAll.value;
};
// 修改单选配分
const chanegeDanX = () => {
  if (Number(data.newdata.singleChoice) < 0) {
    data.newdata.singleChoice = 0
  }
  danXAll.value = danXCount.value * data.newdata.singleChoice || 0;
  data.newdata.examScore = duoXAll.value + danXAll.value + pdAll.value;
};
// 修改判断配分
const chanegePd = () => {
  if (Number(data.newdata.trueOrFalseQuestions) < 0) {
    data.newdata.trueOrFalseQuestions = 0
  }
  pdAll.value = pdCount.value * data.newdata.trueOrFalseQuestions || 0;
  data.newdata.examScore = duoXAll.value + danXAll.value + pdAll.value;
};
//获取试卷详情信息
function getKsData(id) {
  if (id) {
    getApi({}, `/mosty-jcgl/exampaper/getExampaperById/${id}`).then((res) => {
      if (res) {
        data.fromObj = res;
        data.fromObj.type = data.fromObj.type ? data.fromObj.type.split(',') : [];
      }
    });
  }
}
// 试卷考题统计
function getTotal(id, qclass) {
  getApi({ id: id, qclass: qclass },
    "/mosty-jcgl/exampaper/getExamPaperCount"
  ).then((res) => {
    if (res) {
      //已选择
      data.newdata.examScore = res.scoreOrExam.examScore;
      data.newdata.examTime = res.scoreOrExam.examTime;
      res.list.forEach((item) => {
        // 判断
        if (item.qtype === "0") {
          pdCount.value = item.count;
          data.newdata.pdCount = item.count;
        }
        // 单选
        if (item.qtype === "1") {
          danXCount.value = item.count;
          data.newdata.danXCount = item.count;
        }
        // 多选
        if (item.qtype === "2") {
          duoXCount.value = item.count;
          data.newdata.duoXCount = item.count;
          // data.newdata.trueOrFalseQuestions = res.scoreOrExam.trueOrFalseQuestions
        }
        data.newdata.pdCount = data.newdata.pdCount || 0
        data.newdata.danXCount = data.newdata.danXCount || 0
        data.newdata.duoXCount = data.newdata.duoXCount || 0
        // 分数赋值 判断题， 单选题， 多选题
        data.newdata.trueOrFalseQuestions = res.scoreOrExam.trueOrFalseQuestions
        data.newdata.singleChoice = res.scoreOrExam.singleChoice
        data.newdata.multipleChoice = res.scoreOrExam.multipleChoice


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

};
//点击用户选择按钮
function ChooesDdld(val) {
  zzlx.value = val;
  leaderid.value = "";
  if (val == "01") {
    memberList.value = userList.value?.map((item) => {
      return item.id;
    });
    chooseUserVisible.value = true
  } else if (val == '02') {
    //选择证书模板
    showMb.value = true
  }
}
// 选择用户
const getSonValue = (value) => {
  if (zzlx.value == "01") {
    memberList.value = value.map((item) => {
      return item.id;
    });
    userList.value = value.map((item) => {
      return {
        id: item.id,
        userName: item.userName,
        deptName: item.deptName
      };
    });
  } else if (zzlx.value == '02') {
    mbData.value = value
    data.newdata.bbid = value.id
    data.newdata.mbImg = value.url
    data.newdata.mbName = value.name
  }
};

//删除表格数据
function delInfo(row) {
  userList.value.forEach((item, index) => {
    if (row.id == item.id) {
      userList.value.splice(index, 1);
    }
  });
}
// 保存
const handleSave = (ruleFormRefs) => {
  ruleFormRefs.validate((valid1) => {
    if (valid1) {
      loadingshow.value = true
      let arr = [];
      userList.value.forEach((el) => {
        arr.push(el.id);
      });
      data.newdata.ids = arr.join(",");
      data.newdata.examId = props.editObj.id
      if (data.newdata) {

        if (props.editObj.type == 'add') {
          postApi(data.newdata, "/mosty-jcgl/paper/setExamPaper").then((res) => {
            ElMessage.success("发布成功");
            emits("close");
            loadingshow.value = false
          }).catch((err) => {
            loadingshow.value = false
          })
        } else if (props.editObj.type == 'edit') {
          postApi(data.newdata, "/mosty-jcgl/paper/updateExamPaper").then((res) => {
            ElMessage.success("修改成功");
            emits("close");
            loadingshow.value = false
          }).catch((err) => {
            loadingshow.value = false
          })
        }
      }
    }
  })
};
</script>

<style lang="scss" scoped>
.fromboxs {
  width: 100%;

  .el-form {
    width: 85%;
    margin: 20px auto;
    display: flex;
    flex-wrap: wrap;

  }
}


.ld_box {
  display: flex;
  margin-right: 20px;
}

.addbtn {
  margin-bottom: 10px;
}

.bigBox {
  display: block !important;
  box-sizing: border-box;
}

.tabbox {
  max-height: 300px;
  overflow-y: scroll;

  .input {
    width: 100%;
    height: 100%;
  }
}

.erweim {
  margin: 0px auto;
  text-align: center;

  >img {
    width: 200px;
    height: 200px;
    display: block;
  }
}

::v-deep .el-table .cell {
  padding: 0 0 !important;
}

::v-deep .el-table--border .el-table__cell .cell {
  padding-left: 0px !important;

  >input {
    width: 100%;
    height: 33px;
  }
}

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

::v-deep .el-dialog__body {
  height: 70vh !important;
}
</style>
