<!-- 评估管理-创建评估页面 -->
<template>
  <a-drawer
    :visible="createVoteVisible"
    class="drawerStyle createvoteDrawer"
    width="100%"
    placement="right"
    @after-visible-change="afterVisibleChange"
  >
    <div class="researchadd">
      <div class="header">
        <div class="headerTitle">{{ ballotId ? "编辑投票题干" : "创建投票题干" }}</div>
        <img
          style="width: 29px; height: 29px; cursor: pointer"
          src="../../assets/images/basicinfo/close.png"
          @click="closeDrawer"
        />
      </div>
      <div class="main_left">
        <!-- <div class="main_item">
       
          <div class="signbox">
            <div class="sign">
              <img src="@/assets/images/coursewareManage/asterisk.png" alt="" />
            </div>
            <span style="margin-right: 3px">投票名称：</span>
          </div>
          <div class="btnbox">
            <a-input
              v-model:value="ballotName"
              style="width: 424px; height: 32px"
              placeholder="请输入任务名称"
              maxlength="20"
            />
          </div>
        </div>-->
        <div class="main_item">
          <div class="signbox">
            <div class="sign">
              <img
                src="@/assets/images/coursewareManage/asterisk.png"
                alt="asterisk"
              />
            </div>
            <span>创建题干：</span>
          </div>
          <div class="btnbox">
            <button class="xkbtn" @click="handleTypes">添加题干</button>
          </div>
        </div>
        <!-- 创建投票侧弹窗 -->
      </div>

      <div
        v-for="(item, index) in allFormsData"
        :key="index + new Date().getTime()"
      >
        <VoteQuestion :item="item" @del="handleDel" />
      </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>
  </a-drawer>
</template>
<script>
import { reactive, toRefs, toRef, watch } from "vue";
import { message } from "ant-design-vue";
// import { createResearch } from "../../api/indexResearch";
import VoteQuestion from "./VoteQuestion.vue";

import { sortBy, traverseArr } from "../../utils/utils";

//import store from "@/store";
import * as api from "@/api/indexVote";
//import { useRouter } from "vue-router";
import {} from "@/api/indexResearch";

//import { message } from "ant-design-vue";

