<template>
  <div class="intelligentWriting">
    <h3 class="title">
      <el-icon @click="back" class="pointer" style="margin-right: 12px"> <arrow-left /> </el-icon
      >审核方案名称
    </h3>
    <el-row style="margin-top: 20px">
      <el-col :span="8">
        <el-input
          v-model="keyword"
          style="width: 100%"
          placeholder="请输入关键词"
          :prefix-icon="Search"
          clearable
          @input="searchPageData()"
        />
      </el-col>
      <!--搜索条件/批量删除-->
      <el-col :span="8" :offset="8" style="text-align: right">
        <el-dropdown placement="bottom-start">
          <el-button>
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :disabled="ids.length === 0" @click="handleBatchDel">
                <el-icon class="el-icon--right">
                  <delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <el-dropdown placement="bottom-start">
          <el-button type="primary" :icon="Plus" class="ml-12" @click="openCreateDialog">
            新建规则
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                @click="
                  go('smartReviewRule', {
                    type: 'add',
                    reviewId: route.query?.id,
                    reviewName: getReviewPlanName
                  })
                "
              >
                人工编辑规则
              </el-dropdown-item>
              <el-dropdown-item 
                @click="
                  go('smartReviewExtraction',{
                    type: 'add',
                    reviewId: route.query?.id,
                    reviewName: getReviewPlanName
                  })
                "
              > 文档抽取 </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>
    </el-row>
    <!--loading-->
    <div
      v-loading="pageLoading"
      element-loading-text="正在加载..."
      style="width: 100%; height: calc(100vh - 250px)"
      class="loading-page"
      v-if="pageLoading"
    ></div>
    <!--搜索结果-->
    <lz-page-empty v-else-if="!writingData.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="writingData"
      :pagination-config="paginationConfig"
      @sizeChange="handleSizeChange"
      @changePage="getPageData"
      @selection-change="handleSelectionChange"
      :tableDefaultHeight="320"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="规则名称" min-width="220">
        <template #default="{ row }">
          <span @click="handleEdit(row)">
            <AutoTooltip style="color: #3067ef; cursor: pointer">
              {{ row.name }}
            </AutoTooltip>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="规则详情" min-width="220">
        <template #default="{ row }">
          <span>
            <AutoTooltip>
              {{ row.content }}
            </AutoTooltip>
          </span>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="title" label="所属审核方案" min-width="130">
        <template #default="{ row }">
          <AutoTooltip>
            {{ row.review_plan_name }}
          </AutoTooltip>
        </template>
      </el-table-column> -->

      <el-table-column prop="modify_time" label="最近修改" min-width="120">
        <template #default="{ row }">
          <AutoTooltip>
            {{ datetimeFormat(row.modify_time) }}
          </AutoTooltip>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="" width="100">
        <template #header> 启用状态 </template>
        <template #default="{ row }">
          <el-switch
            v-model.lazy="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handelSwitch(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="create_id" label="创建人" min-width="100">
        <template #default="{ row }">
          <AutoTooltip>
            {{ row.create_id }}
          </AutoTooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="120" fixed="right">
        <template #default="{ row }">
          <div>
            <span class="mr-10 primary-text" @click="handleView(row)" style="cursor: pointer">
              <el-tooltip effect="dark" content="查看" placement="top">
                <lz-svg-icon icon-class="cxjg" />
              </el-tooltip>
            </span>
            <span class="mr-10 primary-text" @click="handleEdit(row)" style="cursor: pointer">
              <el-tooltip effect="dark" content="编辑" placement="top">
                <lz-svg-icon icon-class="edit" />
              </el-tooltip>
            </span>
            <span class="mr-10 primary-text" @click="handleDel(row)" style="cursor: pointer">
              <el-tooltip effect="dark" content="删除" placement="top">
                <lz-svg-icon icon-class="delete" />
              </el-tooltip>
            </span>
          </div>
        </template>
      </el-table-column>
    </app-table>
  </div>
</template>

