<template>
  <div class="mainContentBox">
    <div class="content-head">
      <div class="head-box-all">
        <div class="box-all">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
          </el-checkbox>
          <span>显示全部</span>
        </div>
        <div class="box-num">{{ checkedCities.length }}</div>
        <div class="box-text">工程类型</div>
      </div>
      <div class="head-box-group">
        <el-scrollbar>
          <el-checkbox-group
            v-model="checkedCities"
            @change="handleCheckedCitiesChange"
          >
            <div
              class="head-box-item"
              :class="[
                checkedCities.includes(type.engineeringType) ? 'active' : '',
              ]"
              v-for="type in typeList"
              :key="type.engineeringType"
            >
              <el-checkbox label="" :value="type.engineeringType"></el-checkbox>
              <div class="name">{{ type.engineeringType }}</div>
              <div class="num">{{ type.typeCount }}</div>
            </div>
          </el-checkbox-group>
        </el-scrollbar>
      </div>
    </div>
    <div class="content-body">
      <div class="cotent-btns">
        <div>工程列表</div>
        <div>
          <el-button type="primary" @click="showAddFun">
            <span class="add">+</span>
            新增工程
          </el-button>
          <!--          <el-button class="active">-->
          <!--            <i />-->
          <!--            按时间倒序-->
          <!--          </el-button>-->
          <!--          <el-button class="normal">-->
          <!--            <i />-->
          <!--            按创建人姓名-->
          <!--          </el-button>-->
        </div>
      </div>
      <div class="content-scrollbar">
        <el-scrollbar>
          <div class="content-list">
            <div
              v-for="(item, index) in engineeringList"
              :key="index"
              class="content-list-item"
            >
              <div class="list-item-flex">
                <div class="list-itme-tit">
                  {{ item.engineeringProductName }}
                </div>
                <div class="list-item-switch">
                  <span class="item-gray">发布</span>
                  <el-popconfirm
                    width="220"
                    @confirm="changeProjectStatus(item)"
                    title="确定要修改发布状态吗?"
                  >
                    <template #reference>
                      <el-switch :model-value="item.publishStatus" />
                    </template>
                  </el-popconfirm>
                </div>
              </div>
              <div class="list-item-flex">
                <div>
                  <span class="item-gray">工程类型：</span
                  >{{ item.engineeringType }}
                </div>
                <div>
                  <span class="item-gray">版本：</span
                  >{{ item.engineeringVersion }}
                </div>
              </div>
              <div class="list-item-flex">
                <div>
                  <span class="item-gray">开发人员：</span>{{ item.creator }}
                </div>
                <div>
                  <span class="item-gray">更新时间：</span>{{ item.updated }}
                </div>
              </div>
              <div class="list-item-btns">
                <span @click="toEdit(item)">
                  <svg-icon icon-class="homeIcon2" />
                </span>
                <el-popconfirm
                  width="220"
                  :icon="InfoFilled"
                  icon-color="#626AEF"
                  title="确认要删除这个工程吗?"
                  @cancel="onDelCancel"
                  @confirm="deleteConfirm(item)"
                >
                  <template #reference>
                    <span>
                      <svg-icon icon-class="homeIcon3" />
                    </span>
                  </template>
                  <template #actions="{ confirm, cancel }">
                    <el-button size="small" @click="cancel">取消</el-button>
                    <el-button type="danger" size="small" @click="confirm">
                      确认删除
                    </el-button>
                  </template>
                </el-popconfirm>

                <span @click="gotoConfigProject(item)">
                  <svg-icon icon-class="homeIcon4" />
                </span>
                <span @click="gotoExecuteTest(item)">
                  <svg-icon icon-class="homeIcon1" />
                </span>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>

      <el-pagination
        class="content-pag"
        background
        layout="sizes,prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        :page-sizes="[9, 12, 15, 18, 30]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <AddComponent ref="addRef" @save-finish="getEngineeringList" />

    <DetailsComponent ref="detailRef" />
  </div>
</template>

<script lang="ts" setup>
import { InfoFilled } from "@element-plus/icons-vue";
import AddComponent from "./components/add.vue";
import DetailsComponent from "./components/details.vue";

