<template>
  <a-drawer
    :visible="addprojvisible"
    class="drawerStyle addonlineDrawer"
    width="80%"
    title="添加在线"
    placement="right"
    @after-visible-change="afterVisibleChange"
  >
    <div class="drawerMain">
      <div class="header">
        <div v-if="edit" class="headerTitle">编辑项目</div>
        <div v-else class="headerTitle">添加项目</div>
        <img
          style="width: 29px; height: 29px; cursor: pointer"
          src="../../assets/images/basicinfo/close.png"
          @click="closeDrawer"
        />
      </div>
      <div class="contentMain">
        <div class="main_items">
          <div class="mi_ipts">
            <div class="mii_ipt">
              <div class="ipt_name"></div>
              <div class="fi_input">
                <a-input
                  v-model:value="inputV1"
                  style="width: 210px; height: 40px; border-radius: 8px"
                  placeholder="请输入项目名称"
                  maxlength="20"
                />
              </div>
            </div>
            <div class="mii_ipt">
              <div class="ipt_name"></div>
              <div class="fi_input">
                <a-input
                  v-model:value="inputV2"
                  style="width: 210px; height: 40px; border-radius: 8px"
                  placeholder="请输入项目经理"
                  maxlength="20"
                />
              </div>
            </div>
            <div class="mii_ipt">
              <div class="ipt_name"></div>
              <div class="fi_input">
                <a-input
                  v-model:value="inputV3"
                  style="width: 210px; height: 40px; border-radius: 8px"
                  placeholder="请输入创建人"
                  maxlength="20"
                />
              </div>
            </div>
          </div>
          <div class="mi_btns" style="margin-left: 0px">
            <div class="btn btn1">
              <div class="search"></div>
              <div class="btnText" @click="searchProjectList()">搜索</div>
            </div>
            <div class="btn btn2" @click="resetProjectList()">
              <div class="search"></div>
              <div class="btnText">重置</div>
            </div>
          </div>
        </div>
        <div class="main_notice" v-if="edit">
          <div class="mntc_left">
            <div class="notice_icon"></div>
            <div v-if="selectedRows.length == 0">
              <span class="title"
                >已选择
                <span class="data" style="color: #4ea6ff">{{ 0 }}</span>
                条</span
              >
            </div>
            <div v-else>
              <div>
                <span class="title"
                  >已选择
                  <span class="data" style="color: #4ea6ff">{{
                    selectedRows.length
                  }}</span>
                  条&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
                >
                <span class="title"
                  >名称：
                  <span
                    class="data"
                    style="color: #4ea6ff; margin-right: 15px"
                    >{{ selectedRows[0].name }}</span
                  >
                </span>
                <span class="title"
                  >项目经理：
                  <span
                    class="data"
                    style="color: #4ea6ff; margin-right: 15px"
                    >{{ selectedRows[0].manager }}</span
                  >
                </span>
                <span class="title"
                  >创建人：
                  <span
                    class="data"
                    style="color: #4ea6ff; margin-right: 15px"
                    >{{ selectedRows[0].creater }}</span
                  >
                </span>
                <span class="title"
                  >创建时间：
                  <span class="data" style="color: #4ea6ff">{{
                    selectedRows[0].time
                  }}</span>
                </span>
              </div>
              <!-- <div v-else>
                <span class="title"
                  >已选择 <span class="data">1</span> 条;</span
                >
                <span class="title"
                  >名称：
                  <span class="data">{{ assessment1.createName }}</span>
                </span>
                <span class="title"
                  >题数：
                  <span class="data">{{
                    assessment1.essayQuestionVoList.length
                  }}</span>
                </span>
                <span class="title"
                  >创建人：
                  <span class="data">{{ assessment1.createUser }}</span>
                </span>
                <span class="title"
                  >创建时间：
                  <span class="data">{{ assessment1.createTime }}</span>
                </span>
              </div> -->
            </div>
          </div>
        </div>

        <div class="main_table">
          <div class="drawerbox">
            <!-- 添加的时候显示多选的表 -->

            <!-- 编辑的时候显示单选的表 -->
            <a-table
              :columns="tableDataFunc()"
              :data-source="drawertableData"
              :row-selection="{
                selectedRowKeys: selectedRowKeys,
                onChange: onSelectChange,
                type: 'radio',
              }"
              :loading="tableDataTotal === -1 ? true : false"
              @expand="expandTable"
              :pagination="false"
            >
            </a-table>
          </div>
        </div>
        <div class="tableBox">
          <div class="pa">
            <a-pagination
              v-if="tableDataTotal > 10"
              :showSizeChanger="false"
              showQuickJumper="true"
              hideOnSinglePage="true"
              :pageSize="pageSize"
              v-model:current="currentPage"
              :total="tableDataTotal"
              class="pagination"
              @change="changePagination"
              style="
                display: flex;
                justify-content: center;
                margin-top: 12px;
                margin-bottom: 12px;
              "
            />
          </div>
        </div>
      </div>
      <div class="main_btns">
        <button @click="closeDrawer" class="btn1">取消</button>
        <button @click="updateTaskList" class="btn2">确定</button>
      </div>
    </div>
    <!-- 有重复添加的项目时的弹窗 -->
    <a-modal
      v-model:visible="sameModal"
      :footer="null"
      :closable="sameCopy"
      wrapClassName="sameModal"
      centered="true"
    >
      <div class="delete">
        <div class="del_header"></div>
        <div class="del_main">
          <div class="header">
            <div class="icon"></div>
            <span>提示</span>
            <div class="close_exit" @click="closeSameModal"></div>
          </div>
          <div class="body">
            <span>项目已存在，是否重复添加？</span>
          </div>
          <div class="del_btnbox">
            <div class="del_btn btn1" @click="closeSameModal">
              <div class="btnText">取消</div>
            </div>
            <div class="del_btn btn2" @click="sureSameModal">
              <div class="btnText">确定</div>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </a-drawer>
