<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Upload } from '@/components/Upload'
import { Dialog } from '@/components/Dialog'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElButton,
  ElLink,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElPopconfirm,
  ElMessage
} from 'element-plus'
import { Table } from '@/components/Table'
import {
  getRuleConfigList,
  delTableListApi,
  importExcelApiUrl,
  exportExcelApi
} from '@/api/dataReview/detailRuleConfig'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { reactive, ref, unref } from 'vue'
import { useRouter } from 'vue-router'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useRoute } from 'vue-router'
import { useTagsView } from '@/hooks/web/useTagsView'
import Write from './components/Write.vue'

const { setTitle } = useTagsView()

const { params } = useRoute()

const reportId = ref(params.id as string)

setTitle(`规则配置`)

defineOptions({
  name: 'DataReviewDetailRuleConfig'
})

const { push } = useRouter()

const ids = ref<string[]>([])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const ruleTypeList = [
  {
    label: '非空校验',
    value: 0
  },
  {
    label: '长度校验',
    value: 1
  },
  {
    label: '格式校验',
    value: 2
  },
  {
    label: '范围/码值校验',
    value: 3
  },
  {
    label: '唯一性校验',
    value: 4
  },
  {
    label: '值域校验',
    value: 5
  },
  {
    label: '自定义',
    value: 7
  }
]

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getRuleConfigList({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList, refresh } = tableMethods

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'ruleCode',
    label: '规则编码',
    search: {
      component: 'Input'
    },
    form: {
      hidden: false
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'dataSetCode',
    label: '数据集编码',
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'indexCode',
    label: '指标编码',
    search: {
      component: 'Input'
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'indexName',
    label: '指标名称',
    search: {
      component: 'Input'
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'ruleType',
    label: '规则类型',
    search: {
      component: 'Select',
      componentProps: {
        style: {
          width: '100%'
        },
        options: ruleTypeList
      }
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'ruleDesc',
    label: '规则说明',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'ruleStrength',
    label: '规则强度',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'ruleState',
    label: '规则状态',
    search: {
      component: 'Select',
      componentProps: {
        style: {
          width: '100%'
        },
        options: [
          {
            label: '启用',
            value: 1
          },
          {
            label: '停用',
            value: 0
          }
        ]
      }
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElLink type="primary" underline={false} onClick={() => action(data.row, 'edit')}>
                {'编辑'}
              </ElLink>
              <ElPopconfirm
                title={t('common.delTableMsg')}
                width={200}
                v-slots={{
                  reference: () => {
                    return (
                      <>
                        <ElLink type="primary" underline={false}>
                          {'删除'}
                        </ElLink>
                      </>
                    )
                  }
                }}
                onConfirm={() => delAloneData(data.row)}
              ></ElPopconfirm>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const delLoading = ref(false)

const delData = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const delAloneData = async (row: TableData) => {
  delLoading.value = true
  const res = await delTableListApi([row.id])
    .catch(() => {})
    .finally(() => {
      delLoading.value = false
    })
  delLoading.value = false
  if (res) {
    const { code } = res.data
    if (code === 1) {
      ElMessage.success('操作成功!')
      getList()
    } else {
      ElMessage.error('操作失败!')
    }
  }
}

const disabled = ref(true)

const onSelectionChange = (selection: TableData[]) => {
  disabled.value = selection.length === 0
}

const action = async (row: any, type: string) => {
  dialogVisible.value = true
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  actionRuleType.value = row.value
  currentRow.value = row
}

const reportName = ref('报表名称')
const indexSetHigh = ref<any>(null)
const indexSetList = ref<any[]>([{ id: 123, name: '数据集1' }])

const onIndexSetItem = (item: any) => {
  indexSetHigh.value = item
}

const AddAction = (row: any) => {
  dialogTitle.value = t('exampleDemo.add') + `${row.label}配置`
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
  actionRuleType.value = row.value
}

const onExport = async () => {
  const data = { ...unref(searchParams) }
  await exportExcelApi(data)
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<any>(null)
const actionType = ref('')
const actionRuleType = ref<number>()

const writeRef = ref<ComponentRef<typeof Write>>()
const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    // const res = await saveDepartmentApi(formData)
    //   .catch(() => {})
    //   .finally(() => {
    //     saveLoading.value = false
    //   })
    // if (res) {
    //   dialogVisible.value = false
    //   currentPage.value = 1
    //   getList()
    // }
  }
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-1">
      <div class="flex justify-center items-center mb-16px">
        <div class="flex-1">{{ reportName }}</div>
      </div>
      <div class="list">
        <div
          v-for="(item, key) in indexSetList"
          :key="key"
          class="item"
          :class="{ selected: indexSetHigh?.id === item.id }"
          @click="onIndexSetItem(item)"
        >
          {{ item.name }}
        </div>
      </div>
    </ContentWrap>
    <ContentWrap class="flex-[5] ml-10px">
      <Search
        :schema="allSchemas.searchSchema"
        @search="setSearchParams"
        @reset="setSearchParams"
      />

      <Table
        v-model:pageSize="pageSize"
        v-model:currentPage="currentPage"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        :pagination="{
          total: total
        }"
        @register="tableRegister"
        @refresh="refresh"
        @selection-change="onSelectionChange"
      >
        <template #buttons>
          <ElDropdown>
            <ElButton type="primary">
              {{ '添加' }}
            </ElButton>
            <template #dropdown>
              <ElDropdownMenu>
                <ElDropdownItem
                  v-for="(item, key) in ruleTypeList"
                  :key="key"
                  @click="AddAction(item)"
                >
                  {{ item.label }}
                </ElDropdownItem>
              </ElDropdownMenu>
            </template>
          </ElDropdown>
          <Upload :url="importExcelApiUrl" :callback="getList">
            <ElButton type="primary">导入</ElButton>
          </Upload>
          <ElButton type="primary" @click="onExport">导出</ElButton>
        </template>
      </Table>
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <Write
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
      />

      <template #footer>
        <ElButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </ElButton>
        <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
      </template>
    </Dialog>
  </div>
</template>

<style lang="less" scoped>
.list {
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  .item {
    padding: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
    &.selected {
      background-color: #f3f3f3;
    }

    & + .item {
      border-top: 1px solid var(--el-border-color);
    }
  }
}
</style>
