import React, { Component } from 'react'
import {
    Alert,
    Button,
    Card,
    Form,
    Input,
    InputNumber,
    message as Message,
    Popconfirm,
    Space,
    Tag,
    Typography,
} 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'

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

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

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

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

export default class score extends Component {
    state = {
        codes: {},

        disabled: true,
        saving: false,
    }

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

    stageForm = React.createRef()

    tableForm = React.createRef()

    columns = [
        {
            dataIndex: 'code',
            title: '机构备案编号',
            width: 120,
        },
        {
            dataIndex: 'name',
            title: '鉴定机构名称',
            width: 300,
            render: (text, record) => (
                <Space>
                    <span>{text}</span>
                    {!!record.isNew && <Tag color="green">NEW</Tag>}
                </Space>
            ),
        },
        {
            dataIndex: 'prevScoreResult',
            title: '往期名录信用评价',
            width: 120,
            render: text =>
                this.bindCodeValue(text || 0, 'inspection_dir_result', ({ value, extCode }) => {
                    return <Tag color={extCode && extCode.color}>{value}</Tag>
                }),
        },
        {
            dataIndex: 'score',
            title: '本期名录信用评分',
            width: 180,
            render: (text, record, index) => (
                <Form.Item noStyle name={[index, 'score']}>
                    <InputNumber placeholder="请输入信用评分" className="w-150" min={0} max={10} />
                </Form.Item>
            ),
        },
        {
            dataIndex: 'scoreResult',
            title: '本期名录信用评价结果',
            width: 120,
            render: (text, record, index) => (
                <>
                    <Form.Item noStyle name={[index, 'id']}>
                        {this.bindCodeValue(
                            text || 0,
                            'inspection_dir_result',
                            ({ value, extCode }) => {
                                return <Tag color={extCode && extCode.color}>{value}</Tag>
                            }
                        )}
                    </Form.Item>
                </>
            ),
        },
    ]

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

    /**
     * 加载字典数据,之后开始加载表格数据
     * 如果必须要加载字典数据,可直接对表格设置autoLoad=true
     */
    async componentDidMount() {
        const { onLoading, onLoadData } = this.table.current
        onLoading()

        const { data } = await api.inspectionOrgDirDetail()
        if (data) {
            this.stageForm.current.setFieldsValue(data)
        }

        getDictData('inspection_dir_result').then(codes => {
            this.setState({ codes }, () => {
                onLoadData()

                this.setState({
                    disabled: false,
                })
            })
        })
    }

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

        const values = {}
        data.forEach((item, index) => {
            values[index] = item
        })

        this.tableForm.current.setFieldsValue(values)

        return data
    }

    /**
     * 绑定字典数据
     * @param {*} code
     * @param {*} name
     * @returns
     */
    bindCodeValue(code, name, formatter) {
        name = toCamelCase(name)
        const codes = this.state.codes[name]
        if (codes) {
            const c = codes.find(p => p.code == code)
            if (c) {
                if (formatter) {
                    return formatter(c)
                } else {
                    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.delete({ id }), '删除成功')
    }

    //#region 自定义方法
    onChangeScore(key, changedValues, record) {
        const score = changedValues[key].score,
            codes = this.state.codes.inspectionDirResult
        let scoreResult = 0
        for (const code of codes) {
            if (code.extCode) {
                const { range } = code.extCode
                if (score >= range[0] && score < (range[1] || Infinity)) {
                    scoreResult = code.code
                    break
                }
            }
        }

        /**
         * 特殊逻辑处理
         * 如果往期和本期皆为黄牌,直接设定本期为红牌
         */
        if (record.prevScoreResult == 3 && scoreResult == 3) {
            scoreResult = 4
        }
        this.table.current.onChangeData(key, { scoreResult })
    }

    async onFinish(values) {
        const detail = [],
            scores = this.tableForm.current.getFieldsValue()

        for (const key in scores) {
            const item = scores[key]
            if (item.score !== null) {
                item.orgId = item.id
                detail.push(item)
            }
        }

        this.setState({ saving: true })
        try {
            await api.inspectionOrgDirSaveScore({
                ...values,
                detail,
            })

            Message.success('保存评价成功')
        } finally {
            this.setState({ saving: false })
        }
    }
    //#endregion

    render() {
        const { disabled, saving } = this.state

        return (
            <Container mode="fluid">
                <br />
                <Alert
                    type="info"
                    message={
                        <>
                            <Typography.Title level={5}>考核标准参考</Typography.Title>
                            <ul className="mb-none">
                                <li>考核结果评分10分的，信用评级为优秀</li>
                                <li>评分达到8分以上（含8分）、10分以下的，信用评级为合格</li>
                                <li>
                                    评分为6分以上（含6分）、8分以下的，挂黄牌警告，
                                    <span className="text-danger">
                                        连续两年挂黄牌警告的，将视作红牌
                                    </span>
                                </li>
                                <li>
                                    评分为6分以下的，
                                    <span className="text-danger">挂红牌，将移除鉴定机构名录</span>
                                </li>
                            </ul>
                        </>
                    }
                />
                <br />
                <Card bordered={false}>
                    <QueryTable
                        ref={this.table}
                        autoLoad={false}
                        loadData={this.loadData}
                        columns={this.columns}
                        query={<Auth auth={{ [authName]: 'listScore' }}></Auth>}
                        editable
                        form={this.tableForm}
                        formProps={{
                            onValuesChange: changedValues => {
                                Object.keys(changedValues).forEach(key => {
                                    this.onChangeScore(
                                        key,
                                        changedValues,
                                        this.table.current.getRecord(key)
                                    )
                                })
                            },
                        }}
                        operator={
                            <Auth auth={{ [authName]: 'saveScore' }}>
                                <Form
                                    layout="inline"
                                    ref={this.stageForm}
                                    onFinish={values => this.onFinish(values)}
                                >
                                    <Form.Item noStyle name="id">
                                        <Input type="hidden" />
                                    </Form.Item>
                                    <Form.Item
                                        label="期号"
                                        name="no"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入本期名录期号',
                                            },
                                        ]}
                                    >
                                        <Input
                                            autoComplete="off"
                                            placeholder="请输入本期名录期号"
                                            className="w-200"
                                        />
                                    </Form.Item>
                                    <Form.Item>
                                        <Button
                                            type="primary"
                                            htmlType="submit"
                                            icon={<AntIcon type="check" />}
                                            disabled={disabled}
                                            loading={saving}
                                        >
                                            保存评价
                                        </Button>
                                    </Form.Item>
                                </Form>
                            </Auth>
                        }
                    />
                </Card>
            </Container>
        )
    }
}
