import React, { Component } from 'react'
import {
    Button,
    Card,
    Checkbox,
    Col,
    DatePicker,
    Form,
    Input,
    InputNumber,
    message as Message,
    Row,
    Tag,
} from 'antd'
import {
    AntIcon,
    Auth,
    Container,
    InputNumberRange,
    QueryTable,
    QueryTableActions,
} from 'components'
import { api } from 'common/api'
import auth from 'components/authorized/handler'
import { first, isEqual, last } from 'lodash'
import getDictData from 'util/dic'
import { toCamelCase } from 'util/format'
import { getSearchDateRange, getSearchInfo, QueryType } from 'util/query'

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

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

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

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

export default class index extends Component {
    state = {
        codes: {
            houseStatus: [],
            houseType: [],
            houseIndustry: [],
            houseUsedStatus: [],
            housePropertyRights: [],
            landAttribute: [],
            houseBaseInfo: [],
            houseStructureType: [],
            houseStorageOfDrawings: [],
            houseGrade: [],
        },

        showDrawingMaterialText: 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.note
                    }-${record.no.toString().padStart(3, '0')}`}
                    <br />
                    <Tag color="purple">{text}</Tag>
                </>
            ),
        },
        {
            title: '房屋性质及行业',
            dataIndex: 'type',
            sorter: true,
            width: 150,
            render: text => this.bindCodeValue(text, 'house_type'),
        },
        {
            title: '地址',
            dataIndex: 'address',
            sorter: true,
        },
        {
            title: '建档状态',
            dataIndex: 'state',
            sorter: true,
            width: 100,
            render: text => this.bindCodeValue(text, 'house_status'),
        },
    ]

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

        const flag = auth({ [authName]: 'detail' })

        if (flag) {
            this.columns.push({
                title: '操作',
                width: 150,
                dataIndex: 'actions',
                render: (text, record) => (
                    <QueryTableActions>
                        <Auth auth={{ [authName]: 'detail' }}>
                            <a onClick={() => this.onOpen(record.id)}>查看</a>
                        </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(
            'house_status',
            'house_type',
            'house_industry',
            'house_used_status',
            'house_property_rights',
            'land_attribute',
            'house_base_info',
            'house_structure_type',
            'house_storage_of_drawings',
            'house_grade'
        ).then(codes => {
            this.setState({ codes }, () => {
                onLoadData()
            })
        })
    }

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

        const searchInfo = getSearchInfo({
            query,
            queryType: {
                areaCode: QueryType.Like,
                completedDate: [QueryType.GreaterThanOrEqual, QueryType.LessThan],
                createdTime: [QueryType.GreaterThanOrEqual, QueryType.LessThan],
                totalArea: [QueryType.GreaterThanOrEqual, QueryType.LessThanOrEqual],
                totalFloor: [QueryType.GreaterThanOrEqual, QueryType.LessThanOrEqual],
            },
        })

        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 {*} id
     */
    onOpen(id) {
        window.openContentWindow({
            title: '房屋详情',
            path: 'business/house/query/detail',
            param: { 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.delete({ id }), '删除成功')
    }

    //#region 自定义方法
    rednerMoreQuery() {
        const { codes, showDrawingMaterialText } = this.state

        return (
            <Row gutter={16}>
                <Col span={24}>
                    <Form.Item label="使用状态" name="houseUsedStatus">
                        <Checkbox.Group>
                            {codes.houseUsedStatus.map(item => (
                                <Checkbox key={item.code} value={+item.code}>
                                    {item.value}
                                </Checkbox>
                            ))}
                        </Checkbox.Group>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="有无幕墙" name="curtainWall">
                        <Checkbox.Group>
                            <Checkbox value="">全部</Checkbox>
                            <Checkbox value={0}>无</Checkbox>
                            <Checkbox value={1}>有</Checkbox>
                        </Checkbox.Group>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="有无面砖" name="faceBrick">
                        <Checkbox.Group>
                            <Checkbox value="">全部</Checkbox>
                            <Checkbox value={0}>无</Checkbox>
                            <Checkbox value={1}>有</Checkbox>
                        </Checkbox.Group>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="有无涂料" name="coating">
                        <Checkbox.Group>
                            <Checkbox value="">全部</Checkbox>
                            <Checkbox value={0}>无</Checkbox>
                            <Checkbox value={1}>有</Checkbox>
                        </Checkbox.Group>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="有无粉刷" name="painting">
                        <Checkbox.Group>
                            <Checkbox value="">全部</Checkbox>
                            <Checkbox value={0}>无</Checkbox>
                            <Checkbox value={1}>有</Checkbox>
                        </Checkbox.Group>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="安全管理员">
                        <Input autoComplete="off" placeholder="请输入安全管理员" />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="片区监管员">
                        <Input autoComplete="off" placeholder="请输入片区监管员" />
                    </Form.Item>
                </Col>
                <Col span={24}>
                    <Form.Item label="产权性质" name="propertyRights">
                        <Checkbox.Group>
                            <Checkbox value="">全部</Checkbox>
                            {codes.housePropertyRights.map(item => (
                                <Checkbox key={item.code} value={+item.code}>
                                    {item.value}
                                </Checkbox>
                            ))}
                        </Checkbox.Group>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="土地性质" name="landAttribute">
                        <Checkbox.Group>
                            <Checkbox value="">全部</Checkbox>
                            {codes.landAttribute.map(item => (
                                <Checkbox key={item.code} value={+item.code}>
                                    {item.value}
                                </Checkbox>
                            ))}
                        </Checkbox.Group>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="基础情况" name="baseInfo">
                        <Checkbox.Group>
                            <Checkbox value="">全部</Checkbox>
                            {codes.houseBaseInfo.map(item => (
                                <Checkbox key={item.code} value={+item.code}>
                                    {item.value}
                                </Checkbox>
                            ))}
                        </Checkbox.Group>
                    </Form.Item>
                </Col>
                <Col span={24}>
                    <Form.Item label="结构类型" name="structureType">
                        <Checkbox.Group>
                            <Checkbox value="">全部</Checkbox>
                            {codes.houseStructureType.map(item => (
                                <Checkbox key={item.code} value={+item.code}>
                                    {item.value}
                                </Checkbox>
                            ))}
                        </Checkbox.Group>
                    </Form.Item>
                </Col>
                <Col span={24}>
                    <Form.Item label="图纸资料存档处" name="drawingMaterial">
                        <Form.Item name="drawingMaterial" className="mb-none">
                            <Checkbox.Group>
                                {codes.houseStorageOfDrawings.map(item => (
                                    <Checkbox key={item.code} value={item.code}>
                                        {item.value}
                                    </Checkbox>
                                ))}
                            </Checkbox.Group>
                        </Form.Item>
                        {showDrawingMaterialText && (
                            <Form.Item name="drawingMaterialText" className="mb-none mt-xs">
                                <Input.TextArea autoSize placeholder="请输入其他图纸资料存档处" />
                            </Form.Item>
                        )}
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="竣工日期" name="completedDate">
                        <DatePicker.RangePicker
                            className="w-100-p"
                            placeholder={['请选择竣工开始日期', '请选择竣工结束日期']}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="填表日期" name="createdTime">
                        <DatePicker.RangePicker
                            className="w-100-p"
                            placeholder={['请选择填表开始日期', '请选择填表结束日期']}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="总建筑面积" name="totalArea">
                        <InputNumberRange
                            min={0}
                            unit="m²"
                            placeholder={['请输入最小总建筑面积', '请输入最大总建筑面积']}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="总层数" name="totalFloor">
                        <InputNumberRange
                            min={0}
                            precision={0}
                            step={1}
                            unit="层"
                            placeholder={['请输入最小总层数', '请输入最大总层数']}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="建设单位" name="buildingUnit">
                        <Input autoComplete="off" placeholder="请输入建设单位" />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="设计单位" name="desingerUnit">
                        <Input autoComplete="off" placeholder="请输入设计单位" />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="施工单位" name="constructionUnit">
                        <Input autoComplete="off" placeholder="请输入施工单位" />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="监理单位" name="monitorUnit">
                        <Input autoComplete="off" placeholder="请输入监理单位" />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="产权单位" name="propertyUnit">
                        <Input autoComplete="off" placeholder="请输入产权单位" />
                    </Form.Item>
                </Col>
                <Col span={24}>
                    <Form.Item label="综合等级" name="houseGrade">
                        <Checkbox.Group>
                            <Checkbox value="">全部</Checkbox>
                            {codes.houseGrade.map(item => (
                                <Checkbox key={item.code} value={+item.code}>
                                    {item.value}
                                </Checkbox>
                            ))}
                        </Checkbox.Group>
                    </Form.Item>
                </Col>
            </Row>
        )
    }

    onQueryChange(changedValues, allValues) {
        console.log(changedValues)
        if (changedValues.hasOwnProperty('drawingMaterial') && changedValues.drawingMaterial) {
            this.setState({
                showDrawingMaterialText: changedValues.drawingMaterial.includes('100'),
            })
            return
        }

        // 全部
        const { codes } = this.state
        const key = first(Object.keys(changedValues))
        const mapCount = {
            curtainWall: 2,
            faceBrick: 2,
            coating: 2,
            painting: 2,
            propertyRights: codes.housePropertyRights.length,
            landAttribute: codes.landAttribute.length,
            baseInfo: codes.houseBaseInfo.length,
            structureType: codes.houseStructureType.length,
            houseGrade: codes.houseGrade.length,
        }
        if (Object.keys(mapCount).includes(key)) {
            return {
                [key]: this.checkedNone(changedValues[key], mapCount[key]),
            }
        }
    }

    checkedNone(value, count) {
        if (first(value) == '' && value.length > 1) {
            // 在'无'之后选中其他值
            value.shift()
        } else if ((last(value) == '' && value.length > 1) || value.length === count) {
            // 在其他值之后选中'无'
            value = ['']
        }
        return value
    }
    //#endregion

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

        return (
            <Container mode="fluid">
                <br />
                <Card bordered={false}>
                    <QueryTable
                        ref={this.table}
                        autoLoad={false}
                        loadData={this.loadData}
                        columns={this.columns}
                        queryInitialValues={{
                            houseUsedStatus: [1, 2],
                            curtainWall: [''],
                            faceBrick: [''],
                            coating: [''],
                            painting: [''],
                            propertyRights: [''],
                            landAttribute: [''],
                            baseInfo: [''],
                            structureType: [''],
                            houseGrade: [''],
                        }}
                        query={
                            <Auth auth={{ [authName]: 'page' }}>
                                <Form.Item label="地址" name="address">
                                    <Input autoComplete="off" placeholder="请输入地址" />
                                </Form.Item>
                                <Form.Item label="房屋唯一编码" name="houseCode">
                                    <Input autoComplete="off" placeholder="请输入房屋唯一编码" />
                                </Form.Item>
                            </Auth>
                        }
                        moreQuery={
                            <Auth auth={{ [authName]: 'page' }}>{this.rednerMoreQuery()}</Auth>
                        }
                        onQueryChange={(changedValues, allValues) =>
                            this.onQueryChange(changedValues, allValues)
                        }
                        operator={
                            <Auth auth={{ [authName]: 'add' }}>
                                <Button
                                    icon={<AntIcon type="plus" />}
                                    onClick={() => this.onOpen(this.addForm)}
                                >
                                    新增{name}
                                </Button>
                            </Auth>
                        }
                    />
                </Card>
            </Container>
        )
    }
}