import { ref } from "vue";

import type { CheckboxValueType } from "element-plus";
import {
  deleteProject,
  getProjectPage,
  getProjectTypeCount,
  updateProject,
} from "@/api/project";

import { useCommonStoreHook } from "@/store";
const {
  currentProjectId,
  currentMenuIndex,
  pageSize,
  currentTestItemId,
  currentExecutionId,
} = toRefs(useCommonStoreHook());

const checkAll = ref(false);
const isIndeterminate = ref(true);
const checkedCities = ref<any[]>([]);
const typeList = ref<any[]>([]);
// 获取所有的工程类型
const getEngineeringTypeList = () => {
  getProjectTypeCount().then((res) => {
    typeList.value = res.data?.statisticsList ?? [];
  });
};

const handleCheckAllChange = (val: CheckboxValueType) => {
  checkedCities.value = val
    ? typeList.value.map((item) => item.engineeringType)
    : [];
  isIndeterminate.value = false;
  getEngineeringList(false);
};
const handleCheckedCitiesChange = (value: CheckboxValueType[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === typeList.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < typeList.value.length;
  getEngineeringList(false);
};

interface VersionItem {
  id: string; //	主键	string
  engineeringProductName: string; //	产品名称	string
  engineeringType: string; //	工程类型	string
  engineeringVersion: string; //	工程版本	string
  creator: string; //创建人	string 开发人员
  updated: string; //	修改时间	string(date-time)
  created: string; //	创建时间string(date-time)
  deleted: string; //	删除标识;0-未删除；1-已删除	integer(int32)
  deptId: string; //	部门ID	string
  orgId: string; //	组织ID	string
  updator: string; //	上次修改人	string
  publishStatus: number; //发布状态：0-发布 1-未发布
}

/**
 * 显示新增弹框
 */
const addRef = ref();
const showAddFun = () => {
  addRef.value && addRef.value.openDialog();
};
const toEdit = (row) => {
  addRef.value &&
    addRef.value.openDialog(true, JSON.parse(JSON.stringify(row)));
};

// 发布
const isLoading = ref(false);
const changeProjectStatus = async (item: VersionItem) => {
  let p = {
    ...item,
  };
  p.publishStatus = !p.publishStatus;
  await updateProject(p);
  getEngineeringList(false);
};

/**
 * 显示新增弹框
 */
const detailRef = ref();

const showDetailsFun = (row: any) => {
  detailRef.value &&
    detailRef.value.openDialog(true, JSON.parse(JSON.stringify(row)));
};

// 获取列表数据
const currentPage = ref(1);

const total = ref(0);
const engineeringList = ref<VersionItem[]>([]);

const handleSizeChange = (val: number) => {
  currentPage.value = 1;
  pageSize.value = val;
  getEngineeringList();
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getEngineeringList();
};

// const isAsc = ref();
const getEngineeringList = (andGetTypes: boolean = true) => {
  getProjectPage({
    engineeringTypeList: [...checkedCities.value],
    // orders: [
    //   {
    //     column: "",
    //     isAsc: true,
    //   },
    // ],
    pageNo: currentPage.value,
    pageSize: pageSize.value,
    // publishStatus: 0,
  }).then((res) => {
    console.log(res);
    engineeringList.value = res.data.records;
    total.value = res.data.totalCount;
  });
  if (andGetTypes) {
    getEngineeringTypeList();
  }
};

onMounted(() => {
  getEngineeringList();
});

//  删除相关
const onDelCancel = () => {};
const deleteConfirm = async (item) => {
  await deleteProject(item.id);
  ElMessage.success("删除成功");
  getEngineeringList();
};

// 去到配置工程页面
const router = useRouter();
const gotoConfigProject = (project) => {
  currentProjectId.value = project.id;
  currentTestItemId.value = ""; // 要清空数据，不然进入配置页面会导致数据错误

  currentMenuIndex.value = 3;
  router.push({ name: "ProjectConfig", params: { engineerId: project.id } });
};

// 去到测试执行页面
const gotoExecuteTest = (project) => {
  currentExecutionId.value = project.id;

  currentMenuIndex.value = 1;

  router.push({
    name: "RunTesting",
    query: {
      _refresh: Date.now(), // 每次跳转生成不同的时间戳
    },
    params: { engineerId: project.id },
  });
};
</script>

<style scoped lang="scss">
.mainContentBox {
  position: absolute;
  width: 100%;

  .content-head {
    color: var(--hj-white-1);
    // display: flex;
    height: 100px;
    background: $hj-white-1;
    // width: 100%;
    // overflow: hidden;
    // min-width: 0;

    .head-box-all {
      display: inline-block;
      padding: 6px;
      box-sizing: border-box;
      border-radius: 4px 0 0 4px;
      width: 90px;
      height: 100px;
      background: linear-gradient(270deg, #3b7cff 0%, #8aa9ec 100%);
      color: var(--hj-white-1);
      font-size: var(--hj-fs-12);
      text-align: center;

      .box-all {
        color: var(--hj-white-1);
        font-size: var(--hj-fs-12);
      }

      .box-num {
        text-align: center;
        font-size: var(--hj-fs-24);
      }
    }

    .head-box-group {
      display: inline-block;
      width: calc(100% - 100px);

      // flex: 1;

      .el-checkbox-group {
        // height: 100%;
        width: 100%;
        // overflow-x: auto;
        // overflow-y: hidden;
        white-space: nowrap;
        display: flex;
        align-content: center;
        align-items: center;
        flex-direction: row;

        .head-box-item {
          position: relative;
          flex: 0 0 182px;
          font-size: var(--hj-fs-14);
          margin-top: 16px;
          padding: 6px;
          margin-left: 12px;
          height: 67px;
          border: 1px solid #afb9d0;
          border-radius: 4px 4px 4px 4px;

          text-align: center;
          .el-checkbox {
            position: absolute;
            left: 6px;
            top: 0;
          }

          .name {
            line-height: 16px;
            margin-top: 12px;
            font-size: var(--hj-fs-14);
            color: var(--fc-color-5);
          }

          .num {
            line-height: 26px;
            font-size: var(--hj-fs-20);
            font-weight: bold;
            color: var(--fc-color-7);
          }
          &.active {
            background: linear-gradient(90deg, #3cbaff 0%, #3b7cff 100%);
            .name {
              color: var(--hj-white-1);
            }
            .num {
              color: var(--hj-white-1);
            }
          }
        }
      }
    }
  }

  .content-body {
    .cotent-btns {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 26px;
      margin-bottom: 12px;

      .add {
        width: 12px;
        height: 12px;
        line-height: 12px;
        border-radius: 12px;
        text-align: center;
        background-color: #fff;
        color: #3b7cff;
        margin-right: 10px;
      }

      .active,
      .normal {
        i {
          width: 14px;
          height: 14px;
          border-radius: 14px;
          vertical-align: middle;
          margin-right: 10px;
        }
      }

      .active {
        border: 1px solid #1989fa;
        color: #1871f8;

        i {
          border: 4px solid #3b7cff;
        }
      }

      .normal {
        i {
          border: 1px solid #d5d8de;
        }
      }
    }
  }
  .content-scrollbar {
    height: calc(100vh - 325px);
  }
  .content-list {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;

    .content-list-item {
      border: 1px solid #ccc;
      box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1);
      border-radius: 4px 4px 4px 4px;
      padding-top: 12px;
      background-color: $hj-white-1;
    }

    .list-item-flex {
      margin-bottom: 12px;
      padding: 0 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: var(--hj-fs-12);
      color: var(--fc-color-5);

      .list-itme-tit {
        font-size: var(--hj-fs-14);
        font-weight: bold;
      }
      .list-item-switch {
        .item-gray {
          line-height: 32px;
          margin-right: 4px;
        }
      }

      .item-gray {
        color: var(--fc-color-3);
      }
    }

    .list-item-btns {
      height: 37px;
      line-height: 37px;
      color: var(--fc-color-6);
      display: flex;
      justify-content: space-around;
      border-top: 1px solid rgba(175, 185, 208, 0.3);

      span {
        cursor: pointer;
      }
    }
  }
  .content-pag {
    float: right;
    margin-right: 20px;
    margin-top: 20px;
    padding-bottom: 30px;
  }
}
</style>
