import { NavLink, useLocation } from 'react-router-dom'
import { useState, useEffect } from 'react'
import { Row, Col, Space, Button, Table, Select, TreeSelect, Typography, Modal, App, Form, Input } from 'antd'
import dayjs from 'dayjs'
import { isEmpty } from '@/utils/commons'
import { useTranslation } from 'react-i18next'
import useFormStore from '@/stores/Form'
import useReservationStore from '@/stores/Reservation'
import SearchForm from '@/components/SearchForm'

const { Title } = Typography

const { SHOW_PARENT } = TreeSelect

const permissionData = [
  {
    title: '机票管理',
    value: '0-0',
    key: '0-0',
    children: [
      {
        title: '录入机票价格',
        value: '0-0-0',
        key: '0-0-0',
      },
    ],
  },
  {
    title: '产品管理',
    value: '0-1',
    key: '0-1',
    children: [
      {
        title: '录入产品价格',
        value: '0-1-0',
        key: '0-1-0',
      },
      {
        title: '新增产品描述',
        value: '0-1-1',
        key: '0-1-1',
      },
      {
        title: '复制供应商产品信息',
        value: '0-1-2',
        key: '0-1-2',
      },
    ],
  },
  {
    title: '账号管理',
    value: '2-1',
    key: '2-1',
    children: [
      {
        title: '重置账号密码',
        value: '2-1-0',
        key: '2-1-0',
      },
      {
        title: '禁用账号',
        value: '2-1-1',
        key: '2-1-1',
      },
      {
        title: '分配账号角色',
        value: '2-1-2',
        key: '2-1-2',
      },
    ],
  },
];

