<!-- 评估管理-创建评估页面 -->
<template>
  <div class="researchadd">
    <div class="header">
      <span class="title">创建评估</span>
      <router-link to="/researchmanage" class="goback">
        <span class="return"></span>
        <router-link class="returntext" to="/researchmanage">
          返回
        </router-link>
      </router-link>
    </div>
    <div class="addtype">
      <div class="addtypen">创建评估类型</div>
      <div class="types" @click="handleTypes(1)">单选题</div>
      <div class="types" @click="handleTypes(2)">多选题</div>
      <div class="types" @click="handleTypes(3)">问答题</div>
      <div class="types" @click="handleTypes(4)">评分题</div>
    </div>
    <div
      v-for="(item, index) in allFormsData"
      :key="index + new Date().getTime()"
    >
      <ResearchAddSingle
        v-if="item.type === 1"
        :item="item"
        :assessmentId="assessmentId"
        @del="handleDel"
      />
      <ResearchAddMulti
        v-if="item.type === 2"
        :item="item"
        :assessmentId="assessmentId"
        @del="handleDel"
      />
      <ResearchAddAsk
        v-if="item.type === 3"
        :item="item"
        :assessmentId="assessmentId"
        @del="handleDel"
      />
      <ResearchAddPin
        v-if="item.type === 4"
        :item="item"
        :assessmentId="assessmentId"
        @del="handleDel"
      />
    </div>
    <!-- <div class="opinion name2">
      <div class="namebox">
        <div class="inname" style="margin-top: 13px">您的其他意见</div>
      </div>
      <div class="in">
        <a-textarea
          v-model:value="valueMore"
          style="height: 110px"
          show-count
          :maxlength="200"
        />
      </div>
    </div> -->
    <div class="footer">
      <div class="btn">
        <a-button
          type="primary"
          style="
            width: 100px;
            height: 40px;
            border-radius: 8px;
            background-color: #4ea6ff;
          "
          @click="handleSave"
        >
          保存
        </a-button>
        <a-button
          type="primary"
          ghost
          style="
            width: 100px;
            height: 40px;
            margin-left: 14px;
            border-radius: 8px;
          "
          @click="handleAllCancel"
        >
          取消
        </a-button>
      </div>
    </div>
  </div>
</template>
<script>
import { reactive, toRefs, computed } from "vue";
// import { message } from "ant-design-vue";
// import { createResearch } from "../../api/indexResearch";
import ResearchAddSingle from "./components/ResearchAddSingle.vue";
import ResearchAddMulti from "./components/ResearchAddMulti.vue";
import ResearchAddAsk from "./components/ResearchAddAsk.vue";
import ResearchAddPin from "./components/ResearchAddPin.vue";
import {
  sortBy,
  traverseArr,
  filterCommon,
  deepCloneFilterString,
} from "../../utils/utils";
import {
  queryResearchDetailById,
  editResearchMessage,
  createResearch,
  deleteChoiceQuestion,
  deleteQuestionScAndQa,
} from "@/api/indexResearch";
import { useRouter } from "vue-router";
import store from "@/store";
import { message } from "ant-design-vue";

