<script setup lang="ts">
import { reviewPlanList, reviewPlanPageList } from '@/api/review'
import AppTable from '@/components/app-table/index.vue'
import AutoTooltip from '@/components/auto-tooltip/index.vue'
import DialogBox from '@/components/dialog-box/index.vue'
import { cloneDeep, filter } from 'lodash-es'
import { computed, reactive, ref } from 'vue'

const props = defineProps<{
  visible: boolean
  checkIds: any
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'confirm', value: any): void
  (e: 'cancel'): void
}>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const checkIds: any = ref([])
const checkNames: any = ref([])
const showData: any = ref([])

const handleChange = (val: any) => {
  const selectedList = filter(programmeData.value, (v: any) => val.includes(v.id))
  checkNames.value = selectedList.map((v: any) => v.name)
}

const handleConfirm = () => {
  emit('confirm', {
    checkNames: checkNames.value,
    checkIds: checkIds.value
  })
}

const programmeData: any = ref([])

const getProgrammeData = async () => {
  const data = await reviewPlanPageList({ include_default: true })
  programmeData.value = data?.data || []
  if (props.checkIds) {
    checkIds.value = cloneDeep(props.checkIds)
    handleChange(checkIds.value)
  }
  await showRightData(programmeData.value[0])
}
getProgrammeData()

const selectedPlan: any = ref({})

const showRightData = async (item: any) => {
  selectedPlan.value = item
  await getPageData()
}
const pageLoading = ref<boolean>(false)
const pageError = ref(false)
const ruleData = ref([])
const paginationConfig = reactive({
  current_page: 1,
  page_size: 10,
  total: 0
})

function handleSizeChange() {
  paginationConfig.current_page = 1
  getPageData()
}

async function getPageData() {
  pageLoading.value = true
  const { current_page, page_size } = paginationConfig
  reviewPlanList(selectedPlan.value?.id, {
    page: current_page,
    page_size,
    status: 1
  })
    .then((res) => {
      const { data, total } = res
      if (selectedPlan.value.is_customer === 0) {
        // 转换函数
        const transformedData: any = []
        // 按 level2_name 分组
        const level2Groups: any = {}
        data.forEach((item: any) => {
          const groupKey = item.level2_name || item.review_plan_name
          if (!level2Groups[groupKey]) {
            level2Groups[groupKey] = []
          }
          level2Groups[groupKey].push(item.name)
        })
        // 转换为目标格式
        for (const [title, content] of Object.entries(level2Groups)) {
          transformedData.push({ title, content })
        }
        showData.value = transformedData
      } else {
        ruleData.value = data
        paginationConfig.total = total
      }
    })
    .catch((err) => {
      pageError.value = true
    })
    .finally(() => (pageLoading.value = false))
}
</script>
<template>
  <DialogBox :title="'审核方案设置'" v-model="dialogVisible" width="800" @close="emit('cancel')">
    <div class="programme-list">
      <div class="programme-list-left">
        <div class="programme-list-left-title">审核方案</div>
        <div class="programme-list-left-content">
          <el-checkbox-group v-model="checkIds" @change="handleChange">
            <div
              class="programme-list-left-content-item"
              v-for="(v, i) in programmeData"
              :class="{ active: selectedPlan?.id === v.id }"
              :key="i"
            >
              <el-checkbox :value="v.id" />
              <div @click="showRightData(v)" class="name">{{ v.name }}</div>
              <el-tag v-if="v.is_customer === 1">自定义</el-tag>
            </div>
          </el-checkbox-group>
        </div>
      </div>
      <div class="programme-list-right">
        <div class="programme-list-right-content" v-if="selectedPlan.is_customer === 0">
          <div v-for="(v, i) in showData" :key="i">
            <div class="title" :class="{ firstTitle: i === 0 }">{{ v.title }}</div>
            <div class="content">
              <span v-for="(c, j) in v.content" :key="j">
                {{ c }}
              </span>
            </div>
          </div>
        </div>
        <div class="programme-list-right-content" v-else-if="selectedPlan?.id !== ''">
          <!--loading-->
          <div
            v-loading="pageLoading"
            element-loading-text="正在加载..."
            style="width: 100%; height: 100%"
            class="loading-page"
            v-if="pageLoading"
          ></div>
          <!--搜索结果-->
          <lz-page-empty v-else-if="!ruleData.length && !pageLoading" :type="pageError ? '3' : '2'">
            <lz-svg-icon icon-class="empty2" style="font-size: 312px;"/>  
          </lz-page-empty>
          <!-- table列表和分页-->
          <app-table
            v-else
            class="mt-16"
            :data="ruleData"
            :pagination-config="paginationConfig"
            @sizeChange="handleSizeChange"
            @changePage="getPageData"
            :tableDefaultHeight="320"
          >
            <el-table-column prop="title" label="规则名称" min-width="120">
              <template #default="{ row }">
                <AutoTooltip>
                  {{ row.name }}
                </AutoTooltip>
              </template>
            </el-table-column>
            <el-table-column prop="create_id" label="规则详情" min-width="220">
              <template #default="{ row }">
                <AutoTooltip>
                  {{ row.content }}
                </AutoTooltip>
              </template>
            </el-table-column>
          </app-table>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer res_el-dialog__footer">
        <el-button @click="handleConfirm" type="primary">确定</el-button>
      </span>
    </template>
  </DialogBox>
</template>

<style scoped lang="scss">
.programme-list {
  min-height: 420px;
  display: flex;
  flex-direction: row;
  border: 1px solid #dfe0e3;
  border-radius: 6px;
  padding: 10px;
  margin-bottom: 10px;

  &-left {
    width: 30%;
    background: #f6f6f6;
    border-radius: 4px;
    padding: 10px 12px;
    max-height: 400px;

    &-title {
      font-weight: 500;
      font-size: 14px;
      color: #191919;
      margin-bottom: 10px;
    }

    &-content {
      height: calc(100% - 30px);
      overflow-y: auto;

      &-item {
        display: flex;
        align-items: center;
        padding-left: 5px;
        padding-right: 5px;
        cursor: pointer;
        margin-bottom: 5px;
        border-radius: 4px;

        .name {
          flex: 1;
          line-height: 30px;
          font-size: var(--el-dialog-content-font-size);
          margin-right: 5px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        &:hover {
          background: #eee;
        }
      }

      .active {
        background: #eee;
      }

      // 滚动条宽度
      &::-webkit-scrollbar {
        width: 6px;
      }

      // 滚动条轨道
      &::-webkit-scrollbar-track {
        background: transparent;
        border-radius: 2px;
      }

      // 小滑块
      &::-webkit-scrollbar-thumb {
        background: #eee;
        border-radius: 10px;
      }
    }
  }

  &-right {
    width: 70%;
    padding: 10px 0 20px 20px;
    max-height: 400px;
    overflow: hidden;

    &-content {
      height: 100%;
      overflow-y: auto;
      position: relative;
      // 滚动条宽度
      &::-webkit-scrollbar {
        width: 6px;
      }

      // 滚动条轨道
      &::-webkit-scrollbar-track {
        background: transparent;
        border-radius: 2px;
      }

      // 小滑块
      &::-webkit-scrollbar-thumb {
        background: #eee;
        border-radius: 10px;
      }

      .title {
        font-weight: 500;
        font-size: 14px;
        color: #191919;
        margin-bottom: 16px;
        margin-top: 16px;
      }

      .firstTitle {
        margin-top: 0;
      }

      .content {
        display: flex;
        gap: 22px; /* 控制间距 */
        flex-wrap: wrap;

        span {
          font-size: 12px;
          color: #666666;
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
