import React, { Component } from 'react'
import { Button, Radio, Card, Form, Input, message as Message, Popconfirm } from 'antd'
import {
    AntIcon,
    Auth,
    Container,
    ModalForm,
    QueryTable,
    QueryTableActions,
    QueryTreeLayout,
} from 'components'
import { api } from 'common/api'
import auth from 'components/authorized/handler'
import { toCamelCase } from 'util/format'
import { isEqual } from 'lodash'
import getDictData from 'util/dic'
import FormBody from './form'

const apiAction = {
    tree: api.getAreaTree,
    page: api.getHouseProjectPage,
    add: api.houseProejctAdd,
    edit: api.houseProejctEdit,
    delete: api.houseProejctDelete,
}

const name = '项目'

export default class index extends Component {
    state = {
        codes: {
            houseType: [],
        },
        type: 1,
    }

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

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

    // 树选中节点
    selectCode = undefined
    columns = [
        {
            title: '项目名称',
            dataIndex: 'name',
            width: 150,
            sorter: true,
        },
        {
            title: '社区',
            dataIndex: 'areaName',
            width: 100,
            sorter: true,
        },
        {
            title: '备注',
            dataIndex: 'note',
            width: 150,
            sorter: true,
        },
        {
            title: '类型',
            dataIndex: 'type',
            sorter: true,
            width: 80,
            render: text => <>{this.bindCodeValue(text, 'house_type')}</>,
        },
    ]
    /**
     * 构造函数,在渲染前动态添加操作字段等
     * @param {*} props
     */
    constructor(props) {
        super(props)

        const flag = auth({ houseProjectInfo: [['edit'], ['delete']] })

        if (flag) {
            this.columns.push({
                title: '操作',
                width: 150,
                dataIndex: 'actions',
                render: (text, record) => (
                    <QueryTableActions>
                        <Auth auth="houseProjectInfo:edit">
                            <a onClick={() => this.onOpen(this.editForm, record.id)}>编辑</a>
                        </Auth>
                        <Auth auth="houseProjectInfo:delete">
                            <Popconfirm
                                placement="topRight"
                                title="是否确认删除"
                                onConfirm={() => this.onDelete(record)}
                            >
                                <a>删除</a>
                            </Popconfirm>
                        </Auth>
                    </QueryTableActions>
                ),
            })
        }
    }
    /**
     * 阻止外部组件引发的渲染,提升性能
     * 可自行添加渲染条件
     * [必要]
     * @param {*} props
     * @param {*} state
     * @returns
     */
    shouldComponentUpdate(props, state) {
        return !isEqual(this.state, state)
    }

    /**
     * 加载字典数据,之后开始加载表格数据
     * 如果必须要加载字典数据,可直接对表格设置autoLoad=true
     */
    componentDidMount() {
        this.table.current.onLoading()
        getDictData('house_type').then(res => {
            this.setState(
                {
                    codes: res,
                },
                () => {
                    this.table.current.onLoadData()
                }
            )
        })
    }
    /**
     * 调用加载数据接口,可在调用前对query进行处理
     * [异步,必要]
     * @param {*} params
     * @param {*} query
     * @returns
     */
    loadData = async (params, query) => {
        query = {
            ...query,
            pid: this.selectCode,
        }
        //首次加载根据code列升序排序
        // if (!params.sortField) {
        //     params.sortField = 'code';
        //     params.sortOrder = 'ascend';
        // }
        const { data } = await apiAction.page({
            ...params,
            ...query,
        })
        return data
    }

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

    /**
     * 树节点选中事件
     * [必要]
     * @param {*} id
     */
    onSelectTree(code) {
        this.selectCode = code
        this.table.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 {*} record
     */
    onOpen(modal, id) {
        modal.current.open({
            pid: this.selectCode,
            // record,
            id,
        })
    }

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

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

    render() {
        return (
            <QueryTreeLayout
                loadData={this.loadTreeData}
                defaultExpanded={true}
                onSelect={key => this.onSelectTree(key)}
                replaceFields={{ value: 'code', title: 'name', children: 'children' }}
            >
                <Container mode="fluid">
                    <Card bordered={false}>
                        <QueryTable
                            ref={this.table}
                            autoLoad={false}
                            loadData={this.loadData}
                            columns={this.columns}
                            queryInitialValues={{
                                type: 1,
                            }}
                            onQueryChange={values => {
                                if (values.hasOwnProperty('type')) {
                                    this.setState({ type: values.type })
                                }
                            }}
                            query={
                                <Auth auth="houseProjectInfo:page">
                                    <Form.Item label="项目类型" name="type">
                                        <Radio.Group buttonStyle="solid">
                                            <Radio.Button value={0}>全部</Radio.Button>
                                            <Radio.Button value={1}>
                                                <span>住宅</span>
                                            </Radio.Button>
                                            <Radio.Button value={2}>
                                                <span>非住宅</span>
                                            </Radio.Button>
                                        </Radio.Group>
                                    </Form.Item>
                                    <Form.Item label="项目名称" name="name">
                                        <Input autoComplete="off" placeholder="请输入项目名称" />
                                    </Form.Item>
                                    <Form.Item label="项目备注" name="note">
                                        <Input autoComplete="off" placeholder="请输入项目备注" />
                                    </Form.Item>
                                </Auth>
                            }
                            operator={
                                <Auth auth="houseProjectInfo:add">
                                    <Button
                                        icon={<AntIcon type="plus" />}
                                        onClick={() => this.onOpen(this.addForm)}
                                    >
                                        新增{name}
                                    </Button>
                                </Auth>
                            }
                        ></QueryTable>
                    </Card>
                </Container>
                <ModalForm
                    title={`新增${name}`}
                    action={apiAction.add}
                    ref={this.addForm}
                    onSuccess={() => this.table.current.onReloadData()}
                >
                    <FormBody />
                </ModalForm>

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