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

/**
 * 注释段[\/**\/]为必须要改
 */

/**
 * 配置页面所需接口函数
 */
const apiAction = {
    page: api.sysNoticePage,
    add: api.sysNoticeAdd,
    edit: api.sysNoticeEdit,
    delete: api.sysNoticeDelete,
    Detail: api.sysNoticeDetail,
    Status: api.sysNoticeChangeStatus,
}

/**
 * 用于弹窗标题
 * [必要]
 */
const name = '通知公告'

/**
 * 统一配置权限标识
 * [必要]
 */
const authName = '/**/'

export default class index extends Component {
    state = {
        codes: {
            noticeStatus: [],
            noticeType: [],
        },
    }

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

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

    columns = [
        {
            title: '标题',
            dataIndex: 'title',
        },
        {
            title: '发布人',
            dataIndex: 'publicUserName',
        },
        {
            title: '发布时间',
            dataIndex: 'createdTime',
        },
        {
            title: '发布单位',
            dataIndex: 'publicOrgName',
            width: 200,
        },
        {
            title: '类型',
            dataIndex: 'type',
            render: text => this.bindCodeValue(text, 'notice_type'),
        },
        {
            title: '状态',
            dataIndex: 'status',
            render: text => this.bindCodeValue(text, 'notice_status'),
        },
    ]

    /**
     * 构造函数,在渲染前动态添加操作字段等
     * @param {*} props
     */
    constructor(props) {
        super(props)

        const flag = auth({ [authName]: [['edit'], ['goBack'], ['publish'], ['delete']] })

        if (flag) {
            this.columns.push({
                title: '操作',
                width: 150,
                dataIndex: 'actions',
                render: (text, record) => (
                    <QueryTableActions>
                        {record.status === 1 ? (
                            <Auth
                                key={this.subUniqueKey(record.id, 1)}
                                auth={{ [authName]: 'goBack' }}
                            >
                                <Popconfirm
                                    placement="topRight"
                                    title="是否确认撤回"
                                    onConfirm={() => this.onGoBack(record.id)}
                                >
                                    <a>撤回</a>
                                </Popconfirm>
                            </Auth>
                        ) : (
                            [
                                <Auth
                                    key={this.subUniqueKey(record.id, 2)}
                                    auth={{ [authName]: 'edit' }}
                                >
                                    <a onClick={() => this.onOpen(this.editForm, record.id)}>
                                        编辑
                                    </a>
                                </Auth>,
                                <Auth
                                    key={this.subUniqueKey(record.id, 3)}
                                    auth={{ [authName]: 'publish' }}
                                >
                                    <Popconfirm
                                        placement="topRight"
                                        title="是否确认发布"
                                        onConfirm={() => this.onPublish(record.id)}
                                    >
                                        <a>发布</a>
                                    </Popconfirm>
                                </Auth>,
                                <Auth
                                    key={this.subUniqueKey(record.id, 4)}
                                    auth={{ [authName]: 'delete' }}
                                >
                                    <Popconfirm
                                        placement="topRight"
                                        title="是否确认删除"
                                        onConfirm={() => this.onDelete(record.id)}
                                    >
                                        <a>删除</a>
                                    </Popconfirm>
                                </Auth>,
                            ]
                        )}
                    </QueryTableActions>
                ),
            })
        }
    }

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

    /**
     * 加载字典数据,之后开始加载表格数据
     * 如果必须要加载字典数据,可直接对表格设置autoLoad=true
     */
    componentDidMount() {
        const { onLoading, onLoadData } = this.table.current
        onLoading()
        getDictData('notice_status', 'notice_type').then(codes => {
            this.setState({ codes }, () => {
                onLoadData()
            })
        })
    }
    subUniqueKey(text, index) {
        return text.substr(index, 5)
    }
    /**
     * 调用加载数据接口,可在调用前对query进行处理
     * [异步,必要]
     * @param {*} params
     * @param {*} query
     * @returns
     */
    loadData = async (params, query) => {
        const { data } = await apiAction.page({
            ...params,
            ...query,
        })
        return data
    }

    /**
     * 绑定字典数据
     * @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({
            id,
        })
    }

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

    /**
     * 删除
     * @param {*} id
     */
    onDelete(id) {
        this.onAction(apiAction.Status({ id, Status: 3 }), '删除成功')
    }
    /**
     * 发布
     * @param {*} id
     */
    onPublish(id) {
        this.onAction(apiAction.Status({ id, Status: 1 }), '发布成功')
    }
    /**
     * 撤回
     * @param {*} id
     */
    onGoBack(id) {
        this.onAction(apiAction.Status({ id, Status: 2 }), '撤回成功')
    } //

    //#region 自定义方法
    //#endregion

    render() {
        const { codes } = this.state
        return (
            <Container mode="fluid">
                <br />
                <Card bordered={false}>
                    <QueryTable
                        ref={this.table}
                        rowkey={record => record.id}
                        autoLoad={false}
                        loadData={this.loadData}
                        columns={this.columns}
                        query={
                            <Auth auth={{ [authName]: 'page' }}>
                                <Form.Item label="关键字" name="searchValue">
                                    <Input
                                        autoComplete="off"
                                        placeholder="请输入标题、内容"
                                        className="w-200"
                                    />
                                </Form.Item>
                                <Form.Item label="类型" name="type">
                                    <Select placeholder="请选择类型" className="w-200" allowClear>
                                        {codes.noticeType.map(item => (
                                            <Select.Option key={item.code} value={item.code}>
                                                {item.value}
                                            </Select.Option>
                                        ))}
                                    </Select>
                                </Form.Item>
                            </Auth>
                        }
                        operator={
                            <Auth key={record => record.id} auth={{ [authName]: 'add' }}>
                                <Button
                                    icon={<AntIcon type="plus" />}
                                    onClick={() => this.onOpen(this.addForm)}
                                >
                                    新增{name}
                                </Button>
                            </Auth>
                        }
                    />
                </Card>

                <Auth auth={{ [authName]: 'add' }}>
                    <ModalForm
                        title={`新增${name}`}
                        width={800}
                        action={apiAction.add}
                        buttons={[
                            {
                                index: 1,
                                button: (getData, close) => (
                                    <Button
                                        type="primary"
                                        key="111"
                                        onClick={async () => {
                                            const data = await getData()
                                            data.status = 0 //草稿状态
                                            this.onAction(api.sysNoticeAdd(data))
                                            close()
                                        }}
                                    >
                                        保存草稿
                                    </Button>
                                ),
                            },
                        ]}
                        ref={this.addForm}
                        onSuccess={() => this.table.current.onReloadData()}
                    >
                        <FormBody />
                    </ModalForm>
                </Auth>

                <Auth auth={{ [authName]: 'edit' }}>
                    <ModalForm
                        title={`编辑${name}`}
                        width={800}
                        action={apiAction.edit}
                        ref={this.editForm}
                        onSuccess={() => this.table.current.onReloadData()}
                    >
                        <FormBody />
                    </ModalForm>
                </Auth>
            </Container>
        )
    }
}
