<script setup lang="tsx">
import { ContentWrap } from '../../../../components/ContentWrap'
import { Search } from '../../../../components/Search'
import { Dialog } from '../../../../components/Dialog'
import { Table } from '../../../../components/Table'
import { BaseButton } from '../../../../components/Button'

import { ElMessage, ElMessageBox } from 'element-plus'
import {
  BusinessTableList,
  createBusinessTable,
  baseDataList,
  updateBusinessTable,
  delBusinessTable
} from '../../../../api/system-config/field'
import type { IBusiness } from '../../../../api/system-config/field/types'

import { useTable } from '../../../../hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '../../../../hooks/web/useCrudSchemas'
import Write from './Write.vue'
import FieldsConfig from './FieldsConfig/FieldsConfig.vue'

import { ref, unref, reactive, PropType } from 'vue'

const props = defineProps({
  // 业务类型编码
  classifyId: {
    type: [Number, String] as PropType<number | string>,
    default: 0
  }
  // typeList: {
  //   type: Object,
  //   default: () => {}
  // }
})

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await BusinessTableList({
      current: unref(currentPage),
      size: unref(pageSize),
      classifyId: props.classifyId,
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.totalCount
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

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

// 页面类型 用于动态改变表单的数据模板
const pageType = ref(0)

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'keyWord',
    label: '关键字',
    type: 'index',
    table: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'index',
    label: '编号',
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'serviceName',
    label: '业务表名称',
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.serviceName}</>
        }
      }
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'serviceNo',
    label: '业务编码',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    form: {
      component: 'Input'
    }
  },
  // {
  //   field: 'classifyId',
  //   label: '所属分类',
  //   search: {
  //     hidden: true
  //   },
  //   table: {
  //     slots: {
  //       default: (data: any) => {
  //         return <>{findNodeNameById(props.typeList, 'id', data.row.classifyId, 'classifyName')}</>
  //       }
  //     }
  //   },
  //   form: {
  //     hidden: true
  //   }
  // },
  {
    field: 'tableName',
    label: '关联数据表',
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.tableName}</>
        }
      }
    },
    form: {
      component: 'Select',
      optionApi: async () => {
        const res = await baseDataList()
        return res.data.map((item) => {
          return {
            label: item.tableDesc,
            value: item.tableName
          }
        })
      }
    }
  },
  {
    field: 'orderNo',
    label: '排序号',
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.orderNo}</>
        }
      }
    },
    form: {
      component: 'Input',
      componentProps: {
        placeholder: '请输入序号，仅支持数字'
      }
    }
  },
  {
    field: 'pageType',
    label: '页面类型',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            value: 1,
            label: '使用模板'
          },
          {
            value: 2,
            label: '定制开发'
          }
        ],
        on: {
          change: (val) => {
            pageType.value = val
          }
        }
      }
    }
  },
  {
    field: 'pageTemplate',
    label: '页面模板/地址',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            value: 'custom',
            label: '通用模板'
          },
          {
            value: 'auth',
            label: '带部门权限的模板'
          },
          {
            value: 'business1',
            label: '业务模板-动物流调类'
          },
          {
            value: 'business2',
            label: '业务模板-人畜共患病类'
          }
        ]
      }
    }
  },
  {
    field: 'isEnabled',
    label: '启用状态',
    search: {
      hidden: true
    },
    form: {
      component: 'Switch'
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.isEnabled ? '启用' : '未启用'}</>
        }
      }
    }
  },
  {
    field: 'action',
    width: '300px',
    label: '操作',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <BaseButton size="small" type="primary" onClick={() => action(data.row, 'detail')}>
                详情
              </BaseButton>
              <BaseButton size="small" type="primary" onClick={() => action(data.row, 'edit')}>
                编辑
              </BaseButton>
              <BaseButton size="small" type="primary" onClick={() => action(data.row, 'config')}>
                字段配置
              </BaseButton>
              <BaseButton size="small" type="danger" onClick={() => delData(data.row)}>
                删除
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

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

// 业务编码变动
// watch(
//   () => props.classifyId,
//   (val) => {
//     console.log('classifyId', val)
//   }
// )

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

const currentRow = ref<IBusiness | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = '新增'
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const delData = async (row: IBusiness) => {
  ElMessageBox.confirm('确认删除？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await delBusinessTable(row?.id || 0).then(({ success, message }) => {
      getList()
      ElMessage({
        message: message,
        type: success ? 'success' : 'error'
      })
    })
  })
}

const action = (row: IBusiness, type: string) => {
  currentRow.value = row
  actionType.value = type
  if (type === 'config') {
    fieldsConfigVisible.value = true
  } else {
    dialogTitle.value = type === 'edit' ? '编辑' : '详情'
    dialogVisible.value = true
  }
}

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 (
      actionType.value === 'add'
        ? createBusinessTable({
            classifyId: props.classifyId,
            ...(formData as IBusiness),
            orderNo: Number(formData.orderNo || 0),
            isEnabled: formData.isEnabled ? 1 : 0
          })
        : updateBusinessTable({
            ...(formData as IBusiness),
            isEnabled: formData.isEnabled ? 1 : 0
          })
    )
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      ElMessage({
        message: res.message,
        type: res.success ? 'success' : 'error'
      })
      dialogVisible.value = false
      // currentPage.value = 1
      getList()
    }
  }
}

// 字段配置部分
const fieldsConfigVisible = ref(false)
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">新增</BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
    <Write
      :action-type="actionType"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
      :page-type="pageType"
    />
    <template #footer>
      <BaseButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save"
        >保存
      </BaseButton>
      <BaseButton @click="dialogVisible = false">关闭</BaseButton>
    </template>
  </Dialog>

  <FieldsConfig
    v-model:visible="fieldsConfigVisible"
    title="字段配置"
    :current-row="currentRow as any"
  />
</template>
