import React, { useState, useEffect, useCallback } from 'react';
import PropTypes from 'prop-types';
import getCustomHeader from '@/components/token-header';
import PageHead from '@/components/page-head';
import { ajax } from '@/utils';
import {
    Button,
    Table,
    Dialog,
    Form,
    Input,
    Tree,
    Message,
  } from '@alifd/next';
import styles from './index.module.scss';
const SEARCH = ['id','name','code'];
const SEARCHLABEL = {id:'id',name:'名称',code:'角色Code'};
const { Column } = Table;
const FormItem = Form.Item;
const TreeNode = Tree.Node;
const ListRoles = ({ roles, permission }) => {
  const [editId, setEditId] = useState({id:'', type: ''});
  const [editData, setEditData] = useState({});
  const [rolesData, setRolesData] = useState([]);
  const [dataType, setDataType] = useState(true);
  const dataSource = dataType ? roles : rolesData;
  const treeRender = (permissionValue) => {
    const result = permissionValue.map(item => {
      if (item.children && item.children.length) {
        return (
          <TreeNode key={item.id} label={item.name}>
            {treeRender(item.children)}
          </TreeNode>
        )
      } else {
        return <TreeNode key={item.id} label={item.name}></TreeNode>
      }
    });
    return result;
  }
  const treeCheck = (value) => {
    const result = [];
    value.forEach(item => {
      if (item.children && item.children.length) {
        const node = treeCheck(item.children);
        result.push(...node);
      } else {
        if (item.having) result.push(item.id);
      }
    });
    return result;
  }
  const refreshList = async() => {
    const result = await ajax({
      api: 'getRoleList',
      method: 'get',
      type: 'json',
      data: {},
      contentType: 'application/json'
    });
    if (result.success) {
      setRolesData(result.result);
    } else {
      Message.error(result.message);
    }
  }
  const editDialog = () => {
    let editPermission=[], checkPermission=[], treePermission=[];
    treePermission = editData && editData.permissionTree;
    const treeData = editId.type === 'edit' ? treePermission : permission;
    if (editId.type === 'edit') {
      editPermission = treeCheck(treeData);
      checkPermission = editPermission;
    }
    if (!treeData) return;
    return (
      <Dialog
        title={`${editId.type === 'add' ? '新增角色' : '角色编辑' }`}
        visible={true}
        footer={false}
        onClose={() => setEditId({id: '', type: ''})}
        style={{paddingBottom: '25px'}}
      >
        <Form labelAlign="inset">
          <FormItem label='name:' key='name' required>
            <Input
              id='name'
              name='name'
              defaultValue={editId.type === 'edit' && editData ? editData.name : ''}
              style={{width: '400px'}}
            />
          </FormItem>
          <FormItem label='code:' key='code' required>
          <Input
            id='code'
            name='code'
            defaultValue={editId.type === 'edit' && editData ? editData.code : ''}
            style={{width: '400px'}}
            disabled={editId.type==='edit'}
          />
          </FormItem>
          <FormItem label='permissionList' key='permissionList'>
            <Tree
              checkable
              style={{maxHeight: '45vh', overflow:'scroll'}}
              defaultCheckedKeys={editPermission}
              onCheck={(keys, info) => {
                checkPermission = [...keys, ...info.indeterminateKeys];
              }}
            >
              {treeRender(treeData)}
            </Tree>
          </FormItem>
          <Form.Submit
              type="primary"
              validate
              style={{position: 'absolute', right: '20px'}}
              onClick={async(successData, errorData) => {
                const data = {...successData, permissionIds: checkPermission};
                const apiName = editId.type === 'edit' ? 'updateRole' : 'addRole';
                if (editId.type === 'edit') data.id = editId.id;
                if (!errorData) {
                  const result = await ajax({
                    api: apiName,
                    method: 'post',
                    type: 'json',
                    data: JSON.stringify(data),
                    contentType: 'application/json',
                    headers: getCustomHeader()
                  });
                  setDataType(false);
                  if (result.success) {
                    refreshList();
                  } else {
                    Message.error(result.message);
                  }
                  setEditId({id: '', type: ''});
                } else {
                  console.log(errorData);
                }
              }}
            >
              {editId.type === 'edit' ? '保存' : '添加'}
            </Form.Submit>
        </Form>
      </Dialog>
    )
  }

  const editRender = (value, index, record) => {
    return (
      <>
        <span onClick={async() => {
          const result = await ajax({
            api: 'getRole',
            method: 'get',
            type: 'json',
            data: {id: record.id},
            contentType: 'application/json'
          });
          if (result.success) {
            await setEditData(result.result);
            await setEditId({id: record.id, type: 'edit'});
          }
          }
        }
        >编辑</span>
        <span onClick={async() => {
            Dialog.alert({
              title: '提醒',
              content: `是否确认删除id为${record.id}的角色`,
              onOk: async() => {
                const result = await ajax({
                  api: 'removeRole',
                  method: 'post',
                  type: 'json',
                  data: JSON.stringify({id: record.id}),
                  contentType: 'application/json',
                  headers: getCustomHeader()
                });
                setDataType(false);
                if (!result.success) {
                  Message.error(result.message);
                };
                refreshList();
              },
              onCancel: () => console.log('cancel')
            });
        }}>删除</span>
      </>
    )
  }
  return (
    <div className={styles.listRolesBox}>
    <PageHead title="角色管理" />
      <div className={styles.contentBox}>
        <div className={styles.contentHead}>
        <Form inline labelAlign='inset'>
        {
          SEARCH.map(item => {
            return (
              <FormItem label={`${SEARCHLABEL[item]}:`} key={item}>
                <Input style={{width:'200px'}} id={item} name={item} />
              </FormItem>
            )
          })
        }
        <Form.Submit type="primary" validate onClick={async(successData, errorData) => {
          if (!errorData) {
            const result = await ajax({
              api: 'getRoleList',
              method: 'get',
              type: 'json',
              data: {...successData},
              contentType: 'application/json'
            });
            if (result.success) {
              setRolesData(result.result);
            } else {
              Message.error(result.message);
            }
            setDataType(false);
          } else {
            console.log(errorData);
          }
        }}>
          查询
        </Form.Submit>
      </Form>
          <Button
          className={styles.addButton}
          type="primary"
          onClick={() => {
            setEditId({id: '', type: 'add'});
          }}
        >
          添加角色
        </Button>
        </div>
        <Table hasBorder={false} dataSource={dataSource}>
          <Column title="id" dataIndex="id" width={"20%"} />
          <Column title="名称" dataIndex="name" width={"20%"} />
          <Column title="角色Code" dataIndex="code" width={"20%"} />
          <Column title="操作" cell={editRender} dataIndex="identityCardNumber" width={"40%"} />
        </Table>
        {editId.type && editDialog()}
      </div>
    </div>
  );
};

export default ListRoles;