function Management() {
  const { t } = useTranslation()
  const accountListColumns = [
    {
      title: t('account:username'),
      dataIndex: 'username',
      key: 'account:username',
    },
    {
      title: t('account:realname'),
      dataIndex: 'realname',
      key: 'account:realname',
    },
    {
      title: t('account:email'),
      dataIndex: 'email',
      key: 'account:email'
    },
    {
      title: t('account:role'),
      dataIndex: 'role',
      key: 'account:role'
    },
    {
      title: t('account:lastLogin'),
      dataIndex: 'lastLogin',
      key: 'account:lastLogin'
    },
    {
      title: t('account:action'),
      key: 'account:action',
      dataIndex: 'account:action',
      render: actionRender
    },
  ]

  function actionRender() {
    return (
      <Space size='middle'>
        <Button type='link' onClick={() => console.info('account:action.disable')}>{t('account:action.disable')}</Button>
        <Button type='link' onClick={() => console.info('account:action.resetPassword')}>{t('account:action.resetPassword')}</Button>
        <Button type='link' onClick={() => console.info('account:action.assignRole')}>{t('account:action.assignRole')}</Button>
      </Space>
    )
  }


	const onPermissionChange = (newValue) => {
    console.log('onChange ', newValue);
    setPermissionValue(newValue);
  }
  const [permissionValue, setPermissionValue] = useState(['0-0-0'])
  const [isAccountModalOpen, setAccountModalOpen] = useState(false)
  const [isRoleModalOpen, setRoleModalOpen] = useState(false)
  const [dataLoading, setDataLoading] = useState(false)
  const [accountList, setaccountList] = useState([
    {
      username: 'bjyiran',
      realname: '怡小芳',
      email: 'xiaofang@yiran.com',
      role: '国内供应商',
      lastLogin: '2024-06-12 13:53'
    },
    {
      username: 'int-robin',
      realname: 'Robin',
      email: 'robin@int.com',
      role: '海外供应商',
      lastLogin: '2024-06-12 13:53'
    },
    {
      username: 'betty-wu',
      realname: '吴雪',
      email: 'betty@hainatravel.com',
      role: '客服组',
      lastLogin: '2024-06-12 13:53'
    },
    {
      username: 'lancy',
      realname: '吴金倩',
      email: 'lancy@hainatravel.com',
      role: '产品组',
      lastLogin: '2024-06-12 13:53'
    },
    {
      username: 'LYJ',
      realname: '廖一军',
      email: 'lyj@hainatravel.com',
      role: 'Web 开发组,海外测试供应商',
      lastLogin: '2024-06-12 13:53'
    }
  ])

  const formValuesToSub = useFormStore((state) => state.formValuesToSub)

  const [form] = Form.useForm()
  const [fetchAllGuideList, fetchReservationList, reservationList, reservationPage, cityList, selectReservation, getCityListByReservationId] =
    useReservationStore((state) =>
      [state.fetchAllGuideList, state.fetchReservationList, state.reservationList, state.reservationPage, state.cityList, state.selectReservation, state.getCityListByReservationId])

  const { notification } = App.useApp()

  const handleAccountOk = () => {
  }

  const handleAccountCancel = () => {
    setAccountModalOpen(false)
  }

  const handleRoleOk = () => {
  }

  const handleRoleCancel = () => {
    setRoleModalOpen(false)
  }

  const onFinish = (values) => {
    console.log(values)
  }

  const onFinishFailed = (error) => {
    console.log('Failed:', error)
    // form.resetFields()
  }

  // 默认重新搜索第一页，所有状态的计划
  const onSearchClick = (current=1, status=null) => {
  }

  return (
    <>
      <Modal
        centered
        open={isAccountModalOpen} onOk={handleAccountOk} onCancel={handleAccountCancel}
      >
        <Form
        name='basic'
        form={form}
        layout='vertical'
        size='large'
        style={{
          maxWidth: 600,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete='off'
      >
        <Form.Item><Title level={2}>{t('account:management.newAccount')}</Title></Form.Item>
        <Form.Item
          label={t('account:management.username')}
          name='currentPassword'
          rules={[
            {
              required: true,
              message: t('account:Validation.CurrentPassword'),
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label={t('account:management.realname')}
          name='newPassword'
          rules={[
            {
              required: true,
              message: t('account:Validation.NewPassword'),
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label={t('account:management.email')}
          name='reenterPassword'
          rules={[
            {
              required: true,
              message: t('account:Validation.ReenterPassword'),
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item label={t('account:management.role')}>
        <Select>
          <Select.Option value='1'>客服组</Select.Option>
          <Select.Option value='2'>产品组</Select.Option>
          <Select.Option value='3'>国内供应商</Select.Option>
          <Select.Option value='4'>海外供应商</Select.Option>
          <Select.Option value='5'>技术研发部</Select.Option>
          <Select.Option value='0' disabled>系统管理员</Select.Option>
        </Select>
      </Form.Item>
      </Form>
      </Modal>
      {/* Role Edit */}
      <Modal
        centered
        open={isRoleModalOpen} onOk={handleRoleOk} onCancel={handleRoleCancel}
      >
        <Form
        name='basic'
        form={form}
        layout='vertical'
        size='large'
        style={{
          maxWidth: 600,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete='off'
      >
        <Form.Item><Title level={2}>{t('account:management.newRole')}</Title></Form.Item>
        <Form.Item
          label={t('account:management.roleName')}
          name='currentPassword'
          rules={[
            {
              required: true,
              message: t('account:Validation.CurrentPassword'),
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item label={t('account:management.permission')}>
        <TreeSelect treeData={permissionData} value={permissionValue}
        showSearch
        allowClear
        multiple
        treeDefaultExpandAll
        treeLine={true}
        onChange={onPermissionChange}
    // treeCheckable={true}
    showCheckedStrategy={SHOW_PARENT}
    placeholder={'Please select'}
    style={{
      width: '100%',
    }} />
      </Form.Item>
      </Form>
      </Modal>
      <Space direction='vertical' style={{ width: '100%' }}>
        <Title level={3}>{t('account:management.tile')}</Title>
        <SearchForm
          // initialValue={
          //   {
          //   }
          // }
          fieldsConfig={{
            shows: ['referenceNo', 'dates'],
            fieldProps: {
              dates: { label: t('group:ArrivalDate') },
            },
          }}
          onSubmit={(err, formVal, filedsVal) => {
            setDataLoading(true)
            fetchReservationList(formVal)
              .catch(ex => {
                notification.error({
                  message: 'Notification',
                  description: ex.message,
                  placement: 'top',
                  duration: 4,
                })
              })
              .finally(() => {
                setDataLoading(false)
              })
          }}
        />
        <Row>
          <Col span={24}>
            <Space>
              <Button onClick={() => setAccountModalOpen(true)}>{t('account:management.newAccount')}</Button>
              <Button onClick={() => setRoleModalOpen(true)}>{t('account:management.newRole')}</Button>
            </Space>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <Table
              bordered
              loading={dataLoading}
              pagination={{
                showQuickJumper: true,
                showLessItems: true,
                showSizeChanger: true,
                showTotal: (total) => { return `总数：${total}` }
              }}
              onChange={(pagination) => {onSearchClick(pagination.current)}}
              columns={accountListColumns} dataSource={accountList}
            />
          </Col>
        </Row>
      </Space>
    </>
  )
}

export default Management
