import React, { Component } from 'react'
import {
    Button,
    Card,
    Descriptions,
    Divider,
    Form,
    Input,
    List,
    message as Message,
    Popconfirm,
    Select,
    Switch,
    Tag,
} from 'antd'
import {
    AntIcon,
    Auth,
    Container,
    Image,
    ModalForm,
    QueryList,
    QueryTableActions,
    QueryTreeLayout,
} from 'components'
import { api } from 'common/api'
import { toCamelCase } from 'util/format'
import { isEqual } from 'lodash'
import getDictData from 'util/dic'
import FormBody from './form'
import Selector from './selector'
import DataForm from './data'

// 配置页面所需接口函数
const apiAction = {
    tree: api.getOrgTree,
    page: api.houseMemberPage,
    add: api.houseMemberAdd,
    edit: api.houseMemberEdit,
    delete: api.houseMemberDelete,

    changeStatus: api.houseMemberChangeStatus,
    resetPwd: api.sysUserResetPwd,

    grantData: api.houseMemberGrantData,
}

// 用于弹窗标题
const name = '人员'

export default class index extends Component {
    state = {
        codes: {
            sex: [],
            commonStatus: [],
        },
    }

    // 表格实例
    list = React.createRef()

    // 新增窗口实例
    addForm = React.createRef()
    // 编辑窗口实例
    editForm = React.createRef()

    dataForm = React.createRef()
    // 树选中节点
    selectId = undefined

    selectorModal = React.createRef()

    /**
     * 阻止外部组件引发的渲染,提升性能
     * 可自行添加渲染条件
     * [必要]
     * @param {*} props
     * @param {*} state
     * @returns
     */
    shouldComponentUpdate(props, state) {
        return !isEqual(this.state, state)
    }

    /**
     * 加载字典数据,之后开始加载表格数据
     * 如果必须要加载字典数据,可直接对表格设置autoLoad=true
     */
    componentDidMount() {
        this.list.current.onLoading()
        getDictData('sex', 'common_status').then(codes => {
            this.setState({ codes }, () => {
                this.list.current.onLoadData()
            })
        })
    }

    /**
     * 调用加载数据接口,可在调用前对query进行处理
     * [异步,必要]
     * @param {*} params
     * @param {*} query
     * @returns
     */
    loadData = async (params, query) => {
        query = {
            ...query,
            sysEmpParam: {
                orgId: this.selectId,
            },
        }

        const { data } = await apiAction.page({
            ...params,
            ...query,
        })
        return data
    }

    /**
     * 调用树结构数据接口
     * [异步,必要]
     * @returns
     */
    loadTreeData = async () => {
        const { data } = await apiAction.tree()
        return data
    }

    /**
     * 树节点选中事件
     * [必要]
     * @param {*} id
     */
    onSelectTree(id) {
        this.selectId = id
        this.list.current.onReloadData()
    }

    /**
     * 绑定字典数据
     * @param {*} code
     * @param {*} name
     * @returns
     */
    bindCodeValue(code, name) {
        name = toCamelCase(name)
        const codes = this.state.codes[name]
        if (codes) {
            const c = codes.find(p => p.code == code)
            if (c) {
                return c.value
            }
        }
        return null
    }

    /**
     * 打开新增/编辑弹窗
     * @param {*} modal
     * @param {*} id
     */
    onOpen(modal, id) {
        modal.current.open({
            orgId: this.selectId,
            id,
        })
    }

    /**
     * 对表格上的操作进行统一处理
     * [异步]
     * @param {*} action
     * @param {*} successMessage
     */
    async onAction(action, successMessage) {
        this.list.current.onLoading()
        try {
            await action
            Message.success(successMessage)
            this.list.current.onReloadData()
        } catch {
            this.list.current.onLoaded()
        }
    }

    /**
     * 删除
     * @param {*} id
     */
    onDelete(id) {
        this.onAction(apiAction.delete({ id }), '删除成功')
    }

