<template>
    <div class="intelligentWriting">
      <div class="flex-between mb-16" style="margin-top: 17px;">
        <div class="flex-between">
          <el-space>
            <el-input
              v-model="searchForm.keyword"
              style="width: 260px"
              placeholder="请输入关键词"
              :prefix-icon="Search"
              clearable
              @input="searchPageData()"
            />
            <span style="padding-left: 12px;">所属方案</span>
            <el-select
              v-model="searchForm.review_plan_id"
              placeholder="请选择所属方案"
              style="width: 196px"
              clearable
              @change="searchPageData()"
            >
              <el-option
                v-for="item in Options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span style="padding-left: 12px;">状态</span>
            <el-select
              v-model="searchForm.status"
              placeholder="状态"
              style="width: 160px"
              clearable
              @change="searchPageData()"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-space>
        </div>
        <!--搜索条件/批量删除-->
        <div class="flex-between">
          <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>
        </div>
      </div>
      <div class="page-centent" style="height: calc(100vh - 240px); position: relative;">
        <!--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="!tableData.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="tableData"
          :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="handleView(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="review_plan_name" label="所属审核方案" min-width="130">
            <template #default="{ row }">
              <span>
                <AutoTooltip>
                  {{ row.review_plan_name }}
                </AutoTooltip>
              </span>
            </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>
    </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 } from 'vue'
  import { useRouter } from 'vue-router'
  import { Search, Delete } from '@element-plus/icons-vue'
  import { reviewRulePageList, deleteReviewRule, reviewPlanPageList, reviewRuleCheckStatus } from '@/api/review'
  import { datetimeFormat } from '@/utils/time'

  const router = useRouter()

  const Options = ref<any>([])
  const statusOptions = ref([
    { label: '已启用', value: 1 },
    { label: '未启用', value: 0 },
  ])

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

  /** 获取所属方案下拉 */
  function getOptions() {
    reviewPlanPageList({ include_default: false }).then((res) => {
      if (res && res.status === '0' && res.data){
        const temp = res.data.map((el: any)=> {
          return { label: el.name, value: el.id }
        })
        Options.value = temp
      }
    })
  }

  // 启用状态
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()
    })
}

  /**
   * 跳转到二级页面
   * @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: row.review_plan_id,
      reviewName: row.review_plan_name
    })
  }

  function handleView(row: any){
    go('smartReviewRule', {
      id: row.id,
      type: 'view',
      reviewId: row.review_plan_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])
      })
      .catch(() => {
        // 用户点击取消时的静默处理
        console.log('用户取消了删除操作')
      })
  }

  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)
      })
      .catch(() => {
        // 用户点击取消时的静默处理
        console.log('用户取消了删除操作')
      })
  }

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

  async function getPageData() {
    pageLoading.value = true
    const { current_page, page_size } = paginationConfig
    const params: any = {
      page: current_page,
      page_size,
      include_default: false
    }
    if(searchForm.keyword) params.keyword = searchForm.keyword
    if(searchForm.status !== '') params.status = searchForm.status
    if(searchForm.review_plan_id) params.review_plan_id = searchForm.review_plan_id
    reviewRulePageList(params)
      .then((res) => {
        const { data, total } = res
        tableData.value = data
        paginationConfig.total = total
      })
      .catch((err) => {
        console.log(err)
        pageError.value = true
      })
      .finally(() => (pageLoading.value = false))
  }

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

  <style scoped lang="scss">
  .card {
    background: rgba(229, 237, 255, 0.41);
    padding-top: 16px;
    padding-bottom: 17px;
    padding-left: 20px;
    position: relative;
    cursor: pointer;
    border-radius: 8px 8px 8px 8px;
    p {
      font-weight: 500;
      font-size: 18px;
      color: #333333;
      line-height: 22px;
      text-align: left;
      font-style: normal;
      text-transform: none;
    }
    span {
      font-weight: 400;
      font-size: 12px;
      color: #666666;
      line-height: 14px;
      text-align: left;
      font-style: normal;
      text-transform: none;
      margin-top: 9px;
    }
    img {
      position: absolute;
      right: 10px;
      top: 10px;
    }
  }
  </style>