export default {
  name: "ResearchAdd",
  components: {
    ResearchAddSingle,
    ResearchAddMulti,
    ResearchAddAsk,
    ResearchAddPin,
  },
  setup() {
    const router = useRouter();
    const state = reactive({
      assessmentId: "", //编辑时候传
      assessmentName: "",
      assessmentNameNew: computed(() => store.state.assessmentName),

      allFormsData: [],
      valueMore: "",
    });

    // 详情
    const getInfoDate = async () => {
      let id = router.currentRoute.value.params.id;
      if (id) {
        state.assessmentId = id;
        let res = await queryResearchDetailById({
          assessmentId: state.assessmentId,
        }).then((res) => {
          if (res.data.code === 200) {
            return res.data.data;
          }
        });
        state.assessmentName = res.assessmentName;
        state.valueMore = res.assessmentMark;
        let renderArr = [
          ...res.singleStemVoList,
          ...res.multipleStemVoList,
          ...res.essayQuestionVoList,
          ...res.scoringQuestionVoList,
        ];
        sortBy(renderArr, "orderNumber"); //序号
        state.allFormsData = parseData(renderArr, "questionType"); //类型
      }
    };
    getInfoDate();

    // 转换成前端格式
    const parseData = (arr, typeKey) => {
      const resultArr = [];
      arr.forEach((item) => {
        let key = Number(item[typeKey]);
        let obj = {};
        if (key === 1) {
          let restList = traverseArr(item.assessmentSingleChoiceVoList, {
            inputVal: "singleOptionName",
            imgVal: "singleOptionPictureAddress",
            optionId: "singleOptionId",
          }).map((itm, idx) => {
            itm.id = idx + 1;
            return itm;
          });

          obj = {
            type: key,
            valueSingle: item.singleStemName,
            singleList: restList,
            orderNumber: item.orderNumber,
          };
          resultArr.push(obj);
        }
        if (key === 2) {
          let restList = traverseArr(item.multipleChoiceVoList, {
            inputVal: "multipleOptionName",
            imgVal: "multipleOptionPictureAddress",
            optionId: "multipleOptionId",
          }).map((itm, idx) => {
            itm.id = idx + 1;
            return itm;
          });

          obj = {
            type: key,
            valueMutil: item.multipleStemName,
            mutilList: restList,
            orderNumber: item.orderNumber,
          };
          resultArr.push(obj);
        }
        if (key === 3) {
          obj = {
            type: key,
            valueAsk: item.assessmentQaTitle,
            valueAskDesc: item.assessmentQaDescribe,
            optionId: item.assessmentQaId,
          };
          resultArr.push(obj);
        }
        if (key === 4) {
          obj = {
            type: key,
            valuePin: item.assessmentScTitle,
            minScore: item.assessmentMinScore,
            maxScore: item.assessmentMaxScore,
            pinQuan: item.weightScale,
            optionId: item.assessmentScId,
          };
          resultArr.push(obj);
        }
      });
      resultArr.map((itm, idx) => {
        itm.id = idx + 1;
        return itm;
      });
      return resultArr;
    };
    // 转换成后端格式
    const restData = (arr, typeKey) => {
      const resultArr = [];
      arr.forEach((item) => {
        let obj = {};
        if (item[typeKey] === 1) {
          let restList = traverseArr(item.singleList, {
            singleOptionName: "inputVal",
            singleOptionPictureAddress: "imgVal",
            singleOptionId: "optionId",
          }).map((itm, idx) => {
            itm.optionOrderNum = idx + 1;
            return itm;
          });
          restList.forEach((item) => {
            item.singleOptionId = item.singleOptionId
              ? item.singleOptionId
              : "";
          });

          obj = {
            questionType: item[typeKey],
            singleStemName: item.valueSingle,
            singleList: restList,
            orderNumber: item.orderNumber,
          };
          resultArr.push(obj);
        }
        if (item[typeKey] === 2) {
          let restList = traverseArr(item.mutilList, {
            multipleOptionName: "inputVal",
            multipleOptionPictureAddress: "imgVal",
            multipleOptionId: "optionId",
          }).map((itm, idx) => {
            itm.optionOrderNum = idx + 1;
            return itm;
          });
          restList.forEach((item) => {
            item.multipleOptionId = item.multipleOptionId
              ? item.multipleOptionId
              : "";
          });

          obj = {
            questionType: item[typeKey],
            multipleStemName: item.valueMutil,
            mutilList: restList,
            orderNumber: item.orderNumber,
          };
          resultArr.push(obj);
        }
        if (item[typeKey] === 3) {
          obj = {
            questionType: item[typeKey],
            assessmentQaTitle: item.valueAsk,
            assessmentQaDescribe: item.valueAskDesc,
            assessmentQaId: item.optionId ? item.optionId : "",
          };
          resultArr.push(obj);
        }
        if (item[typeKey] === 4) {
          obj = {
            questionType: item[typeKey],
            assessmentScTitle: item.valuePin,
            assessmentMinScore: item.minScore,
            assessmentMaxScore: item.maxScore,
            weightScale: item.pinQuan,
            assessmentScId: item.optionId ? item.optionId : "",
          };
          resultArr.push(obj);
        }
      });
      resultArr.map((itm, idx) => {
        itm.orderNumber = idx + 1;
        return itm;
      });
      return resultArr;
    };
    // 解散传值
    const parseItem = (arr) => {
      const filterComObj = filterCommon(arr, "questionType");
      let resultObj = {};
      for (let key in filterComObj) {
        if (key === "1") {
          let arrSingle = filterComObj[key];
          let arr = [];
          arrSingle.forEach((item) => {
            if (item.singleList.length) {
              item.singleList.forEach((itm) => {
                arr.push({
                  ...itm,
                  singleStemName: item.singleStemName,
                  orderNumber: item.orderNumber,
                  questionType: item.questionType,
                });
              });
            }
          });
          resultObj.assessmentSingleChoiceDtoList = arr;
        }
        if (key === "2") {
          let arrMulti = filterComObj[key];
          let arr = [];
          arrMulti.forEach((item) => {
            if (item.mutilList.length) {
              item.mutilList.forEach((itm) => {
                arr.push({
                  ...itm,
                  multipleStemName: item.multipleStemName,
                  orderNumber: item.orderNumber,
                  questionType: item.questionType,
                });
              });
            }
          });
          resultObj.assessmentMultipleChoiceDtoList = arr;
        }
        if (key === "3") {
          resultObj.assessmentEssayQuestionDtoList = filterComObj[key];
        }
        if (key === "4") {
          resultObj.assessmentScoringQuestionDtoList = filterComObj[key];
        }
      }
      return resultObj;
    };
    const creatFromData = (type) => {
      let obj = {};
      switch (type) {
        case 1:
          obj = {
            type,
            id: state.allFormsData.length + 1,
            valueSingle: "",
            singleList: [
              {
                id: 1,
                inputVal: "",
                imgVal: "",
              },
            ],
          };
          break;
        case 2:
          obj = {
            type,
            id: state.allFormsData.length + 1,
            valueMutil: "",
            mutilList: [
              {
                id: 1,
                inputVal: "",
                imgVal: "",
              },
            ],
          };
          break;
        case 3:
          obj = {
            type,
            id: state.allFormsData.length + 1,
            valueAsk: "",
            valueAskDesc: "",
          };
          break;
        case 4:
          obj = {
            type,
            id: state.allFormsData.length + 1,
            valuePin: "",
            minScore: 1,
            maxScore: 10,
            pinQuan: 100,
          };
          break;
      }
      return obj;
    };

    const handleTypes = (type) => {
      state.allFormsData.push(creatFromData(type));
    };

    const handleDel = ({ id, type, curItem }) => {
      // 接口删除
      if (state.assessmentId && (curItem.orderNumber || curItem.optionId)) {
        if (type === 1) {
          deleteChoiceQuestion({
            assessmentId: state.assessmentId,
            questionType: "1",
            orderNumber: curItem.orderNumber,
          }).then((res) => {
            if (res.data.code === 200) {
              virtualDel(id);
            }
          });
        }
        if (type === 2) {
          deleteChoiceQuestion({
            assessmentId: state.assessmentId,
            questionType: "2",
            orderNumber: curItem.orderNumber,
          }).then((res) => {
            if (res.data.code === 200) {
              virtualDel(id);
            }
          });
        }
        if (type === 3) {
          deleteQuestionScAndQa({
            assessmentId: state.assessmentId,
            questionType: "3",
            optionId: curItem.optionId,
          }).then((res) => {
            if (res.data.code === 200) {
              virtualDel(id);
            }
          });
        }
        if (type === 4) {
          deleteQuestionScAndQa({
            assessmentId: state.assessmentId,
            questionType: "4",
            optionId: curItem.optionId,
          }).then((res) => {
            if (res.data.code === 200) {
              virtualDel(id);
            }
          });
        }
      } else {
        virtualDel(id);
      }
    };
    const virtualDel = (id) => {
      // 前端删除
      state.allFormsData.forEach((item, index) => {
        if (item.id === id) {
          state.allFormsData.splice(index, 1);
        }
      });
      state.allFormsData.map((item, index) => {
        item.id = index + 1;
        return item;
      });
    };

    const handleSave = () => {
      let resultPost = {};
      let filterData = parseItem(restData(state.allFormsData, "type"));
      // 校验
      if (!checkVal(filterData)) {
        return false;
      }

      if (state.assessmentId) {
        resultPost = {
          assessmentId: state.assessmentId,
          assessmentName: state.assessmentName,
          assessmentMark: state.valueMore,
          ...filterData,
        };
        resultPost = deepCloneFilterString(resultPost, [
          "assessmentMaxScore",
          "assessmentMinScore",
        ]);
        editResearchMessage(resultPost).then((res) => {
          if (res.data.code === 200) {
            message.success("编辑成功");
            router.push({
              path: "/researchmanage",
            });
          }
        });
      } else {
        resultPost = {
          assessmentName: state.assessmentNameNew,
          assessmentMark: state.valueMore,
          ...filterData,
        };
        resultPost = deepCloneFilterString(resultPost, [
          "assessmentMaxScore",
          "assessmentMinScore",
        ]);
        createResearch(resultPost).then((res) => {
          if (res.data.code === 200) {
            message.success("创建成功");
            router.push({
              path: "/researchmanage",
            });
          }
        });
      }
    };
    const handleAllCancel = () => {
      state.allFormsData = [];
      router.push({
        path: "/researchmanage",
      });
    };
    const checkVal = (filterData) => {
      // 问答
      if (
        filterData.assessmentEssayQuestionDtoList &&
        filterData.assessmentEssayQuestionDtoList.length
      ) {
        let arr = filterData.assessmentEssayQuestionDtoList;
        for (let item of arr) {
          if (!item.assessmentQaTitle) {
            message.error("问答题干为必填 请确认");
            return false;
          }
        }
      }
      // 多选
      if (
        filterData.assessmentMultipleChoiceDtoList &&
        filterData.assessmentMultipleChoiceDtoList.length
      ) {
        let arr = filterData.assessmentMultipleChoiceDtoList;
        for (let item of arr) {
          if (!item.multipleStemName) {
            message.error("多选题干为必填 请确认");
            return false;
          }
        }
      }
      // 评分
      if (
        filterData.assessmentScoringQuestionDtoList &&
        filterData.assessmentScoringQuestionDtoList.length
      ) {
        let CountNum = 0;
        let CountArr = filterData.assessmentScoringQuestionDtoList;
        for (let item of CountArr) {
          if (!item.assessmentScTitle) {
            message.error("评分题干为必填 请确认");
            return false;
          }
          CountNum += Number(item["weightScale"]);
        }
        console.log("CountNum");
        console.log(CountNum);
        if (CountNum !== 100) {
          message.error("当前权重设置是百分制 请重新配置");
          return false;
        }
      }
      // 单选
      if (
        filterData.assessmentSingleChoiceDtoList &&
        filterData.assessmentSingleChoiceDtoList.length
      ) {
        let arr = filterData.assessmentSingleChoiceDtoList;
        for (let item of arr) {
          if (!item.singleStemName) {
            message.error("单选题干为必填 请确认");
            return false;
          }
        }
      }
      return true;
    };

    return {
      ...toRefs(state),
      handleTypes,
      handleSave,
      handleAllCancel,
      handleDel,
    };
  },
};
</script>
<style lang="scss">
.researchadd {
  width: 100%;
  display: flex;
  flex-direction: column;
  .header {
    width: 100%;
    display: flex;
    justify-content: space-between;
    .title {
      color: #000000;
      font-size: 18px;
      //line-height: 36px;
      padding-top: 30px;
      padding-left: 37px;
      //font-weight: 500;
    }
    .goback {
      padding-right: 70px;
      //padding-top: 37px;
      position: relative;
      .return {
        display: inline-block;
        width: 42px;
        height: 42px;
        margin-top: 17px;
        margin-right: 10px;
        background-image: url("../../assets/images/projectadd/return.png");
      }
      .returntext {
        display: inline-block;
        position: absolute;
        top: 27px;
        color: #4ea6ff;
        font-size: 14px;
      }
    }
  }
  .addtype {
    display: flex;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    margin-right: 20px;
    align-items: center;
    margin-left: 41px;
    .addtypen {
      color: #6f6f6f;
      font-size: 14px;
    }
    .types {
      cursor: pointer;
      width: 80px;
      height: 40px;
      color: #4ea6ff;
      border: 1px solid #4ea6ff;
      border-radius: 4px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 20px 10px;
    }
    .typesCur {
      color: #fff;
      background: #4ea6ff;
    }
  }
  .content {
    display: flex;
    flex-direction: column;
    border: 1px solid rgba(0, 0, 0, 0.1);
    width: 70%;
    min-width: 690px;
    margin-left: 38px;
    margin-top: 20px;
    .tagbox {
      display: flex;
      justify-content: space-between;
      .tagname {
        width: 90px;
        height: 32px;
        margin-top: 24px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-left: 134px;
        background: rgba(78, 166, 255, 0.1);
        border-radius: 4px;
        color: rgba(64, 158, 255, 1);
        font-size: 16px;
      }
      .deleteop {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100px;
        height: 40px;
        margin-top: 20px;
        margin-right: 30px;
        border: 1px solid #4ea6ff;
        border-radius: 8px;
        cursor: pointer;
        .del_text {
          color: #4ea6ff;
          font-size: 14px;
          margin-left: 5px;
        }
      }
    }
    .scorebox {
      display: flex;
      align-items: center;
      margin-top: 20px;
      margin-left: 70px;
      .scoretext {
        font-size: 14px;
        color: #56a3f9;
      }
      .number {
        display: flex;
        border: 1px solid #d7e5fd;
        border-radius: 5px;
        margin: 0 10px;
        padding: 5px;
        .btn {
          width: 40px;
          height: 40px;
          border: 1px solid #56a3f9;
          border-radius: 8px;
          display: flex;
          justify-content: center;
          align-items: center;
          margin: 5px;
          font-size: 14px;
          font-weight: 400;
          color: #56a3f9;
          line-height: 24px;
          cursor: pointer;
        }
        .curBtn {
          background: #56a3f9;
          color: #fff;
        }
      }
    }
    .picture {
      width: 100px;
      display: flex;
      flex-direction: column;
      margin-top: 20px;
      margin-left: 133px;
      .pictureimg {
        width: 100px;
        height: 100px;
      }
      .picturename {
        color: #6f6f6f;
        font-size: 14px;
      }
    }
    .options {
      display: flex;
    }
    .delete {
      cursor: pointer;
      margin-top: 32px;
      margin-left: 20px;
      // float: right;
      color: #4ea6ff;
      font-size: 14px;
    }
    .name2 {
      display: flex;
      align-items: flex-start;
    }
    .name {
      width: 60%;
      // background-color: lightcoral;
      display: flex;
      margin-top: 20px;
      //align-items: center;
      //height: 40px;
      // border: 1px solid black;
      .namebox {
        width: 120px;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        flex-shrink: 0;
        .nameimg {
          width: 10px;
          height: 10px;
        }
      }
      .inname {
        color: #6f6f6f;
        font-size: 14px;
        margin-left: 7px;
        font-weight: 700;
      }
      .in {
        margin-left: 14px;
        flex: 1;
        .assess {
          display: flex;
          width: 226px;
          height: 40px;
          border: 1px solid #56a3f9;
          //margin-bottom: 20px;
          .assesstype {
            width: 50%;
            background: #56a3f9;
            color: #ffffff;
            display: flex;
            justify-content: center;
            align-items: center;
          }
          .assesswhole {
            width: 50%;
            background: rgba(86, 163, 249, 0.1);
            font-size: 14px;
            color: #6f6f6f;
            display: flex;
            justify-content: center;
            align-items: center;
          }
          .ratio {
            position: absolute;
            right: 10px;
            top: 8px;
            color: #6f6f6f;
            font-size: 14px;
          }
        }
        .addimg {
          cursor: pointer;
          color: rgba(78, 166, 255, 1);
          font-size: 14px;
        }
        .text {
          color: rgba(109, 117, 132, 1);
          font-size: 14px;
          //line-height: 24px;
        }
        .ant-radio-wrapper {
        }
        .ant-input {
          border-radius: 5px;
          // height: 120%;
          width: 100%;
          height: 35px;
        }
        .ant-select-selector {
          border-radius: 5px;
          // height: 120%;
          width: 100%;
          height: 40px;
        }
      }
      .numberInp {
        width: 200px;
        .ant-input-number {
          width: 200px;
          height: 40px;
          border-radius: 8px;
        }
        // .ant-input-number-input-wrap {
        //   width: 200px;
        // }
      }
    }
  }
  .name2 {
    display: flex;
    align-items: flex-start;
  }
  .opinion {
    display: flex;
    margin-top: 30px;
    .namebox {
      width: 120px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      flex-shrink: 0;
    }
    .in {
      margin-left: 14px;
      width: 500px;
      .ant-input-textarea-show-count {
        position: relative;
        height: 110px;
      }
      .ant-input-textarea-show-count::after {
        position: absolute;
        right: 10px;
        bottom: 0px;
      }
      .ant-input {
        border-radius: 8px;
      }
    }
  }
  .footer {
    width: 100%;
    margin-top: 31px;
    margin-bottom: 14px;
    .btn {
      display: flex;
      margin-bottom: 20px;
      justify-content: center;
      cursor: pointer;
    }
  }

  .uploadContent {
    display: block !important;
    .uploadBtn {
      margin-left: 120px !important;
    }
  }
}
</style>