</template>
<script>
import { reactive, toRefs } from "vue";
import { RouterEditTask } from "@/api/indexTask";
import { message } from "ant-design-vue";
// import * as apiProj from "../../api/index.js";
import dayjs from "dayjs";
import * as indexAudit from "../../api/indexAudit";

export default {
  name: "AddProject",
  props: {
    addprojvisible: {
      type: Boolean,
      default: false,
    },
    EditProjectId: {
      type: Number,
      default: null,
    },
    edit: {
      //  是否为编辑
      type: Boolean,
      default: null,
    },
    projectId: {
      type: Number,
      default: null,
    },
    chooseStageId: {
      type: Number,
      default: null,
    },
    routerTaskId: {
      type: Number,
      default: 0,
    },
    isLevel: {
      // 是否是关卡页面触发
      type: Number,
      default: null,
    },

    projectTaskId: {
      // 要编辑的projectId
      type: Number,
      default: null,
    },
    routerId: {
      type: Number,
      default: null,
    },
    isactive: {
      type: Number,
      default: null,
    },
    // 路径图里选择的阶段下的任务列表
    chooseProjectList: {
      type: String,
      default: null,
    },
  },
  setup(props, ctx) {
    const state = reactive({
      inputV1: "",
      inputV2: "",
      inputV3: "",
      textV1: "",
      statu: 0,
      checkedC1: false,
      discussSettings: "",
      addLoading: false,
      sameModal: false,
      sameCopy: false,
      sameProj: null,
      selectedRowKeys: [],
      selectedRows: [],
      currentPage: 1,
      tableDataTotal: 0,
      pageSize: 10,
      //项目抽屉、列表参数
      drawertableData: [],
    });

    const tableDataFunc = () => {
      const drawercolumns = [
        {
          title: "项目名称",
          dataIndex: "name",
          key: "projectName",
          width: "40%",
          ellipsis: true,
        },
        {
          title: "项目经理",
          dataIndex: "manager",
          key: "manager",
          width: "20%",
          align: "center",
        },
        {
          title: "创建人",
          dataIndex: "creater",
          key: "creater",
          width: "20%",
          align: "center",
        },
        {
          title: "创建时间",
          dataIndex: "time",
          key: "time",
          width: "20%",
          align: "center",
        },
      ];
      return drawercolumns;
    };
    const closeDrawer = () => {
      ctx.emit("update:addprojvisible", false);
      ctx.emit("update:edit", false);
      state.currentPage = 1;
      state.tableDataTotal = 0;
      state.drawertableData = [];
      state.inputV1 = "";
      state.inputV2 = "";
      state.inputV3 = "";
      state.selectedRows = [];
      state.selectedRowKeys = [];
    };
    // const rowSelection =()=> ref({
    //   checkStrictly: false,
    //   onChange: (selectedRowKeys, selectedRows) => {
    //     console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    //   },
    //   onSelect: (record, selected, selectedRows) => {
    //     console.log(record, selected, selectedRows);
    //   },
    //   onSelectAll: (selected, selectedRows, changeRows) => {
    //     console.log(selected, selectedRows, changeRows);
    //   },
    // });
    const start = () => {
      state.loading = true;
      // ajax request after empty completing
      setTimeout(() => {
        state.loading = false;
      }, 1000);
    };
    // const onSelectChange = (selectedRowKeys, selectedRows) => {
    //   console.log("selectedRowKeys changed: ", selectedRowKeys);
    //   state.selectedRowKeys = selectedRowKeys;
    //   this.selectedRows = selectedRows;
    // };
    const searchProjectList = () => {
      state.selectedRowKeys = [];
      getAllProjText();
    };
    const resetProjectList = () => {
      state.selectedRowKeys = [];
      state.inputV1 = "";
      state.inputV2 = "";
      state.inputV3 = "";
      getAllProjText();
    };

    //翻页
    const changePagination = (page) => {
      state.currentPage = page;
      getAllProjText();
      // console.log("翻页", page, pageSize);
    };

    // 点击编辑默认选中
    const defaultValueOption = () => {
      if (props.edit) {
        state.drawertableData = [];
        state.selectedRowKeys = [props.EditProjectId];
        getCurrentPage();
      }
    };
    // TODO 这里后续需要给接口或者改动
    // 获取所有，确定分页位置
    const getCurrentPage = () => {
      indexAudit
        .auditlist({
          createName: state.inputV1,
          manager: state.inputV2,
          name: state.inputV3,
          pageNo: 1,
          pageSize: 10000,
          status: 3,
        })
        .then((res) => {
          // let arr = res.data.data.rows;
          if (res.status === 200) {
            console.log("all - project - info", res.data.data);

            let allarr = res.data.data.rows;
            let isHav = true;
            for (let i = 0; i < allarr.length; i++) {
              if (allarr[i].projectId == props.EditProjectId) {
                isHav = false;
                state.currentPage = Math.ceil((i + 1) / 10);
                console.log("sdadasd", state.currentPage);
                getAllProjText();
                return;
              }
            }
            if (isHav) {
              getAllProjText();
              state.currentPage = 1;
            }
            // state.drawertableData = getTableDate(arr);
            // state.tableDataTotal = res.data.data.total
          }
        })
        .catch(() => {
          message.destroy();
          //message.error("获取全部项目信息接口失败");
        });
    };

    //获取全部项目信息接口
    const getAllProjText = () => {
      console.log("搜索的参数信息", {
        createName: state.inputV3,
        manager: state.inputV2,
        name: state.inputV1,
        pageNo: state.currentPage,
        pageSize: state.pageSize,
        status: 3,
      });

      indexAudit
        .auditlist({
          createName: state.inputV3,
          manager: state.inputV2,
          name: state.inputV1,
          pageNo: state.currentPage,
          pageSize: state.pageSize,
          status: 3,
        })
        .then((res) => {
          let arr = res.data.data.rows;
          if (res.status === 200) {
            console.log("all - project - info", res.data.data);
            state.drawertableData = getTableDate(arr);
            state.tableDataTotal = res.data.data.total;
          }
        })
        .catch(() => {
          message.destroy();
          //message.error("获取全部项目信息接口失败");
        });
    };
    const afterVisibleChange = () => {
      if (props.edit) {
        defaultValueOption();
      } else {
        getAllProjText();
      }
    };

    const handelChangePage = (page, pageSize) => {
      state.currentPage = page;
      state.pageSize = pageSize;
      getAllProjText();
    };
    const getTableDate = (data) => {
      let array = [];
      data.map((value) => {
        if (value.type == 3) {
          let obj = {
            key: value.projectId,
            parentId: value.parentId,
            projectId: value.projectId,
            name: value.name,
            manager: value.manager,
            time: dayjs(value.createTime).format("YYYY-MM-DD"),
            creater: value.createName,
          };
          array.push(obj);
        } else {
          let obj = {
            key: value.projectId,
            parentId: value.parentId,
            name: value.name,
            manager: value.manager,
            time: dayjs(value.createTime).format("YYYY-MM-DD"),
            children: value.subList ? getTableDate(value.subList) : [],
            creater: value.createName,
          };
          array.push(obj);
        }
      });
      return array;
    };
    //项目抽屉用的
    const updateTaskList = () => {
      //const resultArr = [];
      state.selectedRows.forEach((item) => {
        let origin = JSON.parse(props.chooseProjectList);
        console.log("ccxx", origin);
        if (origin == null) {
          closeSameModal();
          closeDrawer();
          message.destroy();
          message.warning("添加成功");
          return;
        }
        if (origin.length == 0) {
          //可以直接添加到任务列表里
          updateTask(item);
          closeDrawer();
        } else {
          //需要先判断是否含有之前的
          //根据courseId判断
          let re = origin.filter((it) => {
            return it.courseId == item.key;
          });
          console.log("re", re);
          if (re.length == 0) {
            updateTask(item);
          } else {
            state.sameProj = item;
            //询问是否重复添加
            showSameModal();
          }
        }
      });
    };

    const updateTask = async (res) => {
      if (props.isLevel == 1) {
        if (!props.isactive) {
          message.destroy();
          return message.warning("请先选中关卡");
        }
        await RouterEditTask({
          chapterId: props.isactive,
          courseId: res.key,
          name: res.name,
          routerId: props.routerId,
          routerTaskId: props.routerTaskId || 0,
          type: 13,
        })
          .then(() => {
            message.success(`${props.edit ? "编辑" : "新增"}关卡任务成功`);
            ctx.emit("changeData", false);
            closeDrawer();
          })
          .catch(() => {
            message.error(`${props.edit ? "编辑" : "新增"}关卡任务失败`);
          });
      }
    };
    const onSelectChange = (selectedRowKeys, selectRow) => {
      console.log("selectedRowKeys changed: ", selectedRowKeys, selectRow);
      state.selectedRowKeys = selectedRowKeys;
      state.selectedRows = selectRow;
    };

    const showSameModal = () => {
      state.sameModal = true;
    };
    const closeSameModal = () => {
      state.sameProj = null;
      state.sameModal = false;
    };
    const sureSameModal = async () => {
      // updateTask(state.sameProj);
      if (state.selectedRows && state.selectedRows.length) {
        for (const item in state.selectedRows) {
          await updateTask(item);
        }
      }
      state.sameProj = null;
      state.sameModal = false;
      closeDrawer();
      ctx.emit("changeData", false);
    };
    return {
      ...toRefs(state),
      afterVisibleChange,
      closeDrawer,
      getTableDate,
      start,
      getAllProjText,
      onSelectChange,
      tableDataFunc,
      updateTaskList,
      searchProjectList,
      resetProjectList,
      handelChangePage,
      showSameModal,
      closeSameModal,
      sureSameModal,
      changePagination,
      getCurrentPage,
    };
  },
};
</script>
<style lang="scss">
.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa !important;
}

