import React, { Component } from 'react'
import {
    Button,
    Card,
    Drawer,
    Form,
    Input,
    message as Message,
    Popconfirm,
    Radio,
    Select,
    Tag,
} from 'antd'
import {
    AntIcon,
    Auth,
    Container,
    HouseLog,
    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 { getSearchInfo } from 'util/query'

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

/**
 * 配置页面所需接口函数
 */
const apiAction = {
    page: api.houseTaskPage,
}

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

export default class index extends Component {
    state = {
        codes: {
            status: [
                { code: 3, value: '审核中' },
                { code: 6, value: '审核通过' },
            ],
            houseType: [],
            houseIndustry: [],
        },

        type: '',

        visibleLog: false,
    }

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

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

    columns = [
        {
            title: '房屋编码',
            dataIndex: 'houseCode',
            sorter: true,
            width: 300,
            render: (text, record) => (
                <>
                    {`${record.areaName}-${record.roadName}-${record.commName}-${
                        record.fullProjName
                    }-${record.no.toString().padStart(3, '0')}`}
                    <br />
                    <Tag color="purple">{text}</Tag>
                </>
            ),
        },
        {
            title: '房屋性质及行业',
            dataIndex: 'type',
            sorter: true,
            width: 150,
            render: (text, record) =>
                this.bindCodeValue(text, 'house_type') +
                (text === 2 ? `(${this.bindCodeValue(record.industry, 'house_industry')})` : ''),
        },
        {
            title: '地址',
            dataIndex: 'address',
            sorter: true,
        },
        {
            title: '任务截止时间',
            dataIndex: 'endTime',
            sorter: true,
            width: 150,
        },
        {
            title: '审核状态',
            dataIndex: 'status',
            sorter: true,
            width: 100,
            render: text => this.bindCodeValue(text, 'status'),
        },
    ]

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

        const flag = auth({ houseInfo: 'getByTaskId' })

        if (flag) {
            this.columns.push({
                title: '操作',
                width: 150,
                dataIndex: 'actions',
                render: (text, record) => (
                    <QueryTableActions>
                        <Auth auth={{ houseInfo: 'getByTaskId' }}>
                            <a onClick={() => this.onOpen(record.id)}>
                                {record.state === 3 ? `审核` : `查看`}
                            </a>
                        </Auth>
                        <a onClick={() => this.onShowLog(record.id)}>日志</a>
                    </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('house_type', 'house_industry').then(codes => {
            this.setState({ codes: { ...this.state.codes, ...codes } }, () => {
                onLoadData()
            })
        })
    }

    /**
     * 调用加载数据接口,可在调用前对query进行处理
     * [异步,必要]
     * @param {*} params
     * @param {*} query
     * @returns
     */
    loadData = async (params, query) => {
        const searchInfo = getSearchInfo({
            query,
            queryType: {
                type: '=',
                industry: '=',
                address: 'like',
                houseCode: 'like',
                status: '=',
            },
        })

        const { data } = await apiAction.page({
            ...params,
            searchInfo,
        })
        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 {*} record
     */
    onOpen(taskId) {
        window.openContentWindow({
            title: '房屋登记',
            path: 'business/house/info/form',
            param: {
                taskId,
                table: this.table,
            },
        })
    }

    /**
     * 对表格上的操作进行统一处理
     * [异步]
     * @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()
        }
    }

    //#region 自定义方法
    onShowLog(id) {
        this.setState({ visibleLog: id })
    }
    //#endregion

    render() {
        const { codes, type, visibleLog } = this.state

        return (
            <Container mode="fluid">
                <br />
                <Card bordered={false}>
                    <QueryTable
                        ref={this.table}
                        autoLoad={false}
                        loadData={this.loadData}
                        columns={this.columns}
                        queryInitialValues={{
                            type: '',
                            status: '',
                        }}
                        onQueryChange={values => {
                            if (values.hasOwnProperty('type')) {
                                this.setState({ type: values.type })
                            }
                        }}
                        query={
                            <Auth auth={{ [authName]: 'page' }}>
                                <Form.Item label="房屋性质" name="type">
                                    <Radio.Group buttonStyle="solid">
                                        <Radio.Button value="">全部</Radio.Button>
                                        {codes.houseType.map(item => (
                                            <Radio.Button key={item.code} value={item.code}>
                                                {item.value}
                                            </Radio.Button>
                                        ))}
                                    </Radio.Group>
                                </Form.Item>
                                {type == 2 && (
                                    <Form.Item label="行业" name="industry">
                                        <Select
                                            allowClear
                                            className="w-150"
                                            placeholder="请选择行业"
                                        >
                                            {codes.houseIndustry.map(item => (
                                                <Select.Option key={item.code} value={item.code}>
                                                    {item.value}
                                                </Select.Option>
                                            ))}
                                        </Select>
                                    </Form.Item>
                                )}
                                <Form.Item label="地址" name="address">
                                    <Input autoComplete="off" placeholder="请输入地址" />
                                </Form.Item>
                                <Form.Item label="房屋唯一编码" name="houseCode">
                                    <Input autoComplete="off" placeholder="请输入房屋唯一编码" />
                                </Form.Item>
                                <Form.Item label="审核状态" name="status">
                                    <Radio.Group buttonStyle="solid">
                                        <Radio.Button value="">全部</Radio.Button>
                                        {codes.status.map(item => (
                                            <Radio.Button key={item.code} value={item.code}>
                                                {item.value}
                                            </Radio.Button>
                                        ))}
                                    </Radio.Group>
                                </Form.Item>
                            </Auth>
                        }
                    />
                </Card>

                <Drawer
                    width={600}
                    visible={visibleLog}
                    onClose={() => this.setState({ visibleLog: false })}
                    destroyOnClose
                >
                    <HouseLog taskId={visibleLog} />
                </Drawer>
            </Container>
        )
    }
}