<script lang="ts" setup>
import AppTable from '@/components/app-table/index.vue'
import AutoTooltip from '@/components/auto-tooltip/index.vue'
import { MsgConfirm, MsgSuccess, MsgWarning, MsgError } from '@/utils/message'
import { debounce } from 'lodash-es'
import { onMounted, reactive, ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Search, Delete, Plus } from '@element-plus/icons-vue'
import { reviewPlanList, deleteReviewRule, reviewRuleCheckStatus } from '@/api/review'
import { datetimeFormat } from '@/utils/time'

const route = useRoute()
const router = useRouter()

const CreateDialogRef = ref()
const ids = ref([])
const writingData = ref<any[]>([])
const paginationConfig = reactive({
  current_page: 1,
  page_size: 10,
  total: 0
})
const keyword = ref<any>('')
const pageLoading = ref(false)
const pageError = ref(false)

const getReviewPlanName = computed(()=> {
  if (Array.isArray(writingData.value) && writingData.value.length){
    return  writingData.value[0].review_plan_name
  }
  return route.query.reviewName || '';
})

function openCreateDialog(row?: any) {
  CreateDialogRef.value?.open(row)
}
function back() {
  router.go(-1)
}

/**
 * 跳转到二级页面
 * @param name  二级页面路由name名称 docsWriting
 * @param query 可选参数：router传递参数默认以对象形式
 */
function go(name: string, query?: any) {
  router.push({ name, query })
}

function handleEdit(row: any) {
  go('smartReviewRule', {
    id: row.id,
    type: 'edit',
    reviewId: route.query?.id,
    reviewName: row.review_plan_name
  })
}
function handleView(row: any) {
  go('smartReviewRule', {
    id: row.id,
    type: 'view',
    reviewId: route.query?.id,
    reviewName: row.review_plan_name
  })
}

function deletItems(ids: any) {
  if (!Array.isArray(ids)) return MsgWarning('参数错误')
  const temp = ids.map((el: any) => `${el}`)
  deleteReviewRule(temp)
    .then(() => {
      MsgSuccess('删除成功！')
      handleSizeChange()
    })
    .catch(() => {
      MsgError('删除失败！')
    })
    .finally()
}
function handleDel(row: any) {
  MsgConfirm('提示', '确定删除所选规则？').then(() => {
    deletItems([row.id])
  })
}

function handleSizeChange() {
  paginationConfig.current_page = 1
  getPageData()
}
function handleSelectionChange(val: any) {
  ids.value = val.map((v: any) => v.id)
}
function handleBatchDel() {
  if (ids.value.length === 0) {
    return MsgWarning('请先选择一条或多条数据!')
  }
  MsgConfirm('提示', '确定删除所选文档？').then(() => {
    deletItems(ids.value)
  })
}

// 启用状态
function handelSwitch(row: any) {
  pageLoading.value = true
  const status = row.status
  reviewRuleCheckStatus(row.id, status)
    .then((res: any) => {
      if (res.status === '0') {
        MsgSuccess('修改成功')
      }
    })
    .catch((err) => {
      MsgError(err.response.data.msg)
    })
    .finally(() => {
      pageLoading.value = false
      getPageData()
    })
}

const searchPageData = debounce(() => {
  handleSizeChange()
}, 300)

async function getPageData() {
  pageLoading.value = true
  const { current_page, page_size } = paginationConfig
  reviewPlanList(route.query.id, {
    page: current_page,
    page_size,
    keyword: keyword.value
  })
    .then((res) => {
      const { data, total } = res
      writingData.value = data
      paginationConfig.total = total
    })
    .catch((err) => {
      console.log(err)
      pageError.value = true
    })
    .finally(() => (pageLoading.value = false))
}

onMounted(() => {
  getPageData()
})
</script>

<style scoped lang="scss">
.title {
  height: 20px;
  font-family:
    PingFang SC,
    PingFang SC;
  font-weight: 400;
  font-size: 16px;
  color: #191919;
  line-height: 20px;
  text-align: left;
  font-style: normal;
  text-transform: none;
  display: flex;
  align-items: center;
  .pointer {
    cursor: pointer;
  }
}
</style>