.sameModal {
  .ant-modal {
    width: 424px !important;
    height: 258px !important;

    .ant-modal-content {
      width: 424px !important;
      height: 258px !important;

      .ant-modal-body {
        width: 424px !important;
        height: 258px !important;
        padding: 0 !important;

        .delete {
          z-index: 999;
          width: 424px;
          height: 258px;
          background: #ffffff;
          box-shadow: 0px 1px 35px 0px rgba(118, 136, 166, 0.21);
          border-radius: 4px;

          // position: absolute;
          // left: 50%;
          // top: 10%;
          // transform: translate(-50%, -50%);
          .del_header {
            position: absolute;
            width: calc(100%);
            height: 68px;
            background: linear-gradient(
              rgba(78, 166, 255, 0.2) 0%,
              rgba(78, 166, 255, 0) 100%
            );
          }

          .del_main {
            width: 100%;
            position: relative;

            .header {
              display: flex;
              align-items: center;
              padding-top: 20px;
              padding-left: 26px;
              font-size: 16px;

              .icon {
                width: 16px;
                height: 16px;
                margin-right: 10px;
                background-image: url(@/assets/images/taskpage/gan.png);
                background-size: 100% 100%;
              }

              .close_exit {
                position: absolute;
                right: 42px;
                cursor: pointer;
                width: 20px;
                height: 20px;
                background-image: url(@/assets/images/coursewareManage/close.png);
                background-size: 100% 100%;
              }
            }

            .body {
              width: 100%;
              margin: 34px auto 56px auto;
              display: flex;
              justify-content: center;
              align-items: center;
              flex-direction: column;
              // background-color: red;
              position: relative;

              .back {
                position: absolute;
                top: 30px;
                font-size: 12px;
                font-weight: 400;
                color: #666666;
              }
            }

            .del_btnbox {
              display: flex;
              margin: 30px auto;
              justify-content: center;

              .del_btn {
                width: 100px;
                height: 40px;
                background: rgba(64, 158, 255, 0);
                border-radius: 8px;
                display: flex;
                align-items: center;
                justify-content: center;

                flex-shrink: 0;
                cursor: pointer;

                .btnText {
                  font-size: 14px;
                  font-weight: 400;
                  line-height: 40px;
                }
              }

              .btn1 {
                border: 1px solid rgba(64, 158, 255, 1);
                color: #4ea6ff;
                margin-right: 14px;
              }

              .btn2 {
                background-color: #4ea6ff;
                color: #ffffff;
              }
            }
          }
        }
      }
    }
  }
}

