import React, { useEffect, useState, useRef } from 'react'
import {
  Tree,
  Table,
  Input,
  Button,
  Row,
  Col,
  Space,
  DatePicker,
  Popover,
  Drawer,
  Form,
  Modal,
  Switch,
  Radio,
  Image
} from 'antd'
import { useNavigate } from 'react-router-dom'
const { RangePicker } = DatePicker
const { TextArea } = Input
import PaginationCom from '@/common/Pagination'
import dayjs from 'dayjs'
import TableCom from '@/common/TableCom/index'
import { convertToAntdTreeData } from '@/utils/common.js'
import { useSelector } from 'react-redux'
import {
  getList,
  addRole,
  infoRole,
  editRole,
  changeStatus,
  delRole,
  getPowerByRoleId,
  setRolePower,
  getAllrole
} from './request'
import reload from '@/assets/images/icon/reload.png'
import reset from '@/assets/images/icon/reset.png'
import filter from '@/assets/images/icon/filter.png'
import add from '@/assets/images/icon/add.png'
import { findParents, findNodeById } from '@/utils/common'
import { PlusOutlined, CaretDownOutlined, CaretRightOutlined } from '@ant-design/icons'

const RoleList = () => {
  const [data, setData] = useState([])
  const navigate = useNavigate()
  const [page_size, setpage_size] = useState(10)
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(true)
  const [showModal, setshowModal] = useState(false)
  const [isAdd, setIsAdd] = useState(false)
  const [delMoadal, setDelModal] = useState(false)
  const [empower, setempower] = useState(false)
  const [form] = Form.useForm()
  const flag = useRef(true)
  const [checkedKeys, setcheckedKeys] = useState([])
  // 获取操作权限
  const { operationPermissionsList } = useSelector(state => state.user)

  const [selectedKeys, setSelectedKeys] = useState([])

  const treesubmit = async () => {
    const bool = await setRolePower({ role_id: id, power_list: checkedKeys })
    if (!bool) return
    init()
    setempower(false)
  }
  const [id, setId] = useState(0)
  const [initialValues, setinitialValues] = useState({
    name: '',
    remarks: ''
  })
  const [filterObj, setfilterObj] = useState({
    name: '',
    start_time: '',
    end_time: ''
  })
  const [dateVal, setDateVal] = useState('')
  const [treeData, settreeData] = useState([])

  // 过滤
  const handleFilter = (flag, val) => {
    if (flag == 'startandend') {
      let val2 = val || []
      filterObj['start_time'] = parseInt(new Date(dayjs(val2[0]).format('YYYY-MM-DD') + ' 00:00:00').getTime() / 1000)
      const endDate = new Date(dayjs(val2[1])).getDate()
      const endTime = parseInt(new Date(dayjs(val2[1]).format('YYYY-MM-') + endDate + ' 23:59:59').getTime() / 1000)
      filterObj['end_time'] = endTime
      setDateVal(val)
      if (!val2.length) {
        delete filterObj['start_time']
        delete filterObj['end_time']
      }
    } else {
      filterObj[flag] = val
    }
    for (const key in filterObj) {
      if (!filterObj[key]) {
        delete filterObj[key]
      }
    }
    setfilterObj({ ...filterObj })
    if (!val) init(filterObj)
  }
  // 重置
  const handleReset = () => {
    setfilterObj({ real_name: '', tel: '' })
    setDateVal('')
    init()
  }
  const init = async (obj = {}) => {
    console.log(obj)
    setLoading(true)
    let filter = {}
    if (obj.name) filter.name = obj.name
    if (obj.start_time && obj.end_time) {
      filter.start_time = obj.start_time
      filter.end_time = obj.end_time
    }
    const res = await getList({ page, page_size, ...filter })
    setTotal(res.total)
    setData(res.list)
    setLoading(false)
  }
  const handleEdit = async id => {
    const data = await infoRole({ id })
    setIsAdd(false)
    setshowModal(true)
    setId(id)
    // setinitialValues(data); // Update the initialValues state with the new data
    // 回显角色类型
    form.setFieldsValue({
      name: data.name,
      remarks: data.remarks,
      type: data.type.toString() // 将角色类型转换为字符串以匹配 Radio.Group 的值
    })
  }
  const onClose = () => {
    setshowModal(false)
  }
  const submitForm = async obj => {
    if (!obj.remarks) {
      delete obj.remarks // 如果备注为空，则从表单数据中删除该字段
    }
    let bool
    if (isAdd) {
      bool = await addRole({ ...obj })
    } else {
      bool = await editRole({ ...obj, id })
    }
    if (!bool) return
    init()
    setshowModal(false)
  }
  const delSuccess = async () => {
    const bool = await delRole({ id })
    bool && init()
    setDelModal(false)
  }
  const handleStatus = async (status, id) => {
    const bool = await changeStatus({ status: status ? '1' : '2', id })
    bool && init()
  }

  // // 父子关联,子未全选父有样式
  // const ontreeCheck = (keys, { checked, checkedNodes, node, halfCheckedKeys }) => {
  //   console.log(node, 'node');

  //   console.log('keys', keys);
  //   setcheckedKeys(keys);
  // };

  // 父子节点不关联,子空一个父就全空,目前实现点击父全部选中子,但当子全取消父并未取消
  const ontreeCheck = (checkedKeys, { checked, checkedNodes, node, halfCheckedKeys }) => {
    const handleCheck = parentNode => {
      const keys = []

      const traverse = currentNode => {
        keys.push(currentNode.key)

        if (currentNode.children) {
          currentNode.children.forEach(childNode => {
            traverse(childNode, currentNode.key)
          })
        }
      }

      traverse(parentNode)

      return keys
    }

    if (checked) {
      const keysToCheck = handleCheck(node)
      const parentNodes = findParents(treeData, 'key', node.key)
      setcheckedKeys([...checkedKeys.checked, ...keysToCheck, ...parentNodes])

      // 处理父节点选中状态
      if (node.parentNode) {
        ontreeCheck(checkedKeys, {
          checked: true,
          node: node.parentNode
        })
      }
    } else {
      const keysToUncheck = handleCheck(node)
      const newCheckedKeys = checkedKeys.checked.filter(key => !keysToUncheck.includes(key))
      setcheckedKeys(newCheckedKeys)

      // 处理父节点选中状态
      // if (node.parentNode && !halfCheckedKeys.includes(node.parentNode.key)) {
      //   ontreeCheck(checkedKeys, {
      //     checked: false,
      //     node: node.parentNode,
      //   });
      // }

      console.log('checkedKeys', checkedKeys)
    }
  }

  // 点击授权
  const handleEmpower = async id => {
    // 默认勾选
    setempower(true)
    setId(id)
    const data = await getPowerByRoleId({ role_id: id })
    setcheckedKeys(data)
  }
  // 获取所有权限
  const getRoleList = async () => {
    const data = await getAllrole()
    let arr = convertToAntdTreeData(data)
    settreeData(arr)
  }
  useEffect(() => {
    // if(!flag.current){
    getRoleList()
    // }else{
    // flag.current=false
    // }
  }, [])
  useEffect(() => {
    if (!showModal) {
      form.setFieldsValue({ ...initialValues })
    }
  }, [showModal])
  const columns = [
    {
      title: 'ID',
      key: 'id',
      dataIndex: 'id',
      render: (_, record, index) => {
        const cindex = page_size * (page - 1) + (index + 1)
        return <span>{cindex}</span>
      }
    },
    {
      title: '角色名称',
      key: 'name',
      align: 'center',
      dataIndex: 'name',
      width: 300
    },
    {
      title: '角色类型',
      key: 'type',
      align: 'center',
      dataIndex: 'type',
      width: 300,
      render: text => {
        if (text === 1) {
          return '管理员'
        } else if (text === 2) {
          return '老师'
        } else {
          return '未知'
        }
      }
    },
    {
      title: '备注',
      key: 'remarks',
      align: 'center',
      dataIndex: 'remarks',
      width: 300,
      render: text => (
        <Popover content={text} overlayStyle={{ maxWidth: '400px' }}>
          <div
            style={{
              display: '-webkit-box',
              WebkitLineClamp: '3',
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              textAlign: 'center'
            }}>
            {text}
          </div>
        </Popover>
      )
    },
    {
      title: '状态',
      align: 'center',
      key: 'status',
      dataIndex: 'status',
      width: 300,
      render(_, { id, status }) {
        return (
          <Switch
            defaultChecked={status}
            onChange={val => handleStatus(val, id)}
            disabled={!operationPermissionsList.includes('/jurisdiction/role/changeStatus')}
          />
        )
      }
    },
    {
      title: '创建时间',
      key: 'create_time',
      align: 'center',
      dataIndex: 'create_time'
    },
    {
      title: '操作',
      key: 'handle',
      align: 'center',
      dataIndex: 'handle',
      width: 400,
      render: (_, record) => {
        return (
          <Space>
            {operationPermissionsList.includes('/jurisdiction/role/getInfoById') && (
              <Button onClick={() => handleEdit(record.id)}>编辑</Button>
            )}
            {operationPermissionsList.includes('/jurisdiction/role/getPowerByRoleId') && (
              <Button onClick={() => handleEmpower(record.id)}>授权</Button>
            )}
            {operationPermissionsList.includes('/jurisdiction/role/del') && (
              <Button
                onClick={() => {
                  setId(record.id)
                  setDelModal(true)
                }}>
                删除
              </Button>
            )}
          </Space>
        )
      }
    }
  ]
  return (
    <div>
      <Row justify={'space-between'}>
        <Col className="form-devices-inline">
          <Form form={form} layout="inline">
            <Form.Item label="角色名称">
              <Input
                autoComplete="off"
                allowClear
                value={filterObj.name}
                onChange={ev => handleFilter('name', ev.target.value)}
                placeholder="请输入角色名称"
                id="name"></Input>
            </Form.Item>
            <Form.Item label="创建时间">
              <RangePicker
                value={dateVal}
                onChange={ev => handleFilter('startandend', ev)}
                id="createTime"></RangePicker>
            </Form.Item>
            <Space>
              <Button
                type="primary"
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '11px',
                      height: '10px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={reset} />
                  </span>
                }
                onClick={handleReset}>
                重置
              </Button>
              <Button
                type="primary"
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={filter} />
                  </span>
                }
                ghost
                onClick={() => {
                  setPage(1)
                  init(filterObj)
                  // Object.values(filterObj).some((item) => item) ? init(filterObj) : init();
                }}>
                筛选
              </Button>
              <Button
                type="primary"
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '10px',
                      height: '12px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={reload} />
                  </span>
                }
                onClick={() => {
                  init(filterObj)
                }}>
                刷新
              </Button>
              {/* <Button
                type='primary'
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={add} />
                  </span>
                }
                onClick={() => {
                  setIsAdd(true);
                  setshowModal(true);
                  form.resetFields();
                }}
              >
                添加
              </Button> */}
            </Space>
          </Form>
        </Col>
        <Col>
          <Space>
            {operationPermissionsList.includes('/jurisdiction/role/add') && (
              <Button
                type="primary"
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={add} />
                  </span>
                }
                onClick={() => {
                  setIsAdd(true)
                  setshowModal(true)
                  form.resetFields()
                }}>
                添加
              </Button>
            )}
          </Space>
        </Col>
      </Row>
      <br />
      {TableCom({ columns, loading, data })}
      <Modal
        mask={false}
        centered
        open={delMoadal}
        onOk={delSuccess}
        onCancel={() => setDelModal(false)}
        footer={(_, { OkBtn, CancelBtn }) => {
          return (
            <Row justify={'center'} className="delModal" style={{ marginBottom: '30px' }}>
              <Space size={20}>
                <CancelBtn />
                <OkBtn />
              </Space>
            </Row>
          )
        }}
        okText="确认">
        <p style={{ textAlign: 'center', padding: '30px 0 18px', fontSize: 16 }}>角色将永久删除，是否继续?</p>
      </Modal>
      <br />
      <PaginationCom
        total={total}
        page_size={page_size}
        setpage_size={setpage_size}
        page={page}
        setPage={setPage}
        init={init}
        filterObj={filterObj}
      />
      <Drawer placement="right" onClose={onClose} open={showModal} mask={false}>
        <Form form={form} onFinish={submitForm} labelCol={{ span: 6 }}>
          <Form.Item
            name="name"
            label="角色名称"
            rules={[
              { required: true, message: '请输入角色名称' },
              { max: 50, message: '角色名称最多可输入50个字符' }
            ]}>
            <Input autoComplete="off" placeholder="请输入角色名称"></Input>
          </Form.Item>
          <Form.Item name="type" label="角色类型" rules={[{ required: true, message: '请选择角色类型' }]}>
            <Radio.Group style={{ textAlign: 'center' }}>
              <Radio value={'1'}>管理员</Radio>
              <Radio value={'2'}>老师</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            name="remarks"
            label="备注"
            rules={[
              // { required: !isAdd, message: '请输入备注' },
              { required: false, message: '请输入备注' }, //备注非必选
              { max: 100, message: '备注最多可输入100个字符' } // 设置最大长度为100
            ]}>
            <TextArea
              autoSize={{
                minRows: 5,
                maxRows: 8
              }}
              placeholder="请输入备注"></TextArea>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 12, span: 16 }}>
            <Space size={20}>
              <Button onClick={() => setshowModal(false)}>取消</Button>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
      <Drawer placement="right" open={empower} onClose={() => setempower(false)} mask={false}>
        <Form labelCol={{ span: 6 }}>
          <Form.Item name="power_list" style={{ padding: 10, paddingTop: 0 }}>
            <Tree
              checkable
              checkedKeys={checkedKeys}
              defaultExpandAll={false} //让授权后的弹窗只展示根标签
              treeData={treeData}
              // multiple // 支持多选。当父子不关联,添加后,点击父,不能控制所有子
              // showLine //删除这里,树形结构左侧的下拉线消失,图标从＋－更改为默认的△
              checkStrictly // 开启后,父子节点不关联(子空一个,父就空)
              onCheck={ontreeCheck}
            />
          </Form.Item>
          <Form.Item
            wrapperCol={{ offset: 7, span: 16 }}
            style={{
              position: 'fixed',
              bottom: 0,
              width: '30%',
              background: '#fff',
              paddingBottom: 20,
              margin: 0
            }}>
            <Space size={20}>
              <Button onClick={() => setempower(false)}>取消</Button>
              <Button type="primary" htmlType="submit" onClick={treesubmit}>
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  )
}

export default RoleList
