import './style.less'
import React from "react";
import numeral from 'numeral';
import ProCard from "@ant-design/pro-card";
import ProTable from "@ant-design/pro-table";
import useRequest from "@ahooksjs/use-request";

import { useRef, useState } from "react";
import { MenuFoldOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-layout";
import { Descriptions, Drawer, Tree, Typography } from "antd";

import type { CommonTypeModel } from '@/services/options/typings';
import type { ActionType, ProColumns } from "@ant-design/pro-table";
import type { BusinessProjectModel } from "./data";

import { getFieldEnum, getServerpartTree } from "@/services/options";
import { getProjectList } from "./service";
import { contractType } from "../contract/emun";
import ProjectDetail from './detail'
import PageTitleBox from '@/components/PageTitleBox';
import { CurrentUser } from 'umi';
import LeftSelectTree from '../reports/settlementAccount/component/leftSelectTree';

const { Text } = Typography;

// 标题金额拆分小数点前后显示大小
const amountDom = (value: any) => {
    const stringValue = `${value}`
    const [intValue, floatValue] = stringValue.split(".")
    return floatValue ?
        <><Text type="warning" style={{
            fontSize: 36, lineHeight: 1,
            fontFamily: "Bahnschrift Regular"
        }}>{numeral(intValue || 0).format("0,0")}</Text><Text type="warning" style={{
            fontSize: 18,
            fontFamily: "Bahnschrift Regular"
        }}>.{floatValue}</Text>
            <Text type="warning" style={{ fontSize: 14 }}></Text></>
        :
        <><Text type="warning" style={{
            fontSize: 36, lineHeight: 1,
            fontFamily: "Bahnschrift Regular"
        }}>{intValue}</Text><Text type="warning" style={{ fontSize: 14 }}></Text></>
}

// 经营项目查询列表
/**
 * @description: 生成服务区左侧菜单
 * @param {ServerpartTree[]} data 菜单数据源
 * @param {Function} callback 点击菜单回调函数
 * @return {JSX.Element[]} 返回jsx数据节点集
 */
// 项目页面主体
// const ProjecetTable: React.FC = () => {
const ProjecetTable: React.FC<{ currentUser?: CurrentUser }> = (props) => {
    const { currentUser } = props


    // props
    // useState 为umi封装的hooks方法
    const [currentRow, setCurrentRow] = useState<BusinessProjectModel | any>(undefined) // 选中的当前行
    const [showDetail, setShowDetail] = useState<boolean>(false) // 是否显示详情
    const actionRef = useRef<ActionType>() // 项目列表对象
    const [reqDetailList, setReqDetailList] = useState<CommonTypeModel[]>(); // 合计项数据源

    // 请求服务区树列表
    const { loading: treeLoading, data: treeView } = useRequest(async () => { return getServerpartTree() })
    const [collapsible, setCollapsible] = useState<boolean>(false)
    const [selectedId, setSelectedId] = useState<string>()
    // 项目列表 列数据配置
    const columns: ProColumns<BusinessProjectModel>[] = [
        {
            title: '查询项目',
            dataIndex: 'searchKey',
            hideInTable: true,
            hideInDescriptions: true,
            fieldProps: {
                placeholder: "请输入项目/商户名称/备注"
            },
            colSize: 2,
        },
        {
            title: '项目名称',
            dataIndex: 'BUSINESSPROJECT_NAME',
            ellipsis: true,
            hideInDescriptions: true,
            width: '24%',
            render: (_, record) => {
                return <a onClick={() => { // 点击项目名称时 打开抽屉 展示项目详情
                    setCurrentRow(record)
                    setShowDetail(true)
                }}>{record.BUSINESSPROJECT_NAME}</a>

            },
            hideInSearch: true,
        },
        {
            title: '经营模式',
            dataIndex: 'BUSINESS_TYPE',
            valueType: 'select',
            valueEnum: contractType,
            width: 110,
            align: "center",
            // hideInSearch: true,
        },
        {
            dataIndex: 'SETTLEMENT_MODES',
            title: '结算模式',
            valueType: 'select',
            align: 'center',
            width: 120,
            request: async () => {
                return await getFieldEnum({ FieldExplainField: 'SETTLEMENT_MODES' });
            },
            initialValue: 3000,
        },
        {
            dataIndex: 'ROYALTY_PRICE',
            title: '业主分润',
            valueType: "money",
            align: 'right',
            width: 110,
            hideInTable: true,
            hideInSearch: true,
            sorter: true,
        },
        {
            dataIndex: 'EXPIREDAYS',
            title: '预估到期',
            align: 'center',
            width: 110,
            hideInTable: true,
            hideInSearch: true,
            sorter: true,
            render: (_) => {
                return _ === '0' ? '已达保底' : _
            },
        },
        {
            dataIndex: 'EXPIREDAYS',
            title: '完成保底',
            align: 'center',
            valueType: 'select',
            hideInSearch: true,
            valueEnum: {
                '-1': { text: '本月未完成' },
                '0': { text: '本月完成' },
                '1': { text: '已切换' }
            },
            hideInTable: true,
        },
        {
            title: '项目金额(万元)',
            dataIndex: 'GUARANTEE_PRICE',
            align: 'right',
            sorter: true,
            valueType: "digit",
            render: (_) => {
                return <span style={{ paddingRight: 20 }}>{_}</span>
            },
            width: 130,
            hideInSearch: true,

            // hideInTable: true
        },
        {
            title: '经营商户',
            dataIndex: 'MERCHANTS_NAME',
            ellipsis: true,
            width: '22%',
            hideInSearch: true,
        },

        {
            title: '开始日期',
            hideInSearch: true,
            dataIndex: 'PROJECT_STARTDATE',
            valueType: 'date',
            sorter: true,
            // defaultSortOrder: 'descend',
            width: 120
        },
        {
            title: '结束日期',
            hideInSearch: true,
            dataIndex: 'PROJECT_ENDDATE',
            valueType: 'date',
            sorter: true,
            width: 120
        },
    ];

    return (
        <div >
            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <LeftSelectTree setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} />

                <div style={{
                    width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    {/* 项目页面 表格主体 */}
                    <ProTable<BusinessProjectModel>
                        headerTitle={<PageTitleBox props={props} />}
                        rowKey="BUSINESSPROJECT_ID"
                        request={async (params, sorter) => { // 请求项目表格数据 params 查询对象键值对；sorter 排序对象键值对
                            // 排序对象键值对 有值 则调整成后台接口需要的数据格式
                            const sortstr = Object.keys(sorter).map(n => {
                                const value = sorter[n]
                                return value ? `${n} ${value.replace('end', '')}` : ''
                            })
                            // 发起请求，return 请求返回的数据
                            const list = await getProjectList({
                                ...params, PROJECT_VALID: 1, SERVERPART_IDS: selectedId || '0', ShowShare: true,
                                sortstr: sortstr.length ? sortstr.toString() : params?.sortstr,
                                keyWord: params.searchKey ? { key: "BUSINESSPROJECT_NAME,BUSINESSPROJECT_DESC,MERCHANTS_NAME", value: params.searchKey } : null, // 关键词查询
                                pagesize: params.pageSize
                            })
                            if (params && (params.SETTLEMENT_MODES === 3000 || params.SETTLEMENT_MODES === 4000) && list && list?.otherData) {
                                setReqDetailList(list?.otherData)
                            }
                            else {
                                setReqDetailList(undefined)
                            }

                            return list
                        }}
                        actionRef={actionRef} // 表格操作对象
                        search={{ span: 4, labelWidth: 'auto' }} // 查询栏布局配置按照24/6=4份来分割
                        columns={columns}  // 表格列数据配置
                        // tableExtraRender={() => {
                        //     if (reqDetailList && reqDetailList.length > 0) {
                        //         const reduceData = reqDetailList.reduce((p: {
                        //             Data_1000: number, Data_2000: number, Data_3000: number, Data_4000: number
                        //         }, currentValue: CommonTypeModel) => {
                        //             const previousValue = { ...p }
                        //             switch (currentValue.label) {
                        //                 case '1000':
                        //                     previousValue.Data_1000 = numeral(numeral(
                        //                         (currentValue?.value || 0)).format('0.00')).value();
                        //                     break;
                        //                 case '2000':
                        //                     previousValue.Data_2000 = numeral(numeral(
                        //                         (currentValue?.value || 0)).format('0.00')).value();
                        //                     break;
                        //                 case '3000':
                        //                     previousValue.Data_3000 = numeral(numeral(
                        //                         (currentValue?.value || 0)).format('0.00')).value();
                        //                     break;
                        //                 case '4000':
                        //                     previousValue.Data_4000 = numeral(numeral(
                        //                         (currentValue?.value || 0)).format('0.00')).value();
                        //                     break;
                        //                 default:
                        //                     break;
                        //             }
                        //             return previousValue
                        //         }, {
                        //             Data_1000: 0, Data_2000: 0, Data_3000: 0, Data_4000: 0
                        //         });
                        //         return <div style={{ paddingLeft: 24 }}>
                        //             <Descriptions column={5} className="commity-sale-description"
                        //                 contentStyle={{ fontSize: 14, color: "#00000073" }} labelStyle={{ color: "#00000073" }}
                        //             >
                        //                 <Descriptions.Item label="">分润项目：{amountDom(reduceData.Data_1000)}</Descriptions.Item>
                        //                 <Descriptions.Item label="">已切换：{amountDom(reduceData.Data_2000)}</Descriptions.Item>
                        //                 <Descriptions.Item label="">本月完成保底：{amountDom(reduceData.Data_3000)}</Descriptions.Item>
                        //                 <Descriptions.Item label="">业主分润：¥{amountDom(reduceData.Data_4000.toFixed(2))}</Descriptions.Item>
                        //             </Descriptions>
                        //         </div>
                        //     }
                        //     return <></>
                        // }}
                        pagination={{ defaultPageSize: 10 }} // 翻页默认10条分页
                    />
                </div>

                {/* 查看项目详情 右侧弹出的抽屉 */}
                <Drawer
                    width="80%"
                    className="project-drawer"
                    visible={showDetail} // 抽屉弹框是否显示状态
                    onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
                        setCurrentRow(undefined);
                        setShowDetail(false);
                    }}
                    bodyStyle={{ backgroundColor: "#f9f9f9", padding: 0 }}
                    closable={false}
                >
                    {/* 抽屉打开时 加载项目详情组件 */}
                    {showDetail && <ProjectDetail id={currentRow?.BUSINESSPROJECT_ID} editable={false} showType={'search'}
                        tabActive={currentRow?.SETTLEMENT_MODES === 3000 || currentRow?.SETTLEMENT_MODES === 4000 ? '7' : ''}></ProjectDetail>}
                </Drawer>
            </div>
        </div>
    );
}

export default ProjecetTable;