.addrefDrawer {
  .drawerMain {
    // .main_notice {
    //   display: flex;
    //   justify-content: space-between;
    //   align-items: center;
    //   margin-bottom: 32px;
    //   height: 40px;
    //   background-color: #e9f6fe;
    //   .mntc_left {
    //     display: flex;
    //     align-items: center;
    //     .title {
    //       color: rgba(0, 0, 0, 0.65);
    //       margin-right: 17px;
    //     }
    //     .data {
    //       color: #4ea6ff;
    //     }
    //     .notice_icon {
    //       width: 14px;
    //       height: 14px;
    //       margin-right: 9px;
    //       margin-left: 9px;
    //       background-image: url(@/assets/images/coursewareManage/gan.png);
    //       background-size: 100% 100%;
    //     }
    //   }
    //   .mntc_right {
    //     cursor: pointer;
    //   }
    // }
    .header {
      height: 73px;
      border-bottom: 1px solid #e8e8e8;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-shrink: 0;

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

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

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

        .main_item {
          display: flex;
          align-items: center;
          margin-top: 32px;
          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;

            .ant-input {
              height: 100%;
            }

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

        .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;
            }
          }

          .textarea {
            width: 423px;

            .ant-input {
              width: 100%;
            }

            .ant-input-textarea-show-count {
              position: relative;
            }

            .ant-input-textarea-show-count::after {
              position: absolute;
              right: 10px;
              bottom: 0px;
            }

            .ant-input {
              border-radius: 8px;
            }
          }
        }
      }

      .tableBox {
        // margin: 20px 38px 30px;
        margin: 10px 35px 0px 35px;

        th.h {
          background-color: #eff4fc !important;
        }

        .ant-table-tbody
          > tr:hover:not(.ant-table-expanded-row):not(.ant-table-row-selected)
          > td {
          background: #f6f9fd;
        }
      }

      .tableBox {
        padding-bottom: 20px;

        .pa {
          // position: absolute;
          // bottom: 20px;
          // left: 0;
          width: 100%;
          // height: 20px;
          // background-color: red;
          display: flex;
          justify-content: center;

          // margin-bottom: 10px;
          // position: absolute;
          // bottom: -40px;
          .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }
    .main_table {
      position: relative;
      padding-bottom: 80px;
      .ant-checkbox-wrapper {
        align-items: center;
        margin-top: -2px;
      }
      .ant-table-selection-column {
        padding: 0px !important;
        padding-left: 5px !important;
      }
      .ant-table-thead > tr > th {
        background-color: rgba(239, 244, 252, 1);
      }
      th.h {
        background-color: #eff4fc !important;
      }
      .ant-table-tbody
        > tr:hover:not(.ant-table-expanded-row):not(.ant-table-row-selected)
        > td {
        background: #f6f9fd;
      }
      .pa {
        left: 0;
        width: 100%;
        display: flex;
        justify-content: center;
        position: absolute;
        bottom: 20px;
      }
    }
    .main_btns {
      height: 72px;
      width: 100%;
      bottom: 0;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0px 1px 35px 0px rgba(118, 136, 166, 0.16);

      .btn1 {
        width: 100px;
        height: 40px;
        border: 1px solid #4ea6ff;
        border-radius: 8px;
        color: #4ea6ff;
        background-color: #fff;
        cursor: pointer;
      }

      .btn2 {
        cursor: pointer;
        width: 100px;
        height: 40px;
        background: #4ea6ff;
        border-radius: 8px;
        border: 0;
        margin-left: 15px;
        color: #fff;
      }
    }
  }
}
</style>