export default {
  name: "CreateVote",
  components: {
    VoteQuestion,
  },
  props: {
    createVoteVisible: {
      type: Boolean,
      default: false,
    },
    ballotId: {
      type: Number,
      default: null,
    },
    ballot_name: {
      type: String,
      default: null,
    },
    editChild: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, ctx) {
    const ballotIdWatch = toRef(props, "ballotId");
    const state = reactive({
      ballotId: "",
      ballotName: "",
      allFormsData: [],
    });
    watch(ballotIdWatch, (newValue) => {
      if (!newValue) {
        state.ballotId = "";
        state.ballotName = "";
        state.allFormsData = [];
      }
    });

    // const router = useRouter();
    const afterVisibleChange = () => {
      if (props.ballotId) {
        getInfoDate();
      } else {
        handleTypes();
      }
    };
    const closeDrawer = () => {
      handleAllCancel();
      ctx.emit("update:createVoteVisible", false);
      ctx.emit("update:ballotId", state.ballotId);
      ctx.emit("update:ballot_name", state.ballotName);
    };
    // 详情
    const getInfoDate = async () => {
      console.log("props.editChild=====", props.editChild);
      if (props.ballotId) {
        console.log("props.editChild2=====", props.editChild);
        let res = await api.queryStemByStemId(props.ballotId).then((res) => {
          if (res.data.code === 200) {
            return res.data.data;
          }
        });
        state.ballotId = res.ballotId;
        state.ballotName = res.ballotName;
        let renderArr = [...res.voteStemVoList];
        sortBy(renderArr, "orderNumber"); //序号
        state.allFormsData = parseData(renderArr);
      }
    };

    // 转换成前端格式
    const parseData = (arr) => {
      const resultArr = [];

      console.log("arr.voteStemVoList=====", arr);
      arr.forEach((item) => {
        let obj = {};
        let restList = traverseArr(item.optionDetailList, {
          inputVal: "optionName",
          imgVal: "optionPictureAddress",
          optionId: "optionId",
          voteStemId: "voteStemId",
          stem: "stem",
        }).map((itm, idx) => {
          itm.id = idx + 1;
          return itm;
        });

        obj = {
          valueSingle: item.voteStemName,
          optionDetailList: restList,
          orderNumber: item.orderNumber,
          voteStemId: item.voteStemId,
        };
        resultArr.push(obj);
      });
      resultArr.map((itm, idx) => {
        itm.id = idx + 1;
        return itm;
      });
      return resultArr;
    };

    // 转换成后端格式
    const restData = (arr) => {
      const resultArr = [];
      arr.forEach((item) => {
        let obj = {};
        console.log("item=======", item);
        let restList = traverseArr(item.optionDetailList, {
          optionName: "inputVal",
          optionPictureAddress: "imgVal",
          optionId: "optionId",
          voteStemId: "voteStemId",
          stem: "stem",
        }).map((itm, idx) => {
          itm.optionOrderNum = idx + 1;
          return itm;
        });
        restList.forEach((item) => {
          item.optionId = item.optionId ? item.optionId : "";
        });

        obj = {
          voteStemName: item.valueSingle,
          optionDetailList: restList,
          orderNumber: item.orderNumber,
          voteStemId: item.voteStemId,
        };
        resultArr.push(obj);
        console.log("resultArr=======", resultArr);
      });
      resultArr.map((itm, idx) => {
        itm.orderNumber = idx + 1;
        return itm;
      });
      return resultArr;
    };

    const handleTypes = () => {
      let obj = {
        id: state.allFormsData.length + 1,
        valueSingle: "",
        optionDetailList: [
          {
            id: 1,
            inputVal: "",
            imgVal: "",
          },
          {
            id: 2,
            inputVal: "",
            imgVal: "",
          },
        ],
      };
      state.allFormsData.push(obj);
    };

    const handleDel = ({ id, curItem }) => {
      if (state.allFormsData.length > 1) {
        // 接口删除
        if (curItem.voteStemId) {
          api.deleteVoteStem(curItem.voteStemId).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 = restData(state.allFormsData);
      console.log("555555555555555555", filterData);

      // 校验

      if (!checkVal(filterData)) {
        return false;
      }

      if (state.ballotId) {
        resultPost = {
          ballotId: state.ballotId,
          ballotName: state.ballotName,
          voteStemDtoList: filterData,
        };
        console.log("resultPostresultPost");
        console.log(resultPost);
        api.updateStemMessage(resultPost).then((res) => {
          if (res.data.code === 200) {
            state.ballotId = res.data.data.ballotId;
            console.log("res.data.data==============", res.data.data);
            console.log("res.state.ballotId==============", state.ballotId);
            message.success("编辑成功");
            closeDrawer();
          }
        });
      } else {
        resultPost = {
          ballotName: state.ballotName,
          voteStemDtoList: filterData,
        };
        console.log("=========", resultPost);
        api.createStemMessage(resultPost).then((res) => {
          if (res.data.code === 200) {
            state.ballotId = res.data.data.ballotId;
            console.log("res.data.data2==============", res.data.data);
            console.log("res.state.ballotId=2s=============", state.ballotId);
            message.success("创建成功");
            closeDrawer();
          }
        });
      }
    };
    const handleAllCancel = () => {
      state.allFormsData = [];
    };

    const checkVal = (filterData) => {
      console.log("filterData.====", filterData);

      for (let item of filterData) {
        if (!item.voteStemName) {
          message.error("题干为必填 请确认");
          return false;
        }
      }
      return true;
    };

    return {
      ...toRefs(state),
      handleTypes,
      handleSave,
      handleAllCancel,
      handleDel,
      afterVisibleChange,
      closeDrawer,
    };
  },
};
</script>
<style lang="scss">
.researchadd {
  .header {
    height: 73px;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;
    margin-bottom: 25px;

    .headerTitle {
      font-size: 18px;
      font-weight: 600;
      color: #333333;
      line-height: 25px;
      margin-left: 24px;
    }
  }

  .main_left {
    margin-left: 50px;
    padding-right: 30px;
    flex: 1;
    border-right: 1px solid #e8e8e8;

    .main_item {
      display: flex;
      align-items: center;
      margin-bottom: 32px;

      .signbox {
        width: 120px;
        display: flex;
        justify-content: end;
        align-items: center;

        .sign {
          margin-right: 5px;
        }
      }

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

        .xkbtn {
          cursor: pointer;
          width: 130px;
          height: 40px;
          background: #4ea6ff;
          border-radius: 8px;
          border: 0;
          margin-right: 8px;
          color: #fff;
          margin-right: 10px;
        }

        .fileTigan {
          display: flex;
          align-items: center;
          padding: 3px 5px;
          background-color: rgba(42, 103, 209, 0.4);

          span {
            margin-right: 5px;
          }

          .delBox {
            width: 13px;
            height: 13px;
            background-image: url(@/assets/images/basicinfo/ch.png);
            background-size: 100% 100%;
            border-radius: 50%;
          }
        }
      }
    }

    .main_item2 {
      display: flex;
      align-items: flex-start;
      margin-bottom: 32px;

      .signbox {
        width: 120px;
        display: flex;
        justify-content: end;
        align-items: center;

        .sign {
          margin-right: 5px;
        }
      }

      .kqszbox {
        .qdqtbox {
          margin-left: 56px;
        }

        .setbox {
          display: flex;
          flex-wrap: wrap;
          margin-top: 10px;
          margin-bottom: 24px;

          .timerbox {
            margin-top: 6px;
            margin-right: 32px;
            display: flex;
            align-items: center;
            flex-wrap: nowrap;
          }
        }
      }

      .btnbox2 {
        display: flex;
        flex-direction: column;
        justify-content: flex-start;

        .xkbtn {
          cursor: pointer;
          width: 130px;
          height: 40px;
          background: #4ea6ff;
          border-radius: 8px;
          border: 0;
          margin-right: 16px 8px 32px 0;
          color: #fff;
          margin-top: 16px;
          margin-bottom: 60px;
        }
      }
    }
  }
}
</style>
