import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  DataTableRowKey,
  NButton,
  NCascader,
  NDataTable,
  NDatePicker,
  NFormItem,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTag,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import {
  sysApplicationPage,
  sysRolePage,
  sysRoleRemove,
  sysUserDevicePage,
  sysUserDeviceRemove
} from '../api'
import { formatDataList } from '@/utils/urlUtils'
import { getTimes } from '@/utils/dateUtil'
import { filterClientType } from '@/utils/filters'
import { clientTypeArray } from '@/utils/searchArray'

export default defineComponent({
  name: 'subsidy-list',
  setup() {
    const state = reactive({
      loading: false,
      clientTypeList: [] as any,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        keyword: null,
        createTime: null as any,
        clientType: null,
        deviceNum: null
      },
      dataList: [] as any,
      applyList: [] as any,
      visiableRole: false,
      roleOperation: 'add',
      roleData: {} as any
    })
    const dialog = useDialog()
    const message = useMessage()

    const checkedRowKeysRef = ref<DataTableRowKey[]>([])
    const handleCheck = (rowKeys: DataTableRowKey[]) => {
      console.log('🚀 ~ rowKeys', rowKeys)
      checkedRowKeysRef.value = rowKeys
    }

    const columns: any = () => {
      return [
        {
          type: 'selection'
        },
        {
          title: '编号',
          key: 'id'
        },
        {
          title: '用户姓名',
          key: 'nickname'
        },
        {
          title: '手机号',
          key: 'phone'
        },
        {
          title: '设备号',
          key: 'deviceNum'
        },
        {
          title: '客户端',
          key: 'clientType',
          render(row: any) {
            return filterClientType(row.clientType)
          }
        },
        {
          title: '绑定时间',
          key: 'createTime'
        },
        {
          title: '操作',
          key: 'operation',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  size="small"
                  text
                  //v-auth="sysUserDevice/removeIds1633324668827324417"
                  onClick={() => {
                    onRemove(row)
                  }}
                >
                  解除绑定
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

    const onRemove = (row: any): void => {
      console.log(row, 'row')
      dialog.warning({
        title: '警告',
        content: `是否确定解除绑定？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await sysUserDeviceRemove([row.id])
            getList()
            message.success('解除绑定成功')
          } catch {}
        }
      })
    }

    const getList = async () => {
      try {
        state.loading = true

        const { createTime, ...res } = state.searchForm
        const { data } = await sysUserDevicePage({
          ...state.pagination,
          ...res,
          ...getTimes(createTime, ['bindStartTime', 'bindEndTime'], 'YYYY-MM-DD')
        })
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }

    const getApplyList = async (parentId = 0) => {
      try {
        const { data } = await sysApplicationPage({
          page: 1,
          rows: 999,
          leafQuery: true,
          parentId
        })
        state.applyList = formatDataList(data.rows || [], 'bizApps')
      } catch {}
    }

    const handleDeletes = () => {
      console.log(checkedRowKeysRef.value)
      dialog.warning({
        title: '警告',
        content: `是否确认批量解除绑定?`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            const res = await sysUserDeviceRemove(checkedRowKeysRef.value)
            message.success('解除绑定成功')
            checkedRowKeysRef.value = []
            getList()
          } catch (e: any) {}
        }
      })
    }

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

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

    onMounted(() => {
      clientTypeArray.forEach((item: any) => {
        if (item.value != 'BACKEND') {
          state.clientTypeList.push(item)
        }
      })
      getList()
      getApplyList()
    })
    return () => (
      <div class="system-menu-container">
        <h2>设备号管理</h2>

        <SaveForm
          ref={saveForm}
          model={state.searchForm}
          onSubmit={onSubmit}
          onSetModel={(val: any) => (state.searchForm = val)}
        >
          <NFormItem label="搜索" path="appId">
            <NInput
              v-model:value={state.searchForm.keyword}
              placeholder="请输入姓名、手机号"
              clearable
            />
          </NFormItem>
          <NFormItem label="设备号" path="roleName">
            <NInput
              v-model:value={state.searchForm.deviceNum}
              placeholder="请输入设备号"
              clearable
            />
          </NFormItem>
          <NFormItem label="客户端" path="cityCode">
            <NSelect
              v-model={[state.searchForm.clientType, 'value']}
              placeholder="请选择客户端"
              options={state.clientTypeList}
              clearable
            />
          </NFormItem>
          <NFormItem path="createTime" label="绑定时间">
            <NDatePicker
              type="daterange"
              v-model:formattedValue={state.searchForm.createTime}
              valueFormat="yyyy-MM-dd"
              startPlaceholder="绑定开始日期"
              endPlaceholder="绑定结束日期"
              clearable
            />
          </NFormItem>
          <NFormItem>
            <NSpace>
              <NButton type="primary" onClick={onSearch}>
                搜索
              </NButton>
              <NButton type="default" onClick={onBtnReset}>
                重置
              </NButton>
            </NSpace>
          </NFormItem>
        </SaveForm>

        <div class={['section-container']}>
          <NSpace style={{ paddingBottom: '12px' }}>
            <NButton
              type="primary"
              //v-auth="sysUserDevice/removeIds1631499811567173634"
              onClick={handleDeletes}
            >
              批量解除绑定
            </NButton>
          </NSpace>

          <NDataTable
            rowKey={(row: any) => row.id}
            loading={state.loading}
            v-model:checkedRowKeys={checkedRowKeysRef.value}
            onUpdate:checked-row-keys={handleCheck}
            columns={columns()}
            data={state.dataList}
          ></NDataTable>
          <Pagination
            v-model:page={state.pagination.page}
            v-model:pageSize={state.pagination.rows}
            v-model:pageTotal={state.pagination.pageTotal}
            onList={getList}
            sync
          ></Pagination>
        </div>
      </div>
    )
  }
})
