/*
 * @Author: cclu
 * @Date: 2022-04-28 10:47:35
 * @LastEditTime: 2022-04-28 15:29:27
 * @LastEditors: Please set LastEditors
 * @Description: 我的权限组件
 * @FilePath: \cloud-platform\src\pages\account\center\components\Permission\index.tsx
 */
import type { FormInstance } from "antd";
import { Card, Col, message, Row, Tree } from "antd";
import { useRef, useState } from "react";
import { connect } from "umi";

import type { MenuDataItem } from '@ant-design/pro-layout';
import type { CommonTypeModel } from "@/services/options/typings";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import type { PermissionApplyModel, PermissionProinstModel } from "../../data";
import { createPermissionProInst } from "../../sevice";
import ProForm, { ProFormTextArea } from "@ant-design/pro-form";
import useRequest from "@ahooksjs/use-request";
import { getUserDetail } from "@/pages/Setting/Users/service";

// 参数定义
type MyPermissionProps = {
    myRoleTree: CommonTypeModel[],
    roleTree?: CommonTypeModel[],
    myMenu: MenuDataItem[],
    currentUser: CurrentUser | undefined,
    loading: boolean
}

// 提交权限变更审批单
const savePermissionProinst = async (fields: PermissionProinstModel) => {
    const hide = message.loading('正在提交...');

    const result = await createPermissionProInst(fields);
    hide();
    if (result.Result_Code !== 100) {
        message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`);
        return false;
    }
    message.success('提交审批成功！');
    return true;
};

/**
 * @description: 我的权限组件
 * @param {MyPermissionProps} 组件可接收的参数
 * @return {*}
 * @Date Changed:  2022/04/28
 */
const MyPermission: React.FC<MyPermissionProps> = ({ myRoleTree, roleTree, myMenu, loading, currentUser }: MyPermissionProps) => {
    const [changeStatus, setChangeStatus] = useState<boolean>(false) // 初始化显示状态 true 申请变更 false 查看
    const [checkedRole, setCheckedRole] = useState<[]>([]) // 初始化变更的角色状态 存储需要变更的角色ids
    const formRef = useRef<FormInstance>()
    // 获取我的角色 run: getMyRoles, 
    const { data: myRoles } = useRequest(async () => {

        const data = await getUserDetail(currentUser?.ID)
        setCheckedRole(data?.SystemRoleList)
        return data?.SystemRoleList

    }, { manual: true }) // 获取用户角色ids
    // 获取账号角色权限
    return (
        <Row gutter={16}>
            {!changeStatus 
                ? <>
                <Col span={8}>
                    {!loading && <Card
                        style={{ borderColor: "#97D6FE", height: 424 }}
                        size="small"
                        title="我的角色"
                        headStyle={{ backgroundColor: '#E7F7FF' }}
                    // extra={<a onClick={() => {
                    //     getMyRoles()
                    //     setChangeStatus(true)
                    // }}>申请变更角色</a>
                    // }
                    >
                        <Tree
                            treeData={myRoleTree}
                            height={360}
                            defaultExpandAll
                            fieldNames={{
                                title: 'label',
                            }}
                        ></Tree>
                    </Card>
                    }
                </Col>
                <Col span={8}>
                    <Card
                        style={{ borderColor: "#97D6FE", height: 424 }}
                        size="small"
                        title="我的模块权限"
                        headStyle={{ backgroundColor: '#E7F7FF' }}
                    >
                        <Tree
                            defaultExpandAll
                            treeData={myMenu || []}
                            height={360}
                            fieldNames={{
                                title: 'name',
                                children: 'routes'
                            }}
                        ></Tree>

                    </Card>
                </Col>
            </>
                : <>
                    <Col span={8}>
                        <ProForm<PermissionApplyModel>
                            formRef={formRef}
                            submitter={{
                                searchConfig: {
                                    resetText: '取消',
                                    submitText: '提交',
                                },
                                onReset: () => {
                                    setCheckedRole([])
                                    setChangeStatus(false)
                                }
                            }}
                            onFinish={async (values) => {
                                const newValue = {
                                    ...values,
                                    PERMISSIONAPPLY_TYPE: 2000,
                                    STAFF_ID: currentUser?.ID, // 操作人内码
                                    STAFF_NAME: currentUser?.Name, // 操作人员
                                    PERMISSIONAPPLY_STATE: 2000,
                                    SOURCE_PLATFORM: 1,
                                    PERMISSIONAPPLY_DATE: new Date(),
                                    OWNERUNIT_ID: currentUser?.OwnerUnitId
                                }
                                const applyRolesList = checkedRole.map(n => {
                                    return {
                                        PERMISSIONAPPLYDETAIL_TYPE: 2000,
                                        SYSTEMROLE_ID: n
                                    }
                                })

                                const originRoles = myRoles.map((m: any) => {
                                    return {
                                        PERMISSIONAPPLYDETAIL_TYPE: 1000,
                                        SYSTEMROLE_ID: m
                                    }
                                })
                                const success = await savePermissionProinst({
                                    PermissionApplyModel: newValue,
                                    PermissionApplyDetailList: [...applyRolesList, ...originRoles],
                                } as PermissionProinstModel)
                                if (success) {
                                    setChangeStatus(false)
                                    setCheckedRole([])
                                    formRef?.current?.resetFields()
                                    return true
                                }
                                return false
                            }}
                        >
                            <Card
                                style={{ borderColor: "#97D6FE", height: 424, marginBottom: 24 }}
                                size="small"
                                title="申请角色权限变更"
                                headStyle={{ backgroundColor: '#E7F7FF' }}
                            >
                                <Tree
                                    checkedKeys={checkedRole}
                                    defaultExpandAll
                                    treeData={roleTree || []}
                                    height={360}
                                    checkable
                                    fieldNames={{
                                        title: 'SYSTEMROLE_NAME',
                                        key: 'SYSTEMROLE_ID'
                                    }}
                                    onCheck={(checkedKeys: React.Key[] | any) => {
                                        setCheckedRole(checkedKeys)

                                        return checkedKeys
                                    }}
                                />
                            </Card>

                            <ProFormTextArea
                                name="PERMISSIONAPPLY_REASON"
                                label="变更原由"
                                placeholder="请输入变更原由"
                                rules={[
                                    {
                                        required: true,
                                        message: "请输入变更原由"
                                    }
                                ]}
                            />
                
                        </ProForm>
                    </Col>
                </>}
        </Row>
    );
}

export default connect(({ user, global }: ConnectState) => ({
    currentUser: user.currentUser,
    myMenu: global.menuData
}))(MyPermission);