import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  DataTableColumn,
  NButton,
  NDataTable,
  NDatePicker,
  NFormItem,
  NInput,
  NModal,
  NSpace,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { materialCategoryPage, materialCategoryRemove } from '../api'
import styles from '../index.module.less'
import dayjs from 'dayjs'
import AddCategory from '../model/addCategory'
import { getTimes } from '@/utils/dateUtil'

export default defineComponent({
  name: 'category-list',
  setup(props) {
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10000
      },
      visiableCity: false,
      dataList: [] as any,
      cityType: 'add',
      materail: null as any
    })
    const searchForm = reactive({
      keyword: '',
      times: null as any,
      operatorId: '' //创建人
    })

    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '分类名称',
          key: 'name',
          fixed: 'left'
        },
        {
          title: '分类描述',
          key: 'desc'
        },
        {
          title: '上传时间',
          key: 'updateTime',
          render(row: any) {
            return row.updateTime || row.createTime
          }
        },

        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          width: 180,
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  text
                  //v-auth="materialCategory/save1599962104022290433"
                  onClick={() => {
                    state.materail = {
                      parentId: row.id
                    }
                    state.visiableCity = true
                  }}
                >
                  添加子分类
                </NButton>
                <NButton
                  type="primary"
                  text
                  //v-auth="materialCategory/update1599962354053140482"
                  onClick={() => {
                    state.cityType = 'update'
                    state.materail = row
                    state.visiableCity = true
                  }}
                >
                  修改
                </NButton>
                <NButton
                  type="primary"
                  text
                  //v-auth="materialCategory/remove1599962245085122562"
                  onClick={() => handleDelete(row)}
                >
                  删除
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

    const saveForm = ref()
    const onSubmit = () => {
      state.pagination.page = 1
      getList()
    }

    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onBtnReset = () => {
      saveForm.value?.reset()
    }

    const getList = async () => {
      try {
        state.loading = true
        const { times, ...reset } = searchForm
        const body = {
          ...reset,
          ...getTimes(times, ['startTime', 'endTime']),
          page: state.pagination.page,
          rows: state.pagination.rows
        }
        const { data } = await materialCategoryPage(body)
        state.loading = false
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }
    // 删除
    const handleDelete = async (row: any) => {
      dialog.warning({
        title: '警告',
        content: '是否确认删除此分类?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          const res = await materialCategoryRemove(row.id)
          if (res.data) {
            onSubmit()
            message.success('删除成功')
          }
        }
      })
    }

    onMounted(() => {
      getList()
    })

    return () => (
      <>
        <SaveForm
          ref={saveForm}
          model={searchForm}
          onSubmit={onSubmit}
          onSetModel={(val: any) => Object.assign(searchForm, val)}
          saveKey="category-key"
        >
          <NFormItem path="keyword" label="分类名称">
            <NInput
              placeholder="分类名称"
              v-model:value={searchForm.keyword}
              onKeydown={(e) => {
                if (e.code === 'Enter') {
                  onSubmit()
                }
              }}
              clearable
            />
          </NFormItem>
          {/* <NFormItem path="keyword">
            <NInput
              placeholder="更新人"
              v-model:value={searchForm.operatorId}
              onKeydown={(e) => {
                if (e.code === 'Enter') {
                  onSubmit()
                }
              }}
              clearable
            />
          </NFormItem> */}
          <NFormItem path="times" label="时间">
            <NDatePicker
              class={styles.datepicker}
              value-format="yyyy.MM.dd"
              v-model:value={searchForm.times}
              type="daterange"
              clearable
            />
          </NFormItem>
          <NFormItem>
            <NSpace>
              <NButton type="primary" onClick={onSearch}>
                搜索
              </NButton>
              <NButton type="default" onClick={onBtnReset}>
                重置
              </NButton>
            </NSpace>
          </NFormItem>
        </SaveForm>

        <NSpace style={{ paddingBottom: '12px' }}>
          <NButton
            type="primary"
            //v-auth="materialCategory/save1599962104022290433"
            onClick={() => {
              state.materail = null
              state.cityType = 'add'
              state.visiableCity = true
            }}
            disabled={state.loading}
          >
            新增分类
          </NButton>
        </NSpace>
        <NDataTable
          scroll-x="1300"
          loading={state.loading}
          columns={columns()}
          data={state.dataList}
          children-key="subMaterialCategoryList"
          default-expand-all={false}
          row-key={(row: any) => row.id}
        ></NDataTable>

        <NModal
          v-model:show={state.visiableCity}
          preset="dialog"
          showIcon={false}
          title={state.cityType === 'add' ? '新增分类' : '修改分类'}
          style={{ width: '400px' }}
          onClose={() => {
            state.materail = null
          }}
        >
          <AddCategory
            item={state.materail}
            list={state.dataList}
            isAdd={state.cityType === 'add' ? true : false}
            onClose={() => {
              state.visiableCity = false
            }}
            onHandleSuccess={() => {
              state.visiableCity = false
              if (!state.materail) {
                state.pagination.page = 1
              }
              getList()
            }}
          />
        </NModal>
      </>
    )
  }
})