    //#region 自定义方法
    renderItem(record) {
        const {
            id,
            account,
            name,
            nickName,
            avatar,
            sex,
            phone,
            email,
            status,
            roleCode,
            roleName,
            orgName,
        } = record
        return (
            <List.Item
                key={id}
                actions={[
                    <QueryTableActions>
                        <Auth auth="houseMember:edit">
                            <a onClick={() => this.onOpen(this.editForm, id)}>编辑</a>
                        </Auth>
                        <Auth auth="houseMember:delete">
                            <Popconfirm
                                placement="topRight"
                                title="是否确认删除"
                                onConfirm={() => this.onDelete(id)}
                            >
                                <a>删除</a>
                            </Popconfirm>
                        </Auth>
                        <Auth auth="houseMember:resetPwd">
                            <a onClick={() => this.onResetPassword(id)}>重置密码</a>
                        </Auth>
                        <Auth auth="houseMember:grantData">
                            <a onClick={() => this.onOpen(this.dataForm, id)}>授权额外数据</a>
                        </Auth>
                    </QueryTableActions>,
                ]}
            >
                <List.Item.Meta
                    avatar={
                        <>
                            <Image
                                type="avatar"
                                shape="square"
                                size={48}
                                id={avatar}
                                icon={<AntIcon type="user" />}
                            />
                            {roleCode && roleCode.includes('house_security_manager') && (
                                <Button
                                    size="small"
                                    type="primary"
                                    className="block w-100-p mt-xxs"
                                    onClick={() => this.onOpen(this.selectorModal, id)}
                                >
                                    选房
                                </Button>
                            )}
                        </>
                    }
                    title={
                        <>
                            {nickName || name}
                            {roleName &&
                                roleName.split(',').map((item, i) => (
                                    <span key={i}>
                                        <Divider type="vertical" />
                                        <Tag color="pink">{item}</Tag>
                                    </span>
                                ))}
                        </>
                    }
                    description={account}
                />
                <Descriptions className="flex-1" column={2}>
                    <Descriptions.Item label="部门">{orgName}</Descriptions.Item>
                    <Descriptions.Item label="性别">
                        {this.bindCodeValue(sex, 'sex')}
                    </Descriptions.Item>
                    <Descriptions.Item label="手机">{phone || '未设置'}</Descriptions.Item>
                    <Descriptions.Item label="邮箱">{email || '未设置'}</Descriptions.Item>
                </Descriptions>
                <div className="yo-list-content--h">
                    <Auth auth="houseMember:changeStatus">
                        <div className="yo-list-content--h--item text-center">
                            <Switch
                                checked={!status}
                                checkedChildren={this.bindCodeValue(0, 'common_status')}
                                unCheckedChildren={this.bindCodeValue(1, 'common_status')}
                                onChange={checked => this.onSetUserStatus(id, checked)}
                            />
                        </div>
                    </Auth>
                </div>
            </List.Item>
        )
    }

    onSetUserStatus(id, checked) {
        this.onAction(
            apiAction.changeStatus({
                id,
                status: +!checked,
            }),
            '设置成功'
        )
    }

    onResetPassword(id) {
        this.onAction(apiAction.resetPwd({ id }), '重置成功')
    }
    //#endregion

    render() {
        return (
            <QueryTreeLayout
                loadData={this.loadTreeData}
                defaultExpanded={true}
                onSelect={key => this.onSelectTree(key)}
            >
                <Container mode="fluid">
                    <Card bordered={false}>
                        <QueryList
                            ref={this.list}
                            autoLoad={false}
                            loadData={this.loadData}
                            query={
                                <Auth auth="houseMember:page">
                                    <Form.Item label="关键词" name="searchValue">
                                        <Input
                                            autoComplete="off"
                                            placeholder="请输入姓名、账号、手机号"
                                            className="w-200"
                                        />
                                    </Form.Item>
                                    <Form.Item label="状态" name="searchStatus">
                                        <Select
                                            allowClear
                                            placeholder="请选择状态"
                                            className="w-200"
                                        >
                                            {this.state.codes.commonStatus.map(item => {
                                                return (
                                                    <Select.Option
                                                        key={item.code}
                                                        value={item.code}
                                                    >
                                                        {item.value}
                                                    </Select.Option>
                                                )
                                            })}
                                        </Select>
                                    </Form.Item>
                                    <Form.Item label="区域范围" name="treeNodeDataScope">
                                        <Select
                                            allowClear
                                            placeholder="请选择状态"
                                            className="w-200"
                                            defaultValue={1}
                                        >
                                            <Select.Option value={1}>只看本级</Select.Option>
                                            <Select.Option value={2}>查看本级及以下</Select.Option>
                                        </Select>
                                    </Form.Item>
                                </Auth>
                            }
                            operator={
                                <Button
                                    icon={<AntIcon type="plus" />}
                                    onClick={() => this.onOpen(this.addForm)}
                                >
                                    新增
                                    {name}
                                </Button>
                            }
                            renderItem={record => this.renderItem(record)}
                        />
                    </Card>
                </Container>

                <ModalForm
                    title={`新增${name}`}
                    action={apiAction.add}
                    ref={this.addForm}
                    onSuccess={() => this.list.current.onReloadData()}
                >
                    <FormBody mode="add" />
                </ModalForm>

                <ModalForm
                    title={`编辑${name}`}
                    action={apiAction.edit}
                    ref={this.editForm}
                    onSuccess={() => this.list.current.onReloadData()}
                >
                    <FormBody mode="edit" />
                </ModalForm>

                <ModalForm
                    title="数据授权"
                    action={apiAction.grantData}
                    ref={this.dataForm}
                    onSuccess={() => this.list.current.onReloadData()}
                >
                    <DataForm />
                </ModalForm>

                <ModalForm
                    bodyStyle={{ padding: 0 }}
                    footer={false}
                    width="80%"
                    ref={this.selectorModal}
                >
                    <Selector />
                </ModalForm>
            </QueryTreeLayout>
        )
    }
}
